协商:python web应用程序的智能、简单的内容协商

negotiate的Python项目详细描述


python web应用程序的智能、简单的内容协商。

内容协商很难做好。理想情况下,您的代码应该是 干了,你就不会在多个视图中重复同样的老样板了 方法,以便以不同格式发出相同的域对象。 negotiate允许您装饰,让您的生活更轻松 使用格式化程序自动转换域的视图方法 对象转换为客户端请求的格式。

使用起来很简单。希望这个例子(用于烧瓶应用) 明确要点:

# 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}

结果是一个视图操作,默认情况下它将返回post的html版本(即使用Accept: */*且没有显式格式),或者如果显式指定了.html扩展名,或者如果给定了.json扩展名或随请求发送了Accept: application/json,则返回post的json版本。

支架

negotiate目前支持FlaskPylons,不过添加对其他web框架的支持应该非常容易。查看negotiate/flask.pynegotiate/pylons.py以查看所需的少量集成代码。

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
Java:不解析XML的简单XML。例外   KIE Workbench的java自定义UI   java将元素从bucket移动到LinkedList,但有一个元素被完全删除   如何将java stream collect转换为scala   java运行AsynkTask多次不工作   java组织。xml。萨克斯。SAXParseException:cvccomplextype。2.4.c:匹配的通配符是严格的   java是一种计算排序算法所需时间的合适方法   java在O(logn)时间内对排序整数数组中具有相同数字的数字进行计数   xpages从当前数据库javaAgent调用另一个数据库的javaAgent   java如何在instagram中上传特定位置的所有照片   JavaApachePOI可以有效地删除多个列   java创建的对象数   java我可以在关闭连接时关闭Oracle JDBC自动提交吗?