如何解析 Flask 中的 json 数据?

How parse json data in flask?

我正在尝试从 webapp 获取 json 数据:

我试过了:

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/postjson', methods = ['POST'])
def postJsonHandler():
    print (request.is_json)
    content = request.get_json()
    print (content)
    return 'JSON posted'

app.run(port= 8090)

然后:

import requests

url='http://127.0.0.1:8090/postjson'

hj=requests.post(url,{
 "device":"TemperatureSensor",
 "value":"20",
 "timestamp":"25/01/2017 10:10:05"
})

print(hj.text)

我得到:

在服务器端:

 * Running on http://127.0.0.1:8090/ (Press CTRL+C to quit)
127.0.0.1 - - [22/Apr/2018 01:45:54] "POST /postjson/ HTTP/1.1" 404 -
127.0.0.1 - - [22/Apr/2018 01:46:01] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [22/Apr/2018 01:46:01] "GET /robots.txt HTTP/1.1" 404 -
127.0.0.1 - - [22/Apr/2018 01:51:46] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [22/Apr/2018 01:51:47] "GET /robots.txt HTTP/1.1" 404 -
127.0.0.1 - - [22/Apr/2018 01:52:26] "GET /postjson' HTTP/1.1" 404 -
127.0.0.1 - - [22/Apr/2018 01:52:48] "GET /postjson/ HTTP/1.1" 404 -

和客户端输出:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>404 Not Found</title>
<h1>Not Found</h1>
<p>The requested URL was not found on the server.  If you entered the URL manually please check your spelling and try again.</p>

我只想 post json 接收并保存到服务器端的变量

您的 post 脚本只有一个问题。您需要在 request.post 调用中设置参数,即 hj=requests.post(url,json='some json')
也可以从 requests.post 函数定义 def post(url, data=None, json=None, **kwargs): 中看出,因此在您的情况下,您发送的是数据而不是 json.

import requests

url='http://127.0.0.1:8090/postjson'

hj=requests.post(url,json = {
 "device":"TemperatureSensor",
 "value":"20",
 "timestamp":"25/01/2017 10:10:05"
})

print(hj.text)