falcon 可靠高性能的构建大规模应用以及微服务的 python web 框架
falcon 是一个额可靠高性能的构建大规模应用以及微服务的 python web 框架,主要支持的python 版本为3.6+可以与wsgi 以及asgi 兼容,而且还支持cpython,以下是一个简单的试用
python 的版本管理基于pyenv,具体使用参考相关文档
环境准备
- 安装
pyenv local 3.7.5
python -m venv venv
source venv/bin/activate
// 使用新版本可以支持
pip3 install git+https:///falconry/falcon@3.0.0a2
//wsgi
pip3 install gunicorn
// or asgi
pip3 install hypercorn
- 代码
app.py wsgi 模式的
from wsgiref.simple_server import make_server
import falcon
# Falcon follows the REST architectural style, meaning (among
# other things) that you think in terms of resources and state
# transitions, which map to HTTP verbs.
class ThingsResource:
def on_get(self, req, resp):
"""Handles GET requests"""
resp.status = falcon.HTTP_200 # This is the default status
resp.content_type = falcon.MEDIA_TEXT # Default is JSON, so override
resp.body = ('\nTwo things awe me most, the starry sky '
'above me and the moral law within me.\n'
'\n'
' ~ Immanuel Kant\n\n')
# falcon.App instances are callable WSGI apps...
# in larger applications the app is created in a separate file
app = falcon.API()
# Resources are represented by long-lived class instances
things = ThingsResource()
# things will handle all requests to the '/things' URL path
app.add_route('/things', things)
if __name__ == '__main__':
with make_server('', 8000, app) as httpd:
print('Serving on port 8000...')
# Serve until process is killed
httpd.serve_forever()
- 启动
python app.py
- 访问效果
- asgi 模式
demo.py
import falcon
import falcon.asgi
# Falcon follows the REST architectural style, meaning (among
# other things) that you think in terms of resources and state
# transitions, which map to HTTP verbs.
class ThingsResource:
async def on_get(self, req, resp):
"""Handles GET requests"""
resp.status = falcon.HTTP_200 # This is the default status
resp.content_type = falcon.MEDIA_TEXT # Default is JSON, so override
resp.body = ('\nTwo things awe me most, the starry sky '
'above me and the moral law within me.\n'
'\n'
' ~ Immanuel Kant\n\n')
# falcon.asgi.App instances are callable ASGI apps...
# in larger applications the app is created in a separate file
app = falcon.asgi.App()
# Resources are represented by long-lived class instances
things = ThingsResource()
# things will handle all requests to the '/things' URL path
app.add_route('/things', things)
- 运行
hypercorn demo:app
效果
说明
以上是一个简单的falcon 学习,同时使用了支持asgi 的版本(pip 支持通过vcs 安装)