class App(ASyncIOApp): BUILTIN_COMMANDS = [ command for command in ASyncIOApp.BUILTIN_COMMANDS if command.name != 'run' ] + [ Command('run', run), ] def exception_handler(self, exc: Exception) -> http.Response: if isinstance(exc, HTTPException): return http.Response(exc.detail, status=exc.status_code, headers=exc.headers) else: return super().exception_handler(exc)
Run the Postgresql shell with this projects DB settings """ psql = ['psql'] env = os.environ.copy() if backend.url: # Prefer the url psql.append(backend.url) else: # Build a command line from the config. # Put the password in the environment with PGPASS config = backend.config env['DBPASSWORD'] = config.get('PASSWORD', '') keys = set(config.keys()) & set(backend.CLI_CONFIG_MAP.keys()) for k in keys: psql.append(backend.CLI_CONFIG_MAP[k]) psql.append(config[k]) subprocess.call(psql, env=env) components = [ Component(AsyncPgBackend, init=AsyncPgBackend), Component(Connection, init=get_conn, preload=False), ] commands = [ Command('dbshell', pg_cli), ]
def redis_cli(redis_cache: Redis): """ Run the Redis cli with the project Redis connection settings """ loop = asyncio.get_event_loop() conn_info = loop.run_until_complete(redis_cache.conn_info()) args = ['redis-cli', '-n', f"{conn_info.get('db', 0)}"] if isinstance(conn_info['address'], str): args += ['-s', conn_info['address']] else: args += [ '-h', conn_info['address'][0], '-p', str(conn_info['address'][1]) ] if redis_cache.config.get('password'): args += ['-a', redis_cache.config.get('password')] logger.debug('REDIS CLI: %s', ' '.join(args)) subprocess.call(args) components = [ Component(Redis, init=Redis), ] commands = [Command('redis_cli', redis_cli)]
from apistar import Command from .components import MongoBackend def drop_database(backend: MongoBackend) -> None: """ Drop the mongodb database from defined at settings """ backend.drop_database() commands = [ Command('drop_database', drop_database), ]
# example products Route('/products', 'GET', products), Route('/cart/{id}', 'GET', detail_cart), Route('/cart/{id}', 'POST', modify_cart), Route('/cart/{id}', 'DELETE', remove_cart), Route('/cart/{id}/products', 'POST', add_product), Route('/cart/{id}/done', 'POST', done), # Route('/cart/{cart}/products/{product}', 'DELETE', remove_product), # Route('/cart/{cart}/products/{product}', 'PUT', update_product), # Route('/cart/{cart}/vouchers', 'POST', add_voucher), # Route('/cart/{cart}/vouchers/{voucher}', 'DELETE', remove_voucher), # Route('/cart/{cart}/vouchers/{voucher}', 'PUT', update_voucher), # Route('/cart/{cart}/promotion', 'POST', add_promotion), # Route('/cart/{cart}/promotion/{promotion}', 'DELETE', remove_promotion), # Route('/cart/{cart}/promotion/{promotion}', 'PUT', update_promotion), Include('/docs', docs_urls), Include('/static', static_urls) ] commands = [ Command('sign_product', sign_product), Command('unsign_product', unsign_product), ] app = App(routes=routes, commands=commands) if __name__ == '__main__': app.main()
from apistar import Command from apistar.backends import sqlalchemy_backend from main.utils import load_fortunes commands = sqlalchemy_backend.commands + [ Command('load_fortunes', load_fortunes), ]
def downgrade(db_backend: SQLAlchemyBackend, revision): _run_alembic_command(command.downgrade, db_backend.engine, db_backend.metadata, revision=revision) def upgrade(db_backend: SQLAlchemyBackend, revision): _run_alembic_command(command.upgrade, db_backend.engine, db_backend.metadata, revision=revision) def show(db_backend: SQLAlchemyBackend, revision): _run_alembic_command(command.show, db_backend.engine, db_backend.metadata, rev=revision) commands = [ Command('initialize', initialize), Command('create_revision', create_revision), Command('upgrade', upgrade), Command('downgrade', downgrade), Command('show', show) ] __version__ = '0.0.6'
atomic.__exit__(exc_type, exc_value, exc_traceback) def flush(): # pragma: nocover call_command('flush', '--no-input') def makemigrations(): # pragma: nocover call_command('makemigrations') def migrate(): call_command('migrate') def showmigrations(): # pragma: nocover call_command('showmigrations') components = [ Component(DjangoORM), Component(Session, init=get_session, preload=False) ] commands = [ Command('flush', flush), Command('makemigrations', makemigrations), Command('migrate', migrate), Command('showmigrations', showmigrations) ]
def default_args(a=True, b=False, c: int=None, d: float=None): """ Returns the values for a, b, c, and d, which have default values. Args: a: A flag which may be turned [on|off]. b: A flag which may be turned [on|off]. c: A parameter. d: A parameter. """ return 'a=%s, b=%s, c=%s, d=%s' % (a, b, c, d) commands = [ Command('no_args', no_args), Command('required_args', required_args), Command('default_args', default_args) ] app = CliApp(commands=commands) def _get_help_lines(content): """ Return the help text split into lines, but replacing the progname part of the usage line. """ lines = content.splitlines() lines[0] = 'Usage: <progname> ' + ' '.join(lines[0].split()[2:]) return lines
async def get_app(settings: Settings = None): default_settings = { 'DEBUG': True, 'AUTHENTICATION': [], 'QVARN': { 'BACKEND': { 'MODULE': 'qvarn.backends.postgresql', 'USERNAME': '******', 'PASSWORD': '******', 'HOST': 'postgres', 'PORT': None, 'DBNAME': 'planb', 'INITDB': True, }, 'RESOURCE_TYPES_PATH': '/etc/qvarn/resources', 'TOKEN_ISSUER': 'https://auth-jsonb.alpha.vaultit.org', 'TOKEN_AUDIENCE': 'http://localhost:8080', 'TOKEN_SIGNING_KEY': ('ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDLDDFzdeGRZB1EOCWObzmjT34pLhLrSoU4WGu3u0IDhbaQleTQ6hTDj27DkFg20Q' 'ux8PXxcXjxzJXq+ycQDOfDP5ET+/JVeFgPxlX7aQHWyi7g5kY4LNk5AiY6/F1lD/3j4jrdMbhGDfkm44o/ow52q+mU9bnciEeISn1E' 'joDMH4ggk9gzZJDod6fTBwe+tkBETMMG08M9/5jgO4OE3lHBYF60EdMrSQ2kVRvUAOjmXGUyycn80g1BTAwy0SYX01MfGVgfGsSYJ/' 'LKfbtXd5AXjmDXSC3SOsjf/9MdCZ07gNmDzqmyr4yVRJSfYdIn1Prw4BH+seVZmSQqapZ5D2hp' ), }, } settings = merge(default_settings, settings or {}) settings['AUTHENTICATION'] += [BearerAuthentication(settings)] settings['storage'] = await backends.init(settings) routes = [] if settings['DEBUG']: routes += [ Include('/docs', docs_urls), Include('/static', static_urls), ] routes += [ Route('/version', 'GET', views.version), Route('/auth/token', 'POST', views.auth_token), Route('/{resource_type}', 'GET', views.resource_get), Route('/{resource_type}', 'POST', views.resource_post), Route('/{resource_type}/search/{query}', 'GET', views.resource_search), Route('/{resource_type}/{resource_id}', 'GET', views.resource_id_get), Route('/{resource_type}/{resource_id}', 'PUT', views.resource_id_put), Route('/{resource_type}/{resource_id}', 'DELETE', views.resource_id_delete), Route('/{resource_type}/{resource_id}/{subpath}', 'GET', views.resource_id_subpath_get), Route('/{resource_type}/{resource_id}/{subpath}', 'PUT', views.resource_id_subpath_put), ] commands = [ Command('token-signing-key', token_signing_key), ] components = [ Component(backends.Storage, init=backends.get_storage), ] return App(routes=routes, commands=commands, components=components, settings=settings)
settings = { 'DATABASE': { 'URL': 'sqlite:///db.sqlite3', 'METADATA': Base.metadata }, 'STATICS': { 'ROOT_DIR': 'front/static', 'PACKAGE_DIRS': ['apistar'] }, 'TEMPLATES': { 'ROOT_DIR': 'front/templates', 'PACKAGE_DIRS': ['apistar'] } } commands = [ Command('fixtures', fixtures) ] # TODO, combine them? app = App( routes=routes, settings=settings, commands= commands + sqlalchemy_backend.commands, components=sqlalchemy_backend.components ) if __name__ == '__main__': app.main()
} for player_name in player_names ] return {'players': player_list} players_routes = [ Route('/', 'GET', get_all_palyers), Route('/{player_name}/', 'GET', get_palyer_details), ] # ---------------------------------------------------------------------- commands = [ Command('create_user', create_user), Command('delete_user', delete_user), ] routes = [ Route('/show_request', 'GET', show_request), Route('/show_query_params', 'GET', show_query_params), Route('/show_user_agent', 'GET', show_user_agent), Route('/create_project_default', 'GET', create_project_default), Route('/create_project', 'GET', create_project), Route('/hello/{username}/', 'GET', echo_username), Include('/users', user_routes),
status = send_push_notification( title=note.title, text=f"Pokeme {note.title} notification", device_token=note.device_token, credential=settings['FIREBASE_TOKEN']) if status: note.is_notification_send = True session.commit() print("%s note notification was sent" % note.id) def check_schedule(backend: SQLAlchemyBackend): session = backend.Session() try: schedule.every(1).minutes.do( partial(check_notification, session=session)) while True: schedule.run_pending() time.sleep(1) finally: session.close() commands = [ Command('schedule', check_schedule), Command('create_tables', create_tables), Command('drop_tables', drop_tables) ]
def create_tables(backend: SQLAlchemyBackend): """ Create all database tables. Args: backend: The configured database backend. """ backend.metadata.create_all(backend.engine) def drop_tables(backend: SQLAlchemyBackend): """ Drop all database tables. Args: backend: The configured database backend. """ backend.metadata.drop_all(backend.engine) components = [ Component(SQLAlchemyBackend), Component(Session, init=get_session, preload=False) ] commands = [ Command('create_tables', create_tables), Command('drop_tables', drop_tables) ]
def shell_sqlalchemy(session: SqlalchemySession, backend: ShellBackend): """ This command includes SQLAlchemy DB Session """ namespace = {'session': session} namespace.update(backend.get_namespace()) embed(user_ns=namespace, header=backend.header) def shell_django(session: DjangoSession, backend: ShellBackend): """ This command includes Django DB Session """ namespace = {'session': session} namespace.update(backend.get_namespace()) embed(user_ns=namespace, header=backend.header) def shell(backend: ShellBackend): namespace = backend.get_namespace() embed(user_ns=namespace, header=backend.header) sqlalchemy_commands = [Command('shell', shell_sqlalchemy)] django_commands = [Command('shell', shell_django)] common_commands = [Command('shell', shell)]
return http.Response( {'message': 'Unexpected error'}, status=500 ) routes = [ users_routes, projects_routes, tokens_routes, Include('/docs', docs_urls), Include('/static', static_urls) ] app = App( settings=settings, routes=routes, commands=sqlalchemy_backend.commands + [ Command('run', run), Command('make_migrations', revision), Command('migrate', upgrade), Command('revert_migrations', downgrade), ], components=sqlalchemy_backend.components ) if __name__ == '__main__': app.main()
from apistar import Command from .create_user import create_user commands = [ Command('create_user', create_user), ]