【问题标题】:How parse json data in flask? [duplicate]如何解析flask中的json数据? [复制]
【发布时间】:2018-10-02 06:11:59
【问题描述】:

我正在尝试从 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>

我只想发布 json 并接收并将其保存到服务器端的变量中

【问题讨论】:

  • 我无法重现您的问题。该代码对我有用。但是您应该做的一件事(尽管它可能无法解决您的 404 问题)是在您的请求调用中将 json= 放在字典之前。除此之外,我建议停止服务器,在运行客户端脚本时验证连接是否失败,重新启动服务器,然后重试。顺便问一下,为什么会有//robots.txt 的日志?
  • @AlexHall 你能给我看一个小例子吗,比如我如何通过烧瓶中的 url 发送 json,然后在服务器端接收它?
  • 我说你应该写requests.post(url, json={...}),但是缺少json= 并不能解释你的404错误,否则你的代码是完美的。

标签: python python-3.x flask server bottle


【解决方案1】:

您发布的脚本中只有一个问题。您需要在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)

【讨论】:

    猜你喜欢
    • 2014-07-24
    • 1970-01-01
    • 1970-01-01
    • 2012-05-24
    • 2016-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-09
    相关资源
    最近更新 更多