问题描述
是否有不同的基于 Python 的 REST 框架的建议列表,可用于在服务器端编写您自己的 RESTful API?最好各有优劣.
Is there a list somewhere of recommendations of different Python-based REST frameworks for use on the serverside to write your own RESTful APIs? Preferably with pros and cons.
请随时在此处添加建议.:)
Please feel free to add recommendations here. :)
推荐答案
在设计 RESTful API 时需要注意的是 GET 和 POST 的混淆,就好像它们是同一个东西一样.Django 的 基于函数的视图 和 CherryPy 的默认调度程序,尽管两个框架现在都提供了解决此问题的方法 (基于类的视图 和 MethodDispatcher,分别).
Something to be careful about when designing a RESTful API is the conflation of GET and POST, as if they were the same thing. It's easy to make this mistake with Django's function-based views and CherryPy's default dispatcher, although both frameworks now provide a way around this problem (class-based views and MethodDispatcher, respectively).
HTTP 动词在 REST 中非常重要,除非你非常小心关于这一点,你最终会陷入 REST 反模式.
HTTP-verbs are very important in REST, and unless you're very careful about this, you'll end up falling into a REST anti-pattern.
一些正确的框架是 web.py、Flask 和 瓶.当与 mimerender 库(完全公开:我写的)结合使用时,它们允许您编写漂亮的 RESTful Web 服务:
Some frameworks that get it right are web.py, Flask and Bottle. When combined with the mimerender library (full disclosure: I wrote it), they allow you to write nice RESTful webservices:
import web
import json
from mimerender import mimerender
render_xml = lambda message: '<message>%s</message>'%message
render_json = lambda **args: json.dumps(args)
render_html = lambda message: '<html><body>%s</body></html>'%message
render_txt = lambda message: message
urls = (
'/(.*)', 'greet'
)
app = web.application(urls, globals())
class greet:
@mimerender(
default = 'html',
html = render_html,
xml = render_xml,
json = render_json,
txt = render_txt
)
def GET(self, name):
if not name:
name = 'world'
return {'message': 'Hello, ' + name + '!'}
if __name__ == "__main__":
app.run()
服务的逻辑只实现一次,正确的表示选择(Accept header)+派发到适当的渲染函数(或模板)以整洁、透明的方式完成.
The service's logic is implemented only once, and the correct representation selection (Accept header) + dispatch to the proper render function (or template) is done in a tidy, transparent way.
$ curl localhost:8080/x
<html><body>Hello, x!</body></html>
$ curl -H "Accept: application/html" localhost:8080/x
<html><body>Hello, x!</body></html>
$ curl -H "Accept: application/xml" localhost:8080/x
<message>Hello, x!</message>
$ curl -H "Accept: application/json" localhost:8080/x
{'message':'Hello, x!'}
$ curl -H "Accept: text/plain" localhost:8080/x
Hello, x!
更新(2012 年 4 月):添加了有关 Django 的基于类的视图、CherryPy 的 MethodDispatcher 以及 Flask 和 Bottle 框架的信息.提出问题时两者都不存在.
Update (April 2012): added information about Django's class-based views, CherryPy's MethodDispatcher and Flask and Bottle frameworks. Neither existed back when the question was asked.
这篇关于Python REST(Web 服务)框架的推荐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!