예제 #1
0
    app['coap'] = coap
    app['static_root_url'] = './static'

    for dpt in app['dyn_resources']['public_keys']:
        resources.add_file_resource(coap, dpt)
    for dpt in app['dyn_resources']['signed_manifests']:
        resources.add_file_resource(coap, dpt)
    for dpt in app['dyn_resources']['builds']:
        resources.add_file_resource(coap, dpt)
    for dpt in app['dyn_resources']['flasher_paks']:
        resources.add_file_resource(coap, dpt)
    for dpt in app['dyn_resources']['keygens']:
        resources.add_file_resource(coap, dpt)
    for dpt in app['dyn_resources']['unsigned_manifests']:
        resources.add_file_resource(coap, dpt)

    routes.setup_routes(app, PROJECT_ROOT)

    asyncio.Task(aiocoap.Context.create_server_context(coap))
    loop.run_until_complete(init(loop, app))

    print("Server started")
    addrs = netifaces.ifaddresses('eth0')
    #addrs = netifaces.ifaddresses('wlp4s0')
    ipv6_add = addrs[netifaces.AF_INET6][0]['addr']
    logging.debug("Server IPv6 address is: {}".format(ipv6_add))
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
예제 #2
0
import asyncio
import pathlib

import aiohttp_jinja2
import jinja2
from aiohttp import web

from routes import setup_routes
from sales_stat import calculate_stat, start_calculate_stat

TEMPLATES_ROOT = pathlib.Path(__file__).parent / 'templates'
APP_ROOT = pathlib.Path(__file__).parent.parent

app = web.Application()
setup_routes(app, APP_ROOT)
aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader(str(TEMPLATES_ROOT)))

app.on_startup.append(start_calculate_stat)
web.run_app(app)
예제 #3
0
파일: app.py 프로젝트: begor/aiohttp_api
import asyncio
from aiohttp import web

import settings
import db
import routes

loop = asyncio.get_event_loop()
app = web.Application(loop=loop)

app['config'] = settings.load_settings()

app.on_startup.append(db.init_pg)
app.on_shutdown.append(db.close_pg)

routes.setup_routes(app)

web.run_app(app)
예제 #4
0
def main():
    app = web.Application()
    setup_routes(app)
    web.run_app(app)
예제 #5
0
import base64
from aiohttp import web
from cryptography import fernet
from aiohttp_session import setup
from aiohttp_session.cookie_storage import EncryptedCookieStorage

import jinja2
import aiohttp_jinja2
from routes import setup_routes
from db import init_pg, close_pg
from settings import config, BASE_DIR
from middlewares import setup_middlewares
from tracktor import start_background_tasks

app = web.Application()

fernet_key = fernet.Fernet.generate_key()
secret_key = base64.urlsafe_b64decode(fernet_key)
setup(app, EncryptedCookieStorage(secret_key, max_age=300))

app['config'] = config
aiohttp_jinja2.setup(app,
                     loader=jinja2.FileSystemLoader(
                         str(BASE_DIR / 'aiohttp_tracktor' / 'templates')))
setup_middlewares(app)
setup_routes(app, BASE_DIR)
app.on_startup.append(init_pg)
app.on_startup.append(start_background_tasks)
app.on_cleanup.append(close_pg)
web.run_app(app)
예제 #6
0
from aiohttp import web
from routes import setup_routes
import jinja2
import aiohttp_jinja2
from settings import BASE_DIR
print(str(BASE_DIR / 'templates'))
app = web.Application()
setup_routes(app)
aiohttp_jinja2.setup(app,
                     loader=jinja2.FileSystemLoader(str(BASE_DIR /
                                                        'templates')))
web.run_app(app, host='127.0.0.1', port=8080)

예제 #7
0
def init(loop):
    app = web.Application(loop=loop)
    setup_routes(app)
    return app
예제 #8
0
def init(loop):
    app = web.Application(loop=loop)
    setup_routes(app)
    app['semaphore'] = asyncio.Semaphore(CONCURRENT_REQ)
    app['backends'] = {'heavy': heavy_back, 'light': light_back}
    return app
예제 #9
0
    async def get_application(self):
        from routes import setup_routes

        app = web.Application()
        setup_routes(app)
        return app
예제 #10
0
# coding: utf-8
from flask import Flask
from flask_restful_swagger_2 import Api
# The line below needs to be uncommented when debugging
from flask_cors import CORS
from routes import setup_routes

app = Flask(__name__)

api = Api(app, api_version='1.0', api_spec_url='/api/specs')
setup_routes(api)

from data_access.data_access_base import DataAccessBase
DataAccessBase.initialize()

CORS(app)

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True, port=5234)
예제 #11
0
import logging
import sys
from weakref import WeakValueDictionary

from aiohttp import web
from config import LOG_PATH, HOST, PORT
from routes import setup_routes

# formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
# handler = logging.FileHandler(LOG_PATH)
# handler.setFormatter(formatter)
# handler.setLevel(logging.INFO)
# root = logging.getLogger()
# root.addHandler(handler)
# root.setLevel(logging.INFO)

app = web.Application()
app = setup_routes(app)

web.run_app(app, host=HOST, port=PORT)
예제 #12
0
def init(loop):
    app = web.Application(loop=loop)
    setup_routes(app)
    app['semaphore'] = asyncio.Semaphore(CONCURRENT_REQ)
    return app
예제 #13
0
파일: main.py 프로젝트: tsahes/vk
def setup_app() -> web.Application:
    app = web.Application()
    setup_routes(app)
    return app
예제 #14
0
def app():
    app = web.Application()
    setup_routes(app)
    web.run_app(app, host=config.IP_ADDRESS, port=config.PORT)
예제 #15
0
from flask import Flask
from routes import setup_routes

app = Flask(__name__)


setup_routes(app)


if __name__ == "__main__":
    app.run(debug = True)
예제 #16
0
# Create config
CONFIG = WebAppConfig()

# Initialize Sentry
sentry_sdk.init(
    dsn=CONFIG.SENTRY_DSN
)

# Create storage and state stores
STORAGE = MongodbStorage(CONFIG.MONGO_URL, CONFIG.MONGO_DB, CONFIG.MONGO_COL)
USER_STATE = UserState(STORAGE)
CONVERSATION_STATE = ConversationState(STORAGE)

# Create main dialog
INFORMER = RateAmParserExchangeRatesInformer()
MAIN_DIALOG = MainDialog(USER_STATE, CONVERSATION_STATE, INFORMER)

# Create the Bot
BOT = DramRateBot(CONVERSATION_STATE, USER_STATE, MAIN_DIALOG)

# Create the aiohttp web app
APP = web.Application(middlewares=[aiohttp_error_middleware])
setup_routes(APP, ADAPTER, BOT)

if __name__ == "__main__":
    try:
        web.run_app(APP, port=CONFIG.PORT)
    except Exception as error:
        raise error
예제 #17
0
def main():
    app = web.Application()
    setup_routes(app)
    app.on_startup.append(init_pg)
    app.on_cleanup.append(close_pg)
    web.run_app(app)
예제 #18
0
파일: app.py 프로젝트: Olegblow/ideco_test
def init_app() -> web.Application:
    """Инициализирует web приложение."""
    app = web.Application()
    setup_jinja(app)
    setup_routes(app)
    return app
예제 #19
0
파일: main.py 프로젝트: VVAnton/schedule
def main(prefix_name: str='schedule', is_debug=False):
    # set uvloop
    asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
    # get event-loop
    loop = asyncio.get_event_loop()

    logger.info('{}:debug is {}'.format(prefix_name, is_debug))
    # set debug (or not) to loop
    loop.set_debug(is_debug)

    # create web application (with set debug)
    app = web.Application(
        middlewares=[filter_errors_request],
        loop=loop,
        debug=is_debug,
        client_max_size=1024 ** 2 * 64
    )

    # add Headers for request
    app.on_response_prepare.append(on_prepare)

    # set settings for DBManager
    DBManager().set_settings(dict(
        user=config.get('DB', 'user'),
        password=config.get('DB', 'password'),
        database=config.get('DB', 'database'),
        host=config.get('DB', 'host'),
        port=config.get('DB', 'port')
    ))
    # initial connection-poll in DBManager
    loop.run_until_complete(loop.create_task(DBManager().init_pool()))
    app.on_shutdown.append(DBManager().on_shutdown)

    # add jinja2-templates
    aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates'))

    # add link to session in web.app
    app.session_storage = SessionManager()
    # auth header name
    app.auth_header_name = config.get('SERVICE', 'auth_header_name')

    # add routes
    setup_routes(app)

    # get url for run web-app
    bind_url = urlparse(config.get('PUBLIC_API', 'bind'))

    # run swagger
    setup_swagger(app,
                  swagger_url='/api/docs',
                  title='Schedule online docs',
                  description='',
                  api_version='0.1',
                  contact='*****@*****.**')

    # run web application
    try:
        web.run_app(
            app,
            host=bind_url.hostname,
            port=bind_url.port,
            reuse_address=True,
            reuse_port=True,
            shutdown_timeout=1
        )
    finally:
        loop.close()
예제 #20
0
def init(loop):
    app = web.Application(loop=loop)
    setup_routes(app)
    app['backends'] = {'heavy': heavy_back, 'light': light_back}
    return app
예제 #21
0
def init_app():
    app = web.Application()
    setup_routes(app)
    return app
예제 #22
0
async def init():
    app = web.Application(middlewares=MIDDLEWARES)
    app.cleanup_ctx.extend(SERVICES)
    setup_routes(app)
    return app
예제 #23
0
파일: main.py 프로젝트: BON4/toxic_guesser
async def init(loop, conf):
    app = web.Application(loop=loop)
    executor = await setup_executor(app, conf)
    handler = SiteHandler(conf, executor, BASE_ROOT)
    setup_routes(app, handler, BASE_ROOT)
    return app
예제 #24
0
async def init():
    app = web.Application()
    setup_routes(app=app)
    host = os.getenv("IDLP_TENSORBOARD_API_HOST", 'idlp_tensorboard_worker')
    port = os.getenv("IDLP_TENSORBOARD_API_PORT", '8812')
    return app, host, port
예제 #25
0
async def create_app() -> web.Application:
    """Инициализирует приложение"""
    application = web.Application(middlewares=MIDDLEWARES)
    setup_routes(application)
    setup_aiohttp_apispec(application, **settings.APISPEC_CONF)
    return application
예제 #26
0
def main():
    app = web.Application()
    setup_routes(app)
    web.run_app(app, host="0.0.0.0", port=8080)
예제 #27
0
파일: main.py 프로젝트: valentim/ag-wayland
async def create_app():
    app = web.Application()
    setup_routes(app)

    return app
예제 #28
0
async def main():
    app = web.Application()
    setup_routes(app)
    app.on_startup.append(start_background_tasks)
    app.on_cleanup.append(cleanup_background_tasks)
    return app
예제 #29
0
def main():
    app = web.Application()

    aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader(TMPL_FOLDER))
    app['static_root_url'] = STATIC_ROOT_URL
    app.router.add_static('/static', 'static', name='static')

    app.on_startup.append(start_db)
    app.on_cleanup.append(close_db)

    # Setup redis storage if redis server is on
    try:
        import asyncio
        import aioredis
        from aiohttp_session.redis_storage import RedisStorage

        async def make_redis_pool(app):
            return await aioredis.create_redis_pool(REDIS_ADDR, timeout=5)

        async def dispose_redis_pool(app):
            redis_pool.close()
            await redis_pool.wait_closed()

        loop = asyncio.get_event_loop()
        redis_pool = loop.run_until_complete(make_redis_pool(app))

        storage = RedisStorage(redis_pool)
        app.on_cleanup.append(dispose_redis_pool)

    # Setup encrypted storage if redis server is off
    except ConnectionRefusedError:
        logger.warning(
            'Cannot connect to redis server, switching to standard "EncryptedCookieStorage"'
        )
        import base64
        from cryptography import fernet
        from aiohttp_session.cookie_storage import EncryptedCookieStorage

        fernet_key = fernet.Fernet.generate_key()
        secret_key = base64.urlsafe_b64decode(fernet_key)
        storage = EncryptedCookieStorage(secret_key)

    async def custom_async_error_handler(request):
        return web.Response(text='You silly bot, f**k off!', status=403)

    def setup_csrf_protection(app):
        csrf_policy = aiohttp_csrf.policy.FormPolicy(FORM_FIELD_NAME)
        csrf_storage = aiohttp_csrf.storage.CookieStorage(COOKIE_NAME)

        aiohttp_csrf.token_generator.HashedTokenGenerator(SECRET_PHRASE)

        aiohttp_csrf.setup(app,
                           policy=csrf_policy,
                           storage=csrf_storage,
                           error_renderer=custom_async_error_handler)

        # app.middlewares.append(aiohttp_csrf.csrf_middleware)

        # Using middlewares, all handlers will be protected
        # app.middlewares.append(aiohttp_csrf.csrf_middleware)

        # For mannual protection
        # @aiohttp_csrf.csrf_protect - pretection with csrf
        # @aiohttp_csrf.csrf_exempt - no protection with csrf

    setup_routes(app)
    logger.debug('Routes were setup')

    setup_session(app, storage)
    logger.debug('Storage was setup')

    setup_csrf_protection(app)
    logger.debug('csrf protection was setup')

    # aioreloader.start()
    logger.debug('Start with code reload')

    web.run_app(app, port=APP_PORT)
예제 #30
0
파일: main.py 프로젝트: ppdraga/sh_vcp
import os
from aiohttp import web
import aiohttp_jinja2
import jinja2

from settings import config, BASE_DIR
from routes import setup_routes

app = web.Application()
app['config'] = config
setup_routes(app)
aiohttp_jinja2.setup(app,
                     loader=jinja2.FileSystemLoader(
                         str(os.path.join(BASE_DIR, 'templates'))))
web.run_app(app, port=8088)
예제 #31
0
import base64
from cryptography import fernet
from sqlalchemy import create_engine

from middleware import json_content_type_middleware
from routes import setup_routes
from models import metadata
from utils import DBAuthorizationPolicy

engine = create_engine('sqlite:///../database.db')
metadata.create_all(engine)

fernet_key = fernet.Fernet.generate_key()
secret_key = base64.urlsafe_b64decode(fernet_key)

app = web.Application()
cors = aiohttp_cors.setup(app,
                          defaults={
                              "*":
                              aiohttp_cors.ResourceOptions(
                                  allow_methods=["GET", 'POST'],
                                  allow_credentials=True,
                                  expose_headers="*",
                                  allow_headers="*"),
                          })
setup_session(app, EncryptedCookieStorage(secret_key))
setup_security(app, SessionIdentityPolicy(), DBAuthorizationPolicy())

setup_routes(app, cors)

web.run_app(app, port=7000)