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 目前支持 Flask 和 Pylons,尽管添加对其他Web框架的支持应该相当容易。查看 negotiate/flask.py 和 negotiate/pylons.py 来了解所需的小量集成代码。
项目详情
关闭
negotiate-0.0.1.tar.gz 的哈希值
| 算法 | 哈希摘要 | |
|---|---|---|
| SHA256 | 8dbb81a77beda735605a1b16592291524912a7b94fe868c7404f80d901fb66f3 |
|
| MD5 | 2fbd9f86d634d4ce690c63743489d5df |
|
| BLAKE2b-256 | b65fe8905340f93d244508f7613c1e2efdd5f61dd79915e1294250789c0ab69f |