【问题标题】:Flask: API URL with keyword parametersFlask:带有关键字参数的 API URL
【发布时间】:2019-02-12 14:23:55
【问题描述】:

我想使用带有“from”和“to”日期的 URL,也可以只提供两个参数之一。因此,我需要通过关键字知道是否只提供了一个参数,如果它是“从”或“到”日期。

如何设置 URL,以便我可以检查是否提供了任何一个参数并将它们用作相应类中的变量?

这些线程没有解决我的问题:flask restful: passing parameters to GET requestHow 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>')

【问题讨论】:

    标签: python api flask


    【解决方案1】:

    我确实认为通过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'
    

    【讨论】:

    • 似乎我无法从 URL 中提取参数。在args 中分配元素时,它们显然被分配给_Missing,这会导致TypeError,因为该对象不可订阅。我认为将可选参数传递给 URL 的问题相当普遍,但我无法找到解决问题的好资源......
    【解决方案2】:

    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>'
                    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多