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://github.com/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 安裝)
參考資料
https://github.com/falconry/falcon
https://github.com/pyenv/pyenv
https://asgi.readthedocs.io/en/latest/implementations.html