我想使用一个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>')发布于 2018-09-07 11:27:32
在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>'
)发布于 2018-09-07 09:18:56
我确实认为,随着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'https://stackoverflow.com/questions/52219025
复制相似问题