Flask Restful:根据 URL 参数更改表示

Sté*_*oin 5 python flask flask-restful

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

正如restful doc中所述,根据内容类型更改序列化很容易,因此对于我的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
Run Code Online (Sandbox Code Playgroud)

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

问题是,因为有些浏览器可能会被路由到一个网址直接下载一个CSV文件,我希望能够通过URL参数,迫使我系列化例如http://my.domain.net/api/resource?format=csv,其中format=csv将有相同的效果-H "Accept: text/csv"

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

Sea*_*ira 0

只需创建一个子类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()
Run Code Online (Sandbox Code Playgroud)