gpt4 book ai didi

python - 使用 Python-Requests 发送带有 Django View 的请求

转载 作者:行者123 更新时间:2023-12-04 12:59:53 27 4
gpt4 key购买 nike

我正在尝试在我的 Django 项目上创建一个简单的微服务结构:因此,当调用某个 Django View 时,该 View 将向包含一些用户数据的 Flask 微服务发送一个 JSON 发布请求; Flask 微服务应该接收请求,获取该用户的数据并再次使用请求将一些额外的数据发送回 Django,以便我的 Django View 可以接收该数据并执行一些操作,例如将其显示给用户。

现在我只是发送一些虚拟数据,以测试整个系统(Django > request to Flask > Flask > Request to Django)是否有效,但我遇到了一些问题。

为了调试我的代码,我试图只打印接收到的数据。这是我的观点:

def myView(request):

mydict = {}

# The request is sent to my external Python script..
req = requests.post('http://127.0.0.1:5000/', json={"one": 1}) # Some dummy data

# .. Once the external script sends back a request with data, this should handle it
if request.method == 'POST':

# The data is inside this variable
data = request.POST

for key in data.items():
if float(key[1]) > 0:
mydict.update({key[0]: key[1]})

print(mydict) #FIRST PRINT STATEMENT

print(mydict) #SECOND PRINT STATEMENT
response = HttpResponse(get_token(request))
return JsonResponse(mydict) #RETURNS "{}"

下面是我的 Flask 应用程序如何使用 Python-Requests 库发送数据(一旦它从 Django View 接收到 POST 请求):
@app.route("/", methods=["GET","POST"])
def test():
# After the request from the VIEW is received, a request containing some random json data
# is sent to Django
url = 'http://127.0.0.1:8000/myView/'
client = requests.session()

# We need to get the CSRF token, in order for the request to be taken by Django
csrftoken = requests.get(url).cookies['csrftoken']
data = {"two": 2}

header = {'X-CSRFToken': csrftoken}
cookies = {'csrftoken': csrftoken}
resp = requests.post(url, data=data, headers=header, cookies=cookies)
# Let's seend the request to Django

return f"Test!"

这是我的代码有什么问题:
METHOD:  POST
{'two': 2}
[10/Jan/2020 10:41:37] "POST /myView/ HTTP/1.1" 200 320
{}
[10/Jan/2020 10:41:37] "GET /myView/ HTTP/1.1" 200 2

这是出了什么问题:
为什么第一个打印语句返回正确的数据,为什么第二个打印不正确?为什么 return JsonResponse返回一个空字典?

我试图添加 print('METHOD: ', request.method)在 View 的第一行中,发生了以下情况:
METHOD:  GET
METHOD: GET
[10/Jan/2020 10:46:22] "GET /myView/ HTTP/1.1" 200 2
METHOD: POST
[10/Jan/2020 10:46:26] "POST /myView/ HTTP/1.1" 200 320
[10/Jan/2020 10:46:26] "GET /myView/ HTTP/1.1" 200 2

最佳答案

你的 flask View 可以简化为只返回所需的数据

@app.route("/", methods=["GET","POST"])
def test():
return {"two": 2}

然后你可以在向flask发出请求后使用Django View 中的数据
response = requests.post('http://127.0.0.1:5000/', json={"one": 1})
print(response.json()) # This should contain the returned data

关于python - 使用 Python-Requests 发送带有 Django View 的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59694402/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com