我想使用带有'from'和'to'日期的URL,也可以只提供两个参数之一。因此,我需要通过关键字知道是否提供了一个“出发日期”或“截止日期”的参数。
如何设置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>')
答案 0 :(得分:0)
我确实认为通过调整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'
答案 1 :(得分:0)
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>'
)