【问题标题】:Flask Restful: change representation based on URL parameterFlask Restful:根据 URL 参数更改表示
【发布时间】:2015-04-15 16:29:02
【问题描述】:

我正在使用 Flask 和 Flask-Restful 构建 API。 API 可能由不同类型的工具(网络应用程序、自动化工具等)访问,其中一项要求是提供不同的表示形式(为了示例,假设为 json 和 csv)

正如 restful 文档中解释的那样,根据内容类型更改序列化很容易,因此对于我的 CSV 序列化,我添加了以下内容:

@api.representation('text/csv')
def output_csv(data, code, headers=None):
    #some CSV serialized data
    data = 'some,csv,fields'
    resp = app.make_response(data)
    return resp

当使用 curl 并传递正确的-H "Accept: text/csv" 参数时它可以工作。

问题是,由于某些浏览器可能会直接路由到 url 以下载 csv 文件,因此我希望能够通过 url 参数强制我的序列化,例如 http://my.domain.net/api/resource?format=csv 其中 format=csv 会有效果和-H "Accept: text/csv"一样。

我已经阅读了 Flask 和 Flask-Restful 文档,但我不知道如何正确处理这个问题。

【问题讨论】:

    标签: python flask flask-restful


    【解决方案1】:

    只需创建Api 的子类并覆盖mediatypes 方法:

    from werkzeug.exceptions import NotAcceptable
    
    class CustomApi(Api):
        FORMAT_MIMETYPE_MAP = {
            "csv": "text/csv",
            "json": "application/json"
            # Add other mimetypes as desired here
        }
    
        def mediatypes(self):
            """Allow all resources to have their representation
            overriden by the `format` URL argument"""
    
            preferred_response_type = []
            format = request.args.get("format")
            if format:
                mimetype = FORMAT_MIMETYPE_MAP.get(format)
                preferred_response_type.append(mimetype)
                if not mimetype:
                    raise NotAcceptable()
            return preferred_response_type + super(CustomApi, self).mediatypes()
    

    【讨论】:

    • 只是想知道:如何使用 CustomApi 类?当我这样做时: app = Flask(name) api = CustomApi(app) 那么似乎从未使用过覆盖的媒体类型方法?
    【解决方案2】:

    基本上你想从 GET 方法中检索参数。请参阅: How do I get the url parameter in a Flask view

    【讨论】:

      猜你喜欢
      • 2015-08-09
      • 2020-11-15
      • 2018-10-30
      • 2010-10-01
      • 2013-11-07
      • 1970-01-01
      • 2021-03-26
      • 2020-04-12
      • 2020-08-22
      相关资源
      最近更新 更多