Django 在视图中保存调用 api 的数据



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

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

这是我的视图将 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')

您首先必须从响应中提取数据。如果您使用的是requests库,并且您调用的 API 正在以 JSON 为单位进行响应,则可以执行类似 data = r.json() 的操作。

不过,我不知道第二个 API 响应的结构,但我认为您可以从data对象获取字段。

然后,使用您正在使用的任何数据库接口保存您想要的内容。如果是 django ORM,并且你在某处有一个Appointement模型,你可以做类似的事情

Appointment(
    clinic_id=data["clinic_id"], 
    time=data["time"], 
    queueNo=data["queueNo"]
).save()

你完成了...

最新更新