[英]Flask-restx request parser returns 400 Bad Request
我在我的燒瓶應用程序中使用flask-restx
但每次我使用 swagger ui 發出請求時,它都會返回 400:
http://127.0.0.1:5000/api/user/register/?password=test&email=test&username=test
{
"message": "Did not attempt to load JSON data because the request Content-Type was not 'application/json'."
}
我的文件結構:
flask-project/
├─ run.py
├─ app/
│ ├─ main/
│ │ ├─ __init__.py
│ │ ├─ api/
│ │ │ ├─ __init__.py
│ │ │ ├─ user.py
│ ├─ __init__.py
app/_init_.py
import os
from dotenv import load_dotenv
from flask import Flask
# Extensions
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_socketio import SocketIO
db = SQLAlchemy()
ma = Marshmallow()
socketio = SocketIO()
load_dotenv()
def create_app(debug=False):
from app.main.api import api_blueprint
app = Flask(__name__)
app.debug = debug
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///database.sqlite3"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "true" # !! Only in development environment.
db.init_app(app) # Flask-SQLAlchemy must be initialized before Flask-Marshmallow.
ma.init_app(app)
socketio.init_app(app)
app.register_blueprint(api_blueprint, url_prefix='/api')
with app.app_context():
db.create_all()
@app.before_first_request
def create_tables():
""" Pre-populate specific tables """
pass
return app
user.py
from flask_restx import Namespace, Resource, reqparse
api = Namespace('user')
@api.route('/register')
@api.param('username', 'Username')
@api.param('email', 'Email')
@api.param('password', 'Password')
class CreateUser(Resource):
def put(self):
parser = reqparse.RequestParser()
parser.add_argument('username', location='json', type=str)
parser.add_argument('email', location='json', type=str)
parser.add_argument('password', location='json', type=str)
args = parser.parse_args()
return args
當我在put
方法中放置 print 語句時,我發現該方法被調用,並且在我定義 args 之前的任何內容都會打印出來。 在我定義 args 的那一行之后沒有打印。 我究竟做錯了什么?
我發現通過從 Werkzeug 2.1.2 降級到 2.0.2 解決了這個問題。
這個周末我剛剛在一個項目上經歷了這個。
api.param
用於路徑中的參數,例如/users/<user_id>
。 您使用的參數是查詢參數,而不是路徑參數。 所以刪除 3 個@api.param
裝飾器。
據我了解, location='json'
用於從以 JSON 格式發送的請求正文中提取數據。 您的參數是查詢參數。 更改您的parser.add_argument
調用以使用location='args'
。然后在您發布的代碼中調用parse_args()
之后,您應該能夠執行args['username']
來獲取username
查詢 arg 的值,如果沒有給出username
arg,它將給出 None 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.