亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Flask restful - 看不到 json 帖子的輸出

Flask restful - 看不到 json 帖子的輸出

鳳凰求蠱 2021-12-21 16:44:34
我正在使用燒瓶來創建 api 服務器,它獲取 json 數據的帖子。我使用以下本教程來創建代碼: from flask import Flask from flask import requestapp = Flask(__name__)@app.route('/postjson', methods = ['POST'])def postJsonHandler():    print (request.is_json)    content = request.get_json()    print (content)    return 'JSON posted'app.run(host='0.0.0.0')當我運行時:curl -X POST http://127.0.0.1:5000/postjson -H "Content-type: application/json" -d '{ "data": { "url": "https://google.com" }}'我只是看到"JSON posted",沒有任何打印。為什么我看不到任何數據?我也嘗試使用 POSTMAN,但結果相同。我還嘗試了指南示例中的 json:{  &quot;device&quot;:&quot;TemperatureSensor&quot;,  &quot;value&quot;:&quot;20&quot;,  &quot;timestamp&quot;:&quot;25/01/2017 10:10:05&quot; }也一樣。編輯-作為@TomMP 回答,當我嘗試以下代碼時:from flask import Flaskfrom flask import requestapp = Flask(__name__)@app.route('/producer', methods = ['POST'])def postJsonHandler():    print (request.is_json)    content = request.get_json()    print (content)    return request.get_json()    #return 'JSON posted'app.run(host='0.0.0.0')我得到:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><title>500 Internal Server Error</title><h1>Internal Server Error</h1><p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>當我嘗試調試模式時,我得到:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd"><html>  <head>    <title>TypeError: 'dict' object is not callableThe view function did not return a valid response. The return type must be a string, tuple, Response instance, or WSGI callable, but it was a dict. // Werkzeug Debugger</title>    <link rel="stylesheet" href="?__debugger__=yes&amp;cmd=resource&amp;f=style.css"        type="text/css">... (more lines of data)
查看完整描述

3 回答

?
紅糖糍粑

TA貢獻1815條經驗 獲得超6個贊

那是因為你只返回文本 'JSON Posted'

所以返回你想要得到的

像 json 響應:


return jsonify({'status': 0, 'msg': 'success'})

細節


from flask import Flask, request, jsonify


app = Flask(__name__)


@app.route('/postjson', methods = ['POST'])

def postJsonHandler():

    content = request.json

    print(content)

    return jsonify(content)


app.run(host='0.0.0.0')

調用示例:


requests.post('http://0.0.0.0:5000/postjson', json={'a':'b'}).json()


查看完整回答
反對 回復 2021-12-21
?
阿晨1998

TA貢獻2037條經驗 獲得超6個贊

當您使用print()它時,它只是將所有內容打印到控制臺,因此請在運行應用程序時檢查它以查看打印輸出。您從視圖中返回的內容(“JSON 發布”)是作為響應發送回客戶端的內容。


查看完整回答
反對 回復 2021-12-21
?
慕斯709654

TA貢獻1840條經驗 獲得超5個贊

當您使用curl訪問路由時,它只會向您顯示該路由返回的內容 - 在這種情況下,即JSON posted. 它不會向您顯示介于兩者之間的打印語句。您可以嘗試在調試模式下運行燒瓶。這應該打印到您運行此應用程序的控制臺。

編輯:需要明確的是,您仍然不會收到作為對請求的答復發送的數據,即在 Postman 中。為此,您必須在函數結束時使用return request.get_json()


查看完整回答
反對 回復 2021-12-21
  • 3 回答
  • 0 關注
  • 220 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號