从请求瓶获取json [英] Get json from request flask

查看:113
本文介绍了从请求瓶获取json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

客户代码:

import requests
import json

url = 'http://127.0.0.1:5050/login'
user = "newUser"
password = "password"
headers = {'content-type': 'application/json'}
response = requests.post(url, data={"user": user,"pass": password}, headers = headers)

服务器代码:

from flask import Flask, request, make_response

app = Flask(__name__)


@app.route('/login', methods=['GET','POST'])
def login():    
 if request.method == 'POST':

    username = request.form.get("user")
    password = request.form.get("pass")
    //more code
    return make_response("",200)

if __name__ == "__main__":
     app.run(host = "127.0.0.1", port = 5050)

问题在于我的用户名和密码始终为无".

The problem is that my username and password are always None.

我也尝试使用:

content = request.get_json(force = True) 
password = content['pass']

request.form['user']

当我打印内容时,我有:<请求' http://127.0.0.1:5050/login '[POST]>.所以我无法找到客户端发送的json.

When I print the content I have: < Request 'http://127.0.0.1:5050/login' [POST]> .So I cannot find the json send from the client.

我确实添加了json.dumps并使用了request.get_json()并有效

I did add json.dumps and used request.get_json() and it worked

推荐答案

您正在发送表单编码的数据,而不是JSON.仅设置内容类型不会将您的请求转换为JSON.使用json=发送JSON数据.

You are sending form encoded data, not JSON. Just setting the content-type doesn't turn your request into JSON. Use json= to send JSON data.

response = requests.post(url, json={"user": user,"pass": password})

使用以下命令检索Flask中的数据:

Retrieve the data in Flask with:

data = request.get_json()

这篇关于从请求瓶获取json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆