我想使用带有“from”和“to”日期的URL,其中也可以只提供两个参数中的一个。由于我需要通过关键字知道,如果它是'from'或'to'日期,则只提供一个参数。
如何设置URL,以便我可以检查是否提供了任何一个参数并将它们用作相应类中的变量?
这些线程没有解决我的问题:flask restful: passing parameters to GET request和How to pass a URL parameter using python, Flask, and the command line。
class price_history(Resource):
def get(self, from_, to):
if from_ and to:
return 'all data'
if from_ and not to:
return 'data beginning at date "from_"'
if not from_ and to:
return 'data going to date "to"'
if not from_ and not to:
return 'please provide at least one date'
api.add_resource(price_history, '/price_history/from=<from_>&to=<to>')
我确实认为,随着this answer的调整你应该能够。
class Foo(Resource):
args = {
'from_': fields.Date(required=False),
'to': fields.Date(required=False)
}
@use_kwargs(args)
def get(self, from_, to):
if from_ and to:
return 'all data'
if from_ and not to:
return 'data beginning at date "from_"'
if not from_ and to:
return 'data going to date "to"'
if not from_ and not to:
return 'please provide at least one date'
this thread提供的答案为我工作。它允许您完全省略URL中的可选参数。
这是经过调整的代码示例:
class price_history(Resource):
def get(self, from_=None, to=None):
if from_ and to:
return 'all data'
if from_ and not to:
return 'data beginning at date "from_"'
if not from_ and to:
return 'data going to date "to"'
if not from_ and not to:
return 'please provide at least one date'
api.add_resource(price_history,
'/price_history/from=<from_>/to=<to>',
'/price_history/from=<from_>',
'/price_history/to=<to>'
)