Exemplo n.º 1
0
def main(shared: AppsSharedConstants) -> NoReturn:
    """
    The main function of the microservice. Point of entry.

    :param shared: singleton, into which constants are written or reading.
    """
    logger.info('*****[ THE APPLICATION STARTING ]*****')

    asyncio.set_event_loop_policy(EventLoopPolicy())
    app = web.Application(
        logger=logger,
        middlewares=(
            cors_middleware(allow_all=True, urls=[re.compile(r'^\/v\d\/p\/.*')]),
            # Specify custom headers to match, not `X-Forwarded-Proto: https`
            https_middleware({'Forwarded': 'https'}),
            # Ensure that handler will not execute for more than 29.5 seconds
            timeout_middleware(14.5, ignore={}),
        ),
        loop=asyncio.get_event_loop()
    )

    app.on_startup.append(on_startup_override)
    app.on_cleanup.append(on_cleanup_override)

    app.router.add_routes(AwareOfAccountsRoutes.routes())
    app.router.add_routes(AwareOfJobsRoutes.routes())
    app.router.add_routes(AwareOfMetricsRoutes.routes())

    app.shared: AppsSharedConstants   = shared  # shared configs consts
    app.shared.reach_graceful_startup = True
    app.shared.reach_graceful_cleanup = True

    ###
    # Attention! I apologize in advance, but the code that was in this place I had
    # to remove that it would be completely not to violate NDA.
    # ¯\_(ツ)_/¯
    # Thanks for understanding!

    ssl_context: ssl.SSLContext = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    ssl_context.verify_mode = ssl.CERT_REQUIRED
    ssl_context.load_verify_locations(path.join(shared.ssl_ca_certificates_dir, 'ca-certificate-api.pem'))
    ssl_context.load_cert_chain(
        path.join(shared.ssl_ca_certificates_dir, 'here_ca_certificate_*'),
        path.join(shared.ssl_ca_certificates_dir, 'here_ca_certificate_*')
    )

    cfg = shared.extras.get('api')

    web.run_app(
        app,
        host=cfg.get('host'),
        port=cfg.get('port'),
        ssl_context=ssl_context,
        print=None,
        access_log=app.logger,
        reuse_address=True,
        reuse_port=True
    )

    logger.info('*****[ THE APPLICATION STOPPED ]*****')
Exemplo n.º 2
0
def run(args):
    set_event_loop_policy(EventLoopPolicy())
    loop = get_event_loop()
    try:
        shard_id = int(args[-1])
    except ValueError:
        shard_id = 0
    version = f'{v.releaselevel} {v.major}.{v.minor}.{v.micro}'
    if v.serial > 0:
        version += f'-{v.serial}'
    bot = loop.run_until_complete(Hifumi.get_bot(version, shard_id))
    cogs = [
        BotInfo(bot),
        ChannelReader(bot),
        Custom(bot),
        Currency(bot),
        Fun(bot),
        Interactions(bot),
        Moderation(bot),
        Music(bot),
        Nsfw(bot),
        OwnerOnly(bot),
        Roles(bot),
        Tags(bot),
        Utilities(bot)
    ]
    bot.start_bot(cogs)
Exemplo n.º 3
0
def main():
    """Main loop"""

    set_event_loop_policy(EventLoopPolicy())
    conn = AsyncIOMotorClient(MONGO_SERVER)
    database = conn[DATABASE_NAME]
    loop = get_event_loop()
    try:
        loop.run_until_complete(item_handler(database))
    finally:
        loop.close()
Exemplo n.º 4
0
def make_app(close=False):
    app = Application()
    app.router.add_get('/', HomePage)
    app.router.add_post('/multiple', GetData)
    app.router.add_get('/single', GetData)
    set_event_loop_policy(EventLoopPolicy())
    loop = get_event_loop()
    if close:
        loop.close()
    loop.create_server(run_app(app, port=8888))
    print("======= Serving on http://127.0.0.1:8080/ ======")
    loop.run_forever()
Exemplo n.º 5
0
def main():
    """Setup coroutines and kickstart fetcher"""
    set_event_loop_policy(EventLoopPolicy())

    motor = AsyncIOMotorClient(MONGO_SERVER)
    database = motor[DATABASE_NAME]

    loop = get_event_loop()
    ensure_future(feed_fetcher(database))
    try:
        loop.run_forever()
    finally:
        loop.close()
Exemplo n.º 6
0
def main():
    """Setup event loop and start coroutines"""

    set_event_loop_policy(EventLoopPolicy())
    loop = get_event_loop()

    client = AsyncIOMotorClient(MONGO_SERVER)
    database = client[DATABASE_NAME]

    ensure_future(scan_feeds(database))
    try:
        loop.run_forever()
    finally:
        loop.close()
Exemplo n.º 7
0
Arquivo: run.py Projeto: caa06d9c/Mock
    return web.Response(text=request.method + ' ' + request.raw_path + '\n',
                        status=404)


@routes.patch('/{tail:.*}')
async def handle(request):
    print(request.raw_path)
    return web.Response(text=request.method + ' ' + request.raw_path + '\n',
                        status=404)


@routes.delete('/{tail:.*}')
async def handle(request):
    print(request.raw_path)
    return web.Response(text=request.raw_path + '\n', status=404)


if __name__ == '__main__':

    parser = ArgumentParser()
    parser.add_argument('--path', dest="path", action="store")

    args = parser.parse_args()

    set_event_loop_policy(EventLoopPolicy())

    app = web.Application()
    app.add_routes(routes)

    web.run_app(app, path=args.path)
Exemplo n.º 8
0
from collections import deque
from pgoapi.hash_server import HashServer
from sqlalchemy.exc import OperationalError, ProgrammingError

import asyncio
import time

try:
    import _thread
except ImportError:
    import _dummy_thread as _thread

try:
    from uvloop import EventLoopPolicy

    asyncio.set_event_loop_policy(EventLoopPolicy())
except ImportError:
    pass

from db import SIGHTING_CACHE
from utils import get_current_hour, dump_pickle, get_address, get_start_coords, get_bootstrap_points

try:
    import config
except ModuleNotFoundError as e:
    raise ModuleNotFoundError('Please copy config.example.py to config.py and customize it.') from e

# Check whether config has all necessary attributes
_required = (
    'DB_ENGINE',
    'GRID',