我正在创建一个 API 端点来接收数据并根据所述数据创建模型对象。我目前有这个 API 的两个视图——一个发送数据,一个接收数据——但实际上,我将使用脚本而不是视图来发送数据。我正在处理视图以在我的本地主机上接收数据,这就是为什么我现在有了发送它的那个。
我面临的当前问题是将数据发送到 API 端点的函数。我的 POST 请求返回 403 错误并显示Forbidden (CSRF cookie not set.): /reports/swipe/data
。为了解决这个问题,我尝试添加一个 CSRF cookie,但我对 API 端点非常陌生,并且遇到了一些麻烦。我已经尝试过使用@csrf_exempt
和添加verify=False
其他东西,但我还没有取得任何成功。我还花了几个小时在网上搜索可以提供帮助的资源。以下是我的部分代码。我会很感激人们可以提供的任何建议。
视图.py:
from datetime import datetime, timedelta, date, time
import time
import datetime
import json
import os
from django.shortcuts import render
from swipe.models import MyModel
import requests
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
def receive_data(request):
"""
we need the primary keys of the id rows in case they send us the same data twice
or we don't even run it and need to run it on new data every time
get primary key of each row in the original query to have that sent to us as well
create --> update | create
"""
if request.method == 'POST':
bb_data = request.POST.get('data', '')
for entry in bb_data:
print(entry)
new_swipe = MyModel.objects.create(
eventtransactions_id= int(entry['eventtransactions_id']),
customer_lastname= entry['customer_lastname'],
customer_firstname= entry['customer_firstname'],
birthdate= datetime.datetime.strptime(entry['birthdate'], '%m-%d-%Y'),
customer_gender= entry['customer_gender'],
)
print("ENTRY CREATED") #for testing
@csrf_exempt
def send_data(request):
API_ENDPOINT = "http://127.0.0.1:8000/my_api"
for x in range(3):
bb_dict = {
'eventtransactions_id': 0000111,
'customer_gender': 'F',
'customer_firstname': 'Jan',
'customer_lastname': 'Smith',
'birthdate': datetime.datetime(2000, 2, 10, 10, 23, 40, 123443),
}
json_bb_dict = json.dumps(bb_dict, default=str)
requests.post(API_ENDPOINT, data=json_bb_dict, verify=False)
return HttpResponse("Test")
网址.py
from django.conf.urls import include, url
from swipe.views import receive_data, send_data
urlpatterns = [
url(r'^data', receive_data, name='data_import'),
url(r'^test', send_data, name='data_export'),
]