Created
April 28, 2018 18:56
-
-
Save bakatrouble/af5f4d1f0818db03850858db1ea78273 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from urllib import parse | |
from pony.orm import * | |
db = Database() | |
Model = db.Entity | |
class SanicPony(object): | |
def __init__(self, app, connect=True): | |
self.app = app | |
self.db = db | |
self.init_app(connect) | |
def init_app(self, connect=True): | |
defaults = [ | |
('PONY_PROVIDER', 'sqlite'), | |
('PONY_ARGS', 'filename=db.sqlite3'), | |
] | |
for k, v in defaults: | |
self.app.config.setdefault(k, v) | |
@self.app.middleware('request') | |
async def request_middleware(request): | |
db_session.__enter__() | |
@self.app.middleware('response') | |
async def response_middleware(request, response): | |
db_session.__exit__() | |
if connect: | |
db.connect(**self.db_params()) | |
def db_params(self): | |
bind_args = parse.parse_qsl(self.app.config['PONY_ARGS']) | |
return dict(create_db=True, provider=self.app.config['PONY_PROVIDER'], **dict(bind_args)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment