跳转到主要内容

Negotiate:为Python Web应用程序提供智能、简单的内容协商

项目描述

智能、简单的Python Web应用程序内容协商。

内容协商可能很难做到完美。理想情况下,你的代码应该是DRY的,你不会在多个视图方法中重复相同的旧样板代码,只是为了以不同的格式输出相同的领域对象。negotiate通过允许你使用装饰器来装饰你的视图方法,并自动将你的领域对象转换为客户端请求的格式,从而帮助你使生活更加轻松。

使用非常简单。希望这个例子(用于Flask应用程序)可以使主要观点更加清晰

# First, we write a couple of formatters that specify how to translate the
# output of the view function into a particular format. Here we define a
# JSON formatter and an HTML formatter that takes a template parameter.

from negotiate.flask import Formatter

class JSONFormatter(Formatter):
    format = 'json'
    mimetypes = ['application/json']

    def render(self, obj):
        return json.dumps(obj)

class HTMLFormatter(Formatter):
    format = 'json'
    mimetypes = ['text/html']

    def configure(self, template):
        self.template = template

    def render(self, obj):
        return render(self.template, **obj)

# Then, when building the application, we decorate the view function with the
# "negotiate" decorator, listing the formats in which this view is available.

from negotiate.flask import negotiate

@app.route('/posts/<id>')
@app.route('/posts/<id>.<format>')
@negotiate(JSONFormatter)
@negotiate(HTMLFormatter, template='post.html')
def view_post(id, format=None):
    post = Posts.by_id(id)

    if post is None:
        abort(404)
    if not g.user.authorize('read', post):
        abort(401)

    return {'post': post}

结果是一个视图操作,默认情况下将返回HTML版本的帖子(即,带有Accept: */*和没有显式格式),或者如果显式指定了.html扩展名,或者如果提供了.json扩展名或请求中发送了Accept: application/json,则返回JSON版本的帖子。

支持

negotiate 目前支持 FlaskPylons,尽管添加对其他Web框架的支持应该相当容易。查看 negotiate/flask.pynegotiate/pylons.py 来了解所需的小量集成代码。

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪一个,请了解更多关于 安装包 的信息。

源代码分发

negotiate-0.0.1.tar.gz (4.9 kB 查看哈希值)

上传时间 源代码

支持

AWSAWS 云计算和安全赞助商DatadogDatadog 监控FastlyFastly CDNGoogleGoogle 下载分析MicrosoftMicrosoft PSF赞助商PingdomPingdom 监控SentrySentry 错误日志StatusPageStatusPage 状态页面