def create_app(app_config=None): from property_app.config import get_config from property_app import middleware, logging from property_app import routes if app_config is None: app_config = get_config() logging.initialize_logging(log_mode=app_config.LOG_MODE) starlette_app = Starlette( debug=app_config.DEBUG, middleware=middleware.get_middleware(app_config) ) local_dir = os.path.dirname(os.path.abspath(__file__)) starlette_app.mount( "/static", app=StaticFiles(directory=os.path.join(local_dir, "static")), name="static", ) starlette_app.mount( "/assets", app=StaticFiles(directory="dist/assets/"), name="assets", ) routes.init_app(starlette_app) return starlette_app
def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ from property_app.database.app_base import AppBase def process_revision_directives(_context, _revision, directives): if getattr(config.cmd_opts, "autogenerate", False): script = directives[0] if script.upgrade_ops.is_empty(): directives[:] = [] logger.info("No changes in schema detected.") app_config = get_config() config.set_main_option("sqlalchemy.url", str(app_config.DATABASE_URI)) engine = engine_from_config( config.get_section(config.config_ini_section), prefix="sqlalchemy.", poolclass=pool.NullPool, ) import warnings from sqlalchemy import exc as sa_exc with warnings.catch_warnings(): warnings.filterwarnings( "ignore", category=sa_exc.SAWarning, message= "Skipped unsupported reflection of expression-based index*.", ) connection = engine.connect() context.configure( connection=connection, target_metadata=AppBase.metadata, process_revision_directives=process_revision_directives, include_object=include_object, include_schemas=True, ) try: with context.begin_transaction(): context.run_migrations() except Exception as exception: logger.error(exception) raise exception finally: connection.close()
def get_templates(template_root=None): from property_app.config import get_config if template_root is None: config = get_config() template_root = pathlib.Path(config.TEMPLATE_ROOT) template_dir = template_root / pathlib.Path("templates") templates = Jinja2Templates(directory=template_dir.as_posix()) jinja_env = templates.env jinja_env.globals["asset_url"] = asset_url return templates
def asset_url(context: dict, name: str, dist_root=None): if dist_root is None: from property_app.config import get_config config = get_config() dist_root = config.DIST_ROOT dist_path = pathlib.Path(dist_root) manifest_path = dist_path / pathlib.Path("assets/manifest.json") with open(manifest_path, "rb") as manifest_file: manifest = json.load(manifest_file) asset_name = pathlib.Path(manifest[name]) request = context["request"] return request.url_for("assets", path=asset_name.as_posix())
def page_assets(request: Request): from property_app.config import get_config config = get_config() dist_root = config.DIST_ROOT page_path = request.path_params["page_path"] manifest = None dist_dir = pathlib.Path(dist_root) manifest_path = dist_dir / pathlib.Path("assets/manifest.json") with open(manifest_path, "rb") as manifest_file: manifest = json.load(manifest_file) asset_name = pathlib.Path(manifest[page_path]) asset_url = request.url_for("assets", path=asset_name.as_posix()) return RedirectResponse(asset_url)
def start(reload=None): import uvicorn # type: ignore from property_app.config import get_config config = get_config() if config.DEBUG: start_app = "property_app.app:app" else: start_app = create_app(app_config=config) if reload is None: reload = config.DEBUG uvicorn.run( start_app, host=config.APP_HOST, port=config.APP_PORT, log_level="info", reload=reload, )
def get_middleware(config=None): """ Setup app middleware """ from property_app.config import get_config if config is None: config = get_config() return [ Middleware(ProxyHeadersMiddleware), Middleware( SessionMiddleware, secret_key=str(config.SECRET_KEY), session_cookie="_session", https_only=True, domain=config.DOMAIN, ), Middleware(RequestMetaMiddleware), Middleware(DatabaseSessionMiddleware), Middleware(AuthenticationMiddleware, backend=PasswordAuthBackend()), Middleware(CanonicalLogMiddleware), ]
import sqlalchemy as sa from sqlalchemy import orm from property_app.config import get_config from property_app.middleware import get_request_id app_metadata = sa.MetaData( naming_convention={ "ix": "ix_%(column_0_label)s", "uq": "uq_%(table_name)s_%(column_0_name)s", "ck": "ck_%(table_name)s_%(constraint_name)s", "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", "pk": "pk_%(table_name)s", }) _session_options = { "autocommit": False, "autoflush": False, } app_config = get_config() engine = sa.create_engine(str(app_config.DATABASE_URI), pool_pre_ping=True, use_batch_mode=True) Session = orm.scoped_session(orm.sessionmaker(bind=engine, **_session_options), scopefunc=get_request_id)