协商: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目前支持Flask和Pylons,不过添加对其他web框架的支持应该非常容易。查看negotiate/flask.py和negotiate/pylons.py以查看所需的少量集成代码。