Skip to content

Instantly share code, notes, and snippets.

@Julian-Nash
Created July 21, 2021 16:18
Show Gist options
  • Save Julian-Nash/6b5dd11c1e97052db8d46926508df90a to your computer and use it in GitHub Desktop.
Save Julian-Nash/6b5dd11c1e97052db8d46926508df90a to your computer and use it in GitHub Desktop.
Sanic Motor Example
from pathlib import Path
import os
from sanic import Sanic
from motor.motor_asyncio import AsyncIOMotorClient
from app.config import get_config
from app.blueprints import view, ws, api
def create_app(config_name: str) -> Sanic:
""" Creates and returns a Sanic application.
Args:
config_name (str): The name of the config class to load (prod|dev|test)
Returns:
The application (Sanic)
"""
config_class = get_config(config_name)
app = Sanic("Sanic Motor example", config=config_class())
@app.listener('before_server_start')
def init(sanic, loop):
client = AsyncIOMotorClient(config_class.MONGO_HOST, config_class.MONGO_PORT)
sanic.ctx.db = client["my_db"]
# Define static directory
app.static("/static", os.path.join(Path(__file__).parent.resolve(), "static"), name="static")
# Register blueprints
for bp in (view, ws, api):
app.blueprint(bp)
return app
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment