def db_uri(): cfg = get_config().get('postgres') driver = 'postgresql' user = cfg.get('user') password = cfg.get('password') host = cfg['host'] port = cfg['port'] database = cfg['database'] return f'{driver}://{user}:{password}@{host}:{port}/{database}'
def build_app(): app = web.Application() config = get_config() app['config'] = config app['auth_backend'] = JWTClientBackend(config['jwt_secret']) setup_middlewares(app) setup_routes(app) app.on_response_prepare.append(on_prepare) return app
def main(argv): logging.basicConfig(level=logging.DEBUG) app = init_app(argv) config = get_config(argv) web.run_app(app, host=config['host'], port=config['port'])
async def init_app(argv=None): app = web.Application() config = get_config(argv) app['config'] = config # create db connection on startup, shutdown on exit app.on_startup.append(init_pg) app.on_cleanup.append(close_pg) app['event_bus'] = EventBus() # setup views and routes setup_routes(app) setup_subapps(app) return app
def create_app(config=None) -> web.Application: app = web.Application() app["config"] = get_config(config) app["project_root"] = pathlib.Path(__file__).parent.as_posix() # setup aiohttp-debugtoolbar aiohttp_debugtoolbar.setup( app, intercept_redirects=False, check_host=False, extra_templates="/usr/src/app/_dev/extra_tpl", extra_panels=[RequestPgDebugPanel, RequestRedisDebugPanel], ) # setup Jinja2 template renderer aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader("./app/templates/")) # create db connection on startup, shutdown on exit app.on_startup.append(setup_redis) app.on_cleanup.append(teardown_redis) # create db connection on startup, shutdown on exit app.on_startup.append(setup_pg) app.on_cleanup.append(teardown_pg) # shutdown SQLalchemy db connection on exit app.on_cleanup.append(teardown_pgsa) # create session on startup, shutdown on exit app.on_startup.append(setup_session) app.on_cleanup.append(teardown_session) # create security using SQLalchemy db connection on startup app.on_startup.append(setup_security) # setup middlewares app.on_startup.append(setup_middlewares) setup_routes(app) return app
import functools from gino import GinoEngine from app import settings settings.config = settings.get_config(settings.BASE_DIR / "config" / "tests.yaml") from main import create_app from tests.fixtures import * @pytest.fixture def app(): return create_app() @pytest.fixture async def cli(aiohttp_client, app): client = await aiohttp_client(app) yield client @pytest.fixture(autouse=True) async def db_transaction(cli): db = cli.app["db"].db real_acquire = GinoEngine.acquire async with db.acquire() as conn:
def __init__(self): self.cfg = settings.get_config() self.path = 'cpu' self.conn = statsd.Connection(self.cfg['statsd']['host'], self.cfg['statsd']['port'])
# -*- coding: utf8 -*- import socket import time import statsd import psutil from app import settings config = settings.get_config() class Collector(object): def __init__(self): self.cfg = settings.get_config() self.path = 'cpu' self.conn = statsd.Connection(self.cfg['statsd']['host'], self.cfg['statsd']['port']) def collect(self): """ Collect cpu stats. """ cpu_percents = psutil.cpu_percent(percpu=True) gauge = statsd.Gauge('.'.join([self.cfg['default']['hostname'], self.path]), self.conn) for c in cpu_time._fields: value = getattr(cpu_time, c) gauge.send(c, value)
from sqlalchemy import create_engine, MetaData from app.settings import BASE_DIR, get_config from app.db_meta import meta DSN = "postgresql://{user}:{password}@{host}:{port}/{database}" USER_CONFIG_PATH = BASE_DIR / 'config' / 'main.yaml' USER_CONFIG = get_config(['-c', USER_CONFIG_PATH.as_posix()]) USER_DB_URL = DSN.format(**USER_CONFIG['postgres']) user_engine = create_engine(USER_DB_URL) TEST_CONFIG_PATH = BASE_DIR / 'config' / 'test.yaml' TEST_CONFIG = get_config(['-c', TEST_CONFIG_PATH.as_posix()]) TEST_DB_URL = DSN.format(**TEST_CONFIG['postgres']) test_engine = create_engine(TEST_DB_URL) def admin_db_url(config): cfg = config.copy() cfg.update(database='postgres') return DSN.format(**cfg) def setup_db(config, override=False): db_name = config['database'] db_user = config['user'] db_pass = config['password'] ADMIN_DB_URL = admin_db_url(config) admin_engine = create_engine(ADMIN_DB_URL, isolation_level='AUTOCOMMIT')
from app.extensions import db """3.4 is crippled""" try: from os import scandir, walk except ImportError: from scandir import scandir, walk def find_assets(): """Yield paths for all static files and templates.""" for name in ['static', 'templates']: directory = os.path.join(app.config['PATH'], name) for entry in scandir(directory): if entry.is_file(): yield entry.path config = get_config(os.getenv('FLASK_ENV')) app = create_app(config) migrate = Migrate(app, db) server = Server(host='0.0.0.0', extra_files=find_assets(), threaded=True) manager = Manager(app) manager.add_command('run', server) manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run()
card_id = request.form['cardid'] path = os.path.join(app.config['UPLOAD_FOLDER'], datetime.datetime.now().strftime('%Y-%m-%d')) if not os.path.exists(path): os.mkdir(path) file_path = os.path.join(path, card_id + os.path.splitext(file.filename)[1]); file.save(file_path) upload_face_image = face_recognition.load_image_file(file_path) upload_face_encoding = face_recognition.face_encodings(upload_face_image)[0] if card_id in known_face_names: _name_index = known_face_names.index(card_id) known_face_names[_name_index] = upload_face_encoding else: known_face_encodings.append(upload_face_encoding) known_face_names.append(card_id) return render_template("/upload.html", success='true') @app.route('/favicon.ico') def get_fav(): return current_app.send_static_file('favicon.ico') if len(sys.argv) > 1: env = sys.argv[1] else: env = os.environ.get('ENV', 'ir') if __name__ == '__main__': app.config.from_object(get_config('gen')) app.run(host='0.0.0.0', port=5001, debug=True, ssl_context=('server-cert.pem', 'server-key.pem'))
def db(): test_config = get_config(['-c', TEST_CONFIG_PATH.as_posix()]) setup_db(test_config['postgres'], override=True) yield teardown_db(test_config['postgres'])
def db(): test_config = get_config(TEST_CONFIG) setup_db(test_config['mysql']) yield teardown_db(test_config['mysql'])
from app.db import terminal DSN = "mysql://{user}:{password}@{host}:{port}/{db}" ADMIN_DB_URL = DSN.format(user='******', password='', db='mysql', host='localhost', port=3306) admin_engine = create_engine(ADMIN_DB_URL, isolation_level='AUTOCOMMIT') USER_CONFIG_PATH = BASE_DIR / 'config' / 'config.yaml' USER_PATH = USER_CONFIG_PATH.as_posix() USER_CONFIG = get_config(USER_PATH) USER_DB_URL = DSN.format(**USER_CONFIG['mysql']) user_engine = create_engine(USER_DB_URL) TEST_CONFIG_PATH = BASE_DIR / 'config' / 'config_test.yaml' TEST_PATH = TEST_CONFIG_PATH.as_posix() TEST_CONFIG = get_config(TEST_PATH) TEST_DB_URL = DSN.format(**TEST_CONFIG['mysql']) test_engine = create_engine(TEST_DB_URL) def setup_db(config): db_name = config['mysql']['db'] db_user = config['mysql']['user']
from app.settings import get_config CONFIG = get_config()