创建Starlette插件更简单
项目描述
starlette-plugins – 使用 Starlette 加快插件开发的辅助工具
Starlette-Plugins 是一个简化插件开发的辅助工具
需求
python >= 3.7
安装
starlette-plugins 应使用 pip 进行安装
pip install starlette-plugins
用法
让我们想象一下,我们需要为 Peewee ORM 编写 Starlette 插件。
from aiopeewee import db_url
from starlette_plugins import StarlettePlugin
class Peewee(StarlettePlugin):
# Give your plugin a name
name = 'db'
# Prepare a default configuration
config = {
'url': 'sqlite+async:///db.sqlite',
'connection_params': {},
}
def __init__(self, app=None, **settings):
super(Peewee, self).__init__(app, **settings)
self.database = None
def setup(self, app, **settings):
"""Setup the plugin."""
super(Peewee, self).setup(app, **settings)
self.database = db_url.connect(self.config.url, **self.config.connection_params)
async def middleware(self, scope, receive, send, app):
"""An optional ASGI middleware."""
try:
await self.database.connect_async()
await app(scope, receive, send)
finally:
await self.database.close_async()
async def shutdown(self, scope):
""" The methods are supported: `startup`, `shutdown`."""
if hasattr(self.database, 'close_all'):
self.database.close_all()
使用插件
from starlette.applications import Starlette
db = Peewee(url='postgres+async://database')
app = Starlette()
db.setup(app)
问题跟踪器
如果您有任何建议、错误报告或烦恼,请向https://github.com/klen/starlette-plugins/issues 的问题跟踪器报告
贡献
许可
在MIT许可证下许可。