所以我有一个 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')
关于python - Django 在 View 中通过调用 api 保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48414202/