我創建了一個小Flask服務。但是,每次我嘗試使用say-hi端點時,都會收到以下訊息:
{
"message": "The browser (or proxy) sent a request that this server could not understand."
}
我的 Flask 服務如下所示:
from flask import Flask, request
from flask_restful import Resource, Api, abort, reqparse
app = Flask(__name__)
api = Api(app)
class HelloResource(Resource):
def get(self):
return { 'message': 'Hello' }
class SayHiResource(Resource):
def get(self):
parser = reqparse.RequestParser()
parser.add_argument('name', required=True, help='Name cannot be blank')
args = parser.parse_args()
return { 'message': 'Hello ' args['name'] }
api.add_resource(HelloResource, '/hello')
api.add_resource(SayHiResource, '/say-hi')
if __name__ == '__main__':
app.run(debug=True, load_dotenv=True)
但是,沒有太多關于失敗原因的資訊。
我運行的方式是使用gunicorn和serviceEntrypoint.py檔案,它只有這個內容:
from src.api.service import app
if __name__ == '__main__':
app.run()
這是我的檔案夾結構
.
├── requirements.txt
├── serviceEntrypoint.py
└── src
├── __init__.py
└── api
├── __init__.py
└── service.py
為什么/hello結局有效,say-hi但當我打電話給時卻沒有http://localhost:8000/say-hi?name=John?
uj5u.com熱心網友回復:
如果您運行燒瓶除錯服務器并發出 HTTP 請求http://localhost:8000/say-hi?name=John,您將看到實際錯誤是:
message "Did not attempt to load JSON data because the request Content-Type was not 'application/json'."
這里有檔案和示例,但歸結為選擇請求應該是 GET 還是 POST。您構建請求的方式 - 您只傳遞 1 個欄位,即用戶名 - 它看起來像 GET,在這種情況下,您應該具有:
api.add_resource(SayHiResource, '/say-hi/<username>')
和類:
class SayHiResource(Resource):
def get(self, username):
return { 'message': 'Hello ' username }
如果要實作 POST 請求,請在檔案中跟蹤呼叫觸發的示例:curl http://localhost:5000/todos -d "task=something new" -X POST -v
更新:
對于使用查詢引數,您可以使用request.args:
api.add_resource(SayHiResource, '/say-hi')
班級:
class SayHiResource(Resource):
def get(self):
username = request.args.get("username")
status = request.args.get("status")
# print(query_args)
return { 'message': 'Hello {}, your status is: {}'.format(username, status) }
例子:
[http_offline@greenhat-35 /tmp/] > curl 'http://localhost:8000/say-hi?username=lala&status=enabled'
{
"message": "Hello lala, your status is: enabled"
}
[http_offline@greenhat-35 /tmp/] >
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/459284.html
上一篇:args不解包
