[英]Why am I unable to send HTTP Headers to Flask-RESTful reqparse module using add_argument()?
[英]How to add different flask-restful reqparse requirements for different requests
我正在創建一個這樣的登錄端點作為示例:
from flask_restful import reqparse
parser = reqparse.RequestParser()
parser.add_argument('email', help = 'This field cannot be blank', required = True)
parser.add_argument('password', help = 'This field cannot be blank', required = True)
class UserLogin(Resource):
def post(self):
data = parser.parse_args()
current_user = User.find_by_email(data['email'])
if not current_user:
return {
.
.
.
問題是現在這兩個參數 - 電子郵件和密碼一樣 - 都是強制性的。 但是,如果我想創建另一個只需要其中一個作為填充字段的端點類呢? 顯然刪除required = True
參數可以解決這個問題,但這會破壞class UserLogin
的驗證邏輯。
有沒有現成的資源或模式來做到這一點?
通常,您會為您編寫的每個資源制作不同的解析器。 問題在於解析器是否有共同的參數。 您可以編寫一個包含所有共享參數的父解析器,然后使用copy()擴展解析器,而不是重寫參數。 您還可以使用replace_argument()覆蓋父級中的任何參數,或使用remove_argument()將其完全刪除。 例如:
from flask_restful import reqparse
parser = reqparse.RequestParser()
parser.add_argument('foo', type=int)
parser_copy = parser.copy()
parser_copy.add_argument('bar', type=int)
# parser_copy has both 'foo' and 'bar'
parser_copy.replace_argument('foo', required=True, location='json')
# 'foo' is now a required str located in json, not an int as defined
# by original parser
parser_copy.remove_argument('foo')
# parser_copy no longer has 'foo' argument
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.