Skip to main content
 首页 » 编程设计

python之Django 在 View 中通过调用 api 保存数据

2025年05月04日36tintown

所以我有一个 View ,其中有一个调用另一个 Django 项目 API 的 Get 和 Post 请求。但我还想保存从 api 调用中获得的信息。

项目 1 有一个预约表,其中包含这些字段 clinic Id、time 和 queueNo。当我向项目 2 发出发布请求以创建/创建约会时,成功创建后,它将显示我想保存到项目 1 约会表数据库中的那 3 个字段。我该怎么做 ?我的约会也有一个 API,那么我该如何将它保存在那里?

这是我的 View 调用api到另一个django项目的代码

views.py

@csrf_exempt 
def my_django_view(request): 
    if request.method == 'POST': 
        r = requests.post('http://127.0.0.1:8000/api/test/', data=request.POST) 
    else: 
        r = requests.get('http://127.0.0.1:8000/api/test/', data=request.GET) 
    if r.status_code == 200: 
        # r.text, r.content, r.url, r.json 
        return HttpResponse(r.text) 
    return HttpResponse('Could not save data') 

请您参考如下方法:

假设您在项目 2 中的端点返回一个包含您需要的字段的 JSON 响应:

{ 
    "clinicId": 1, 
    "time": some-time-string, 
    "queueNo": 2 
} 

您可以在发出请求后通过调用 r.json() 检索响应。

基于此,您可以将 r.json() 视为字典并使用 Appointment.objects.create(**r.json()) 创建实例>。它可能是这样的。

@csrf_exempt 
def my_django_view(request): 
    if request.method == 'POST': 
        r = requests.post('http://127.0.0.1:8000/api/test/', data=request.POST) 
    else: 
        r = requests.get('http://127.0.0.1:8000/api/test/', data=request.GET) 
 
    if r.status_code == 200 and request.method == 'POST': 
        # Convert response into dictionary and create Appointment 
        data = r.json() 
        # Construct required dictionary 
        appointment_attrs = { 
            "clinicId": data["some-key-that-points-to-clinicid"], 
            "time": data["some-key-that-points-to-time"], 
            "queueNo": data["some-key-that-points-to-queue-num"] 
        } 
        appointment = Appointment.objects.create(**appointment_attrs) 
        # r.text, r.content, r.url, r.json 
        return HttpResponse(r.text) 
    elif r.status_code == 200:  # GET response 
        return HttpResponse(r.text) 
 
    return HttpResponse('Could not save data')