代码之家  ›  专栏  ›  技术社区  ›  Toby Weed

使用flask restful检索查询参数

  •  0
  • Toby Weed  · 技术社区  · 7 年前

    我有一个flask restful端点定义为:

    class SearchEvents(Resource):
        def get(self, name, start_date, end_date):
             #do stuff
    
    api.add_resource(endpoints.SearchEvents, '/events/<string:name>/<string:start_date>/<string:end_date>')
    

    我在和邮递员手工测试。我想传入起始日期和结束日期的空值。然而:

    screenshot of postman interface 我已尝试将URL修改为:

    http://127.0.0.1:5000/events/test/ /  #<--Spaces
    

    http://127.0.0.1:5000/events/test/""/""
    

    无济于事。

    2 回复  |  直到 7 年前
        1
  •  4
  •   Toby Weed    7 年前

    最后解决了这个问题 request 对象,它具有 args 从请求URL检索查询参数的属性:

    from flask_restful import request #import request from flask restful
    
    class SearchEvents(Resource):
        def get(self):
            args = request.args #retrieve args from query string
    
    api.add_resource(endpoints.SearchEvents, '/events')
    

    然后提出如下请求: http://127.0.0.1:5000/events?param1=value1&param2=value2 或传递空值: http://127.0.0.1:5000/events?param=&param2=value1

        2
  •  1
  •   Gastón Avila    7 年前

    传递的值不在查询字符串中。您使用路由部件作为参数,因此除非您提供表单中的某些内容,否则不会匹配路由 /events/some_name/2019-86-98/2100-9885-24515 . 您所做的尝试被烧瓶捕获为不匹配的路径,您将得到404未找到。

    要将这些参数作为查询字符串的一部分发送,需要使用 /events?name=some_name&start_date=2019-86-98&end_date=2100-9885-24515 要获取路由处理程序中的值,应该使用 name = request.args.get('name') 等等。传递空值则意味着命中相同的url,但没有查询参数。