Ejemplo n.º 1
0
 def routes(self):
     return [
         web.get('/', self.index),
         web.get('/data.json', self.data),
         web.static('/assets/css', CSS_DIR),
         web.static('/assets/js', JS_DIR)
     ]
Ejemplo n.º 2
0
def run_server():
    app = web.Application()
    app.add_routes([
        web.get('/meteo', get_meteodata),
        web.static('/media', INSTAGRAM_DATA.absolute()),
        web.get('/', root_handler),
        web.static(
            '/',
            pathlib.Path(os.getcwd()).joinpath('client', 'dist').absolute()),
    ])

    cors = aiohttp_cors.setup(app,
                              defaults={
                                  "*":
                                  aiohttp_cors.ResourceOptions(
                                      allow_credentials=True,
                                      expose_headers="*",
                                      allow_headers="*",
                                  )
                              })
    for route in list(app.router.routes()):
        cors.add(route)

    logging.info(
        f'*** WebServer is running at http://{"0.0.0.0"}:{os.environ["REST_OUTER_PORT"]} ***'
    )
    web.run_app(app,
                host=os.environ['REST_IP'],
                port=int(os.environ['REST_PORT']))
Ejemplo n.º 3
0
async def serve():
    # Telnet
    hdi = HyperDeckInterface()
    usbmon = USBMonitor(asyncio.Event(), hdi)
    asyncio.create_task(usbmon.monitor_wait())
    #usbmon.registerEvent('add', xxx)
    #usbmon.registerEvent('remove', xxx)

    hds = HDServer(hdi)
    ts = await asyncio.start_server(hds.new_conn, '', 9993)

    addr = ts.sockets[0].getsockname()
    print(f'Serving HyperDeck Server on {addr}')

    logging.basicConfig(level=logging.DEBUG)
    #http
    http = HTTP(hdi)
    app = aiohttp.web.Application()
    # index, loaded for all application uls.
    app.router.add_get('/', http.index_handle)
    app.router.add_get('/kiosk/', http.index_kios_handle)

    app.router.add_post('/upload', http.store_fileupload_handler)
    app.add_routes([web.static('/static', 'html/static/')])
    app.add_routes([web.static('/thumbs', 'thumbs/')])
    app.add_routes([web.static('/videos/', 'videos/')])
    runner = aiohttp.web.AppRunner(app)
    await runner.setup()
    site = aiohttp.web.TCPSite(runner, '', '8082')
    await site.start()

    #ws
    ws = WS(hdi)
    wsserver = await websockets.serve(ws.handler, '', 8765)
    await wsserver.wait_closed()
Ejemplo n.º 4
0
def setup_routes(app, cors, node=True, content_path=None, client=True):
    if node:
        app.add_routes([
            web.get('/hello', hello),
            web.get('/discover', discover),
            web.get('/discover/{magnet}', discover),
            web.post('/upload/{magnet}', upload),
        ])
    if content_path:
        app.add_routes([web.static('/content', content_path)])
    if client:
        # TODO: replace with implementation of sarafan-app prototype
        app.add_routes([
            web.get('/', home),
            web.get('/publications', publications),
            web.get('/abuses', abuses),
            web.get('/awards', awards),
            web.get('/api/posts', post_list),
            web.post('/api/create_post', create_post),
            web.post('/api/publish', publish),
            web.static('/',
                       Path(__file__).parent.parent.parent / 'build')
        ])
    # Configure CORS on all routes.
    for route in list(app.router.routes()):
        cors.add(route)
    return app
Ejemplo n.º 5
0
def main():
    backend = Backend()
    handler = Handler(backend)

    chain_path = '/home/jbones/fullchain.pem'
    privkey_path = '/home/jbones/privkey.pem'
    ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
    ssl_context.load_cert_chain(chain_path, privkey_path)

    app = web.Application()
    app.add_routes([
        web.get('/favicon.ico', handler.handle_favicon),
        web.get('/', handler.handle_index_get),
        web.post('/', handler.handle_index_post),
        web.get('/menu/{menu_id}', handler.handle_menu),
        web.post('/order', handler.handle_order),
        web.post('/echo', handler.handle_echo),
        web.get('/rest', handler.handle_websocket),
        web.get('/rest_page', handler.handle_rest_page_get),
        web.post('/rest_page', handler.handle_rest_page_post),
        web.static('/resources', '../adminwebpage/resources'),
        make_static_js('/qrloader.js'),
        make_static_js('/qr-scanner.min.js'),
        make_static_js('/qr-scanner-worker.min.js'),
        web.static('/static', '../static_stuff/static')
    ])
    web.run_app(app, port=443, ssl_context=ssl_context)
Ejemplo n.º 6
0
async def create_app_two():
    app = web.Application()
    app.add_routes([
        web.get('/', index_app_two),
        web.static('/get_agent/', path=THIS_DIR / 'agents', show_index=True),
        web.static('/atomics/', path=THIS_DIR / 'art/atomics', show_index=True)
    ])
    setup_agent_communication_routes(app)
    return app
Ejemplo n.º 7
0
def create_app(is_main=False):
    """
    Main asynchronous program.
    """
    start_logger()
    log = logging.getLogger(__name__)

    parser = configargparse.ArgParser(
        default_config_files=["~/.virgin-monitor"])
    parser.add("-c",
               "--my-config",
               is_config_file=True,
               help="config file path")
    parser.add("-p",
               "--db-path",
               env_var="DB_PATH",
               default="~/virgin-monitor.sqlite",
               help="database file path")
    parser.add("-i",
               "--interval",
               env_var="POLL_INTERVAL",
               default=10,
               help="poll interval (seconds)",
               type=int)
    parser.add("-u",
               "--url",
               env_var="URL",
               default=ENDPOINT_URL,
               help="Endpoint URL")

    if is_main:
        argv = sys.argv[1:]
    else:
        # Run with adev or something
        argv = sys.argv[2:]
    args = parser.parse_args(argv)

    db_path = os.path.expanduser(args.db_path)

    http = aiohttp.ClientSession()

    app = web.Application()
    app.update(  # pylint: disable=no-member
        args=args,
        http=http,
        sql3_connect=lambda: aiosqlite.connect(db_path, isolation_level=None),
        log=log)

    app.on_startup.append(start_monitor)
    app.on_cleanup.append(cleanup)

    # Web routes
    app.add_routes([web.static('/js', "web/js")])
    app.add_routes([web.static('/css', "web/css")])
    app.router.add_get('/', render_index)
    app.router.add_get('/data', render_data)
    return app
Ejemplo n.º 8
0
 def routes(self):
     return [
         web.get('/', self.index),
         web.post('/start.json', self.start_capture),
         web.post('/stop.json', self.stop_capture),
         web.get('/status.json', self.get_status),
         web.static('/assets/css', CSS_DIR),
         web.static('/assets/js', JS_DIR)
     ]
 def buildApp(self, app):
     path = abspath(join(__file__, "..", "..", "static"))
     app.add_routes([
         static("/static", path, append_version=True),
         static("/drive/static", path, append_version=True),
         get("/drive/picker", self.picker),
         get("/", self.index),
         get("/drive/authorize", self.authorize),
         post("/drive/refresh", self.refresh),
         post("/logerror", self.error)
     ])
     aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader(path))
     return app
Ejemplo n.º 10
0
def enable_for_aiohttp(app, package_directory):
    async def root_handler(request):
        return aiohttp.web.HTTPFound('/ui/index.html')

    async def favicon_handler(request):
        # return aiohttp.web.HTTPFound('/ui/favicon.ico')
        return web.FileResponse(package_directory.joinpath('web-ui','favicon.ico'))

    app.router.add_route('*', '/ui/', root_handler)
    app.router.add_route('*', '/favicon.ico', favicon_handler)
    app.add_routes([web.static('/ui', package_directory.joinpath('web-ui'))])
    app.add_routes([web.static('/js', package_directory.joinpath('web-ui', 'js'))])
    app.add_routes([web.static('/css', package_directory.joinpath('web-ui', 'css'))])
    app.add_routes([web.static('/fonts', package_directory.joinpath('web-ui', 'fonts'))])
Ejemplo n.º 11
0
def main():
    global args, cfg
    parser = argparse.ArgumentParser()
    parser.add_argument('-c',
                        '--config',
                        dest='config',
                        default='config.cfg',
                        help="Config file. Default: config.cfg")
    args = parser.parse_args()

    config = configparser.ConfigParser()
    config.read(args.config)
    cfg = config['default']

    logging.basicConfig(
        level=cfg['debug'],
        format='%(asctime)s %(name)s.%(lineno)s %(levelname)s: %(message)s')

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates'))
    app.add_routes([
        web.get('/', index),
        web.get(r'/csv/{id}', csv_get),
        web.get(r'/graph/{id}', graph),
        web.post(r'/id/{id}', store),
        web.get('/favicon.ico', favicon),
        web.static('/static', 'static'),
    ])

    p = Process(target=listenudp.main)
    p.start()

    web.run_app(app, host=cfg['host'], port=cfg['port'])
Ejemplo n.º 12
0
def run_app(host, port, *, routes, tasks=None):
    logging.basicConfig(
        format=
        '%(asctime)s.%(msecs)03d %(name)-10s %(levelname)-8s %(filename)12s:%(lineno)3s  %(message)s',
        level=logging.DEBUG,
        datefmt='%Y-%m-%d %T')

    tasks = tasks or []

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=PackageLoader('aiowebcam', 'templates'))

    app.add_routes(routes)
    app.add_routes([
        web.static('/static',
                   pkg_resources.resource_filename('aiowebcam', 'static'))
    ])

    app['static_root_url'] = '/static'

    loop = asyncio.get_event_loop()

    runner = web.AppRunner(app)
    loop.run_until_complete(runner.setup())

    site = web.TCPSite(runner, host, port)
    loop.run_until_complete(site.start())

    if tasks:
        loop.run_until_complete(asyncio.gather(*tasks))
    else:
        loop.run_forever()
Ejemplo n.º 13
0
async def init():
    PROJECT_ROOT = Path(__file__).parent

    app = web.Application()
    aiohttp_debugtoolbar.setup(app, intercept_exc='debug')

    loader = jinja2.FileSystemLoader([str(TEMPLATE_DIR)])
    aiohttp_jinja2.setup(app, loader=loader)

    routes = [
        web.get('/', index, name='index'),
        web.get('/redirect', redirect, name='redirect'),
        web.get('/exception', exception, name='exception'),
        web.get('/jinja2_exc', jinja2_exception, name='jinja2_exception'),
        web.get('/ajax', ajax, name='ajax'),
        web.post('/ajax', ajax, name='ajax'),
        web.static('/static', PROJECT_ROOT / 'static'),
    ]

    if aiohttp_mako:
        mako_cfg = {
            'input_encoding': 'utf-8',
            'output_encoding': 'utf-8',
            'default_filters': ['decode.utf8'],
            'directories': [str(TEMPLATE_DIR)],
        }
        aiohttp_mako.setup(app, **mako_cfg)
        route = web.get('/mako_exc', mako_exception, name='mako_exception')
        routes.append(route)

    app.add_routes(routes)
    return app
Ejemplo n.º 14
0
def setup(app):
    app.add_routes([get('/', index)])
    app.add_routes([get('/ws', websocket_handler)])

    app.add_routes([post('/message', message)])

    app.add_routes([static('/static', Path(__file__).parent / 'static')])
Ejemplo n.º 15
0
def main():

    app = web.Application()

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

    app.add_routes([
        web.get('/', home),
        web.get('/Homepage', home),
        web.get('/Locations', locations),
        web.get('/Classes', classes),
        web.get('/Safety', safety),
        web.get('/Login', show_login),
        web.post('/Login', login),
        web.get('/Logout', logout),
        web.get('/CreateAdmin', create_admin),
        web.static('/static', 'static', show_index=False),
        web.post('/tweet', add_tweet),
        web.get('/delete', delete_tweet),
        web.get('/like', like),
        web.get('/like.json', like_json)
    ])

    print("Hi!!! Welcome to Webserver 1.0")
    web.run_app(app, host="0.0.0.0", port=80)
Ejemplo n.º 16
0
def main():
    parser = argparse.ArgumentParser(description='Pyide args')
    parser.add_argument('--host', metavar='host', type=str, default='0.0.0.0', help='Host name')
    parser.add_argument('-p', '--port', metavar='port', type=int, default=31415, help='Listen port number')
    parser.add_argument('-d', '--debug', action='store_true', default=False, help='Debug mode')
    args = parser.parse_args()

    settings = {'debug': args.debug}
    if args.debug:
        logging.basicConfig(level=logging.DEBUG)

    app = web.Application(**settings)
    app.add_routes(
        [
            # web.view(ROUTING['command'], Command),
            web.view(ROUTING['filelisting'] + '/{file_name:.*}', FileListing),
            web.view(ROUTING['filelisting'], FileListing),
            web.view(ROUTING['code'] + '/{file_name:.*}', Code),
            web.view(ROUTING['tags'] + '/{file_name:.*}', Tags),
            web.view(ROUTING['gotodefinition'] + '/{file_name:.*}', GoToDefinition),
            web.view(ROUTING['line'] + '/{file_name:.*}', Line),
            web.view(ROUTING['autocomplete'] + '/{file_name:.*}', AutoComplete),

            web.static('/client', ROUTING['client']),

            web.view(ROUTING['favicon'], Favicon)

        ]
    )
    web.run_app(app, host=args.host, port=args.port)
Ejemplo n.º 17
0
def app(handlers=None):
    handlers = handlers or _dev_handlers()
    app = web.Application()
    app.on_startup.append(handlers.on_startup)
    app.on_cleanup.append(handlers.on_cleanup)
    app.add_routes([
        web.get("/", handlers.index),
        web.get("/w/{word}/{encrypt}", handlers.word),
        web.get("/shorten_word_url/{word}/{encrypt}",
                handlers.shorten_word_url),
        web.get("/define_word", handlers.define_word),
        web.get("/favicon.ico", handlers.favicon),
        web.static("/static", "./website/static"),
    ])
    aiohttp_jinja2.setup(
        app,
        loader=jinja2.FileSystemLoader("./website/templates"),
        filters={
            "quote_plus": quote_plus,
            "remove_period": lambda x: x.rstrip("."),
            "escape_double": lambda x: x.replace('"', r'\"'),
            "strip_quotes": lambda x: x.strip('"'),
        },
    )
    return app
Ejemplo n.º 18
0
async def start_server(host, port):
    app = web.Application()
    app.add_routes([
        web.get('/', http_root_handler),
        web.get('/img/{img:[a-f0-9]{24}}.jpg', http_img_handler),
        web.get('/thumb/{img:[a-f0-9]{24}}.jpg', http_thumb_handler),
        web.get('/avatar/{img:[a-f0-9]{24}}.jpg', http_avatar_handler),
        web.get('/comments/{img:[a-f0-9]{24}}.json', http_comments_handler),
        web.get(
            '/api/{category:(latestuploads|awards|staffpicks|popular)}/{offset:\d+}.json',
            http_api_category_handler),
        web.get('/api/user:{uid:[a-f0-9]{24}}/{offset:\d+}.json',
                http_api_user_handler),
        web.get('/api/album:{aid:[a-f0-9]{24}}/{offset:\d+}.json',
                http_api_album_handler),
        web.get('/api/tag:{tag}/{offset:\d+}.json', http_api_tag_handler),
        web.get('/api/search:{q}/{offset:\d+}.json', http_api_search_handler),
        web.get('/api/username:{q}/{offset:\d+}.json',
                http_api_username_handler),
        web.static('/', 'resources'),
    ])
    app.middlewares.append(error_middleware)
    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, host, port)
    await site.start()
    print(f'Listening {host}:{port}')
Ejemplo n.º 19
0
    def __init__(self, loop=None):
        self.loop = loop
        if self.loop == None:
            self.loop = asyncio.get_event_loop()
        self.app = web.Application()
        aiohttp_jinja2.setup(self.app, loader=jinja2.FileSystemLoader('./www/tmpl'))
        self.app.add_routes([web.static('/static', './www/static', show_index=True)])

        self.timergoing = False
        self.timer = datetime.timedelta(hours=1)

        self.MQTT = MQTTClient(config={
            'keep_alive': 10,
            'ping_delay': 1,
            'default_qos': 0,
            'default_retain': False,
            'auto_reconnect': True,
            'reconnect_max_interval': 10,
            'reconnect_retries': 2,
        })

        # self.crons = {"foo": (crontab.CronTab("*/1 * * * * * *"), [foo])}
        self.tosub = []
        self.plugins = {}
        self.controlviews = {}
        self.controls = {}
        if sys.platform != "win32":
            self.player = JackNPlayer(loop=self.loop)
            self.player2 = JackNPlayer(loop=self.loop)
        self.speakertags = []
        self.speakers = []
        self.speakergroups = {}
        self.config = {}
Ejemplo n.º 20
0
    def _register_panel(self):
        """Register panel for homeassistant."""
        panel_dir = Path(__file__).parent.joinpath("panel")

        def create_response(panel_file):
            """Create a function to generate a response."""
            path = panel_dir.joinpath(f"{panel_file!s}.html")
            return lambda request: web.FileResponse(path)

        # This route is for backwards compatibility with HA < 0.58
        self.webapp.add_routes(
            [web.get('/panel', create_response('hassio-main-es5'))])

        # This route is for backwards compatibility with HA 0.58 - 0.61
        self.webapp.add_routes([
            web.get('/panel_es5', create_response('hassio-main-es5')),
            web.get('/panel_latest', create_response('hassio-main-latest')),
        ])

        # This route is for backwards compatibility with HA 0.62 - 0.70
        self.webapp.add_routes([
            web.get('/app-es5/index.html', create_response('index')),
            web.get('/app-es5/hassio-app.html', create_response('hassio-app')),
        ])

        # This route is for HA > 0.70
        self.webapp.add_routes([web.static('/app', panel_dir)])
Ejemplo n.º 21
0
    def serve_resource(self, url_prefix: str, r: Resource, *, name: str = None):
        """
        Serve resource files on given url, example:

            >>> server = Server()
            >>> r1 = Bundle().add('some/directory')
            >>> server.serve_resource('/static', r1)  # GET /static/directory/

        """
        assert isinstance(r, Resource), f'{r!r} must be resource'
        dir_prefix = urllib.parse.urljoin(url_prefix + '/', str(r.mount))
        target_path = r.abspath

        if target_path.is_file():
            # aiohttp only supports serving directories

            async def handler(_: web.Request):
                return web.FileResponse(target_path)

            self._app.router.add_get(dir_prefix, handler, name=name)
            logger.debug(
                'added custom file route: %r -> %r',
                dir_prefix, target_path
            )
        else:
            route = web.static(dir_prefix, target_path, name=name)
            self._app.add_routes([route])
            logger.debug(
                'added static directory route: %r -> %r',
                dir_prefix, target_path
            )
Ejemplo n.º 22
0
    def __init__(self, run_forever=True):
        self.logger = logging.getLogger(__name__)
        self.logfrontend = logging.getLogger("etabackend.frontend")

        self.hostip = os.environ.get('ETA_IP') or "localhost"
        self.hostport = int(os.environ.get('ETA_PORT') or "5678")
        self.hostdashport = int(os.environ.get('ETA_DASHPORT') or "5679")
        self.not_displaying = threading.Event()
        self.not_displaying.set()
        self.display_url = None
        self.display_shutdown_url = None

        # Fix for tornado webserver
        if hasattr(asyncio, "WindowsSelectorEventLoopPolicy"):
            asyncio.set_event_loop_policy(
                asyncio.WindowsSelectorEventLoopPolicy())

        self.app = web.Application(
            logger=logging.getLogger("etabackend.aiohttp"))
        self.app['websockets'] = weakref.WeakSet()
        self.app.add_routes([web.get('/', self.web_redirect),
                             web.get('/index.html', self.web_index,
                                     name='default'),
                             web.get('/ws', self.websocket_handler),
                             web.get('/shutdown-display',
                                     self.shutdown_display),
                             web.get('/shutdown', self.shutdown),
                             web.static('/', BASE_DIR / 'static/',
                                        append_version=True),
                             ])
        self.logfrontend.addHandler(WebClientHandler(self.schedule_send_text))

        self.kernel = ETA()
        self.kernel.add_callback(
            'running', lambda: self.schedule_send({'op': 'running'}))
        self.kernel.add_callback(
            'paused', lambda: self.schedule_send({'op': 'paused'}))
        self.kernel.add_callback(
            'finished', lambda: self.schedule_send({'op': 'finished'}))
        self.kernel.add_callback(
            'update-recipe', lambda: self.schedule_recipe_update())

        # Monkeypatch a display function to the kernel to support display in recipe.
        # FIXME This is somehow evil, but works. Should be fixed if the Display function is every fixed, it is also not so beautiful.
        self.kernel.display = self.display
        self.kernel.send = self.schedule_send_text

        self.logger.info(
            "ETA URL: http://{}:{}".format(self.hostip, self.hostport))

        self.app.on_shutdown.append(self.on_shutdown)

        async def set_loop(app):
            self.loop = asyncio.get_event_loop()        
        self.app.on_startup.append(set_loop)
  

        if run_forever:
            web.run_app(self.app, host=self.hostip, port=self.hostport,
                        shutdown_timeout=1, access_log=None)
Ejemplo n.º 23
0
    def __init__(
        self,
        *,
        session_launcher: SshJobLauncher,
        external_url: Url,
        oidc_client: OidcClient,
    ):
        self.session_launcher: SshJobLauncher = session_launcher
        self.external_url: Url = external_url
        self.oidc_client: OidcClient = oidc_client
        self._http_client_session: Optional[ClientSession] = None
        self.session_user_locks: Dict[uuid.UUID, asyncio.Lock] = {}

        self.app = web.Application()
        self.app.add_routes([
            web.get('/', self.welcome),
            web.get(
                '/api/viewer', self.login_then_open_viewer
            ),  #FIXME: this is only here because the oidc redirect URLs must start with /api
            web.get('/api/check_login', self.check_login),
            web.get('/api/login_then_close', self.login_then_close),
            web.get('/api/hello', self.hello),
            web.post('/api/session', self.spawn_session),
            web.get('/api/session/{session_id}', self.session_status),
            web.post('/api/get_ebrains_token', self.get_ebrains_token
                     ),  #FIXME: I'm using this in NG web workers
            web.get('/service_worker.js', self.serve_service_worker),
            web.static(
                '/public',
                Path(__file__).joinpath(
                    "../../../public"),  # FIXME: how does this work?
                follow_symlinks=True,
                show_index=True),
        ])
        super().__init__()
Ejemplo n.º 24
0
def run():
    app = web.Application()
    app.add_routes(routes)
    app.add_routes([web.static(base_url + '/static', 'resources/feedback-templates/static')])
    aiohttp_jinja2.setup(app,
                         loader=jinja2.FileSystemLoader('resources/feedback-templates/'))
    web.run_app(app, port=config.getint("FEEDBACK", "PORT", fallback=8080))
Ejemplo n.º 25
0
def start_server():
  app = web.Application()
  logging.basicConfig(level=logging.INFO)
  logger = logging.getLogger("API")
  is_prod = os.getenv("ENV") is "prod"


  app.add_routes(ping_router)
  app.add_routes(transribe_router)

  if is_prod:
    app.add_routes([web.static('/app', './client/dist')])

  cors = aiohttp_cors.setup(app, defaults={
    "*": aiohttp_cors.ResourceOptions(
            allow_credentials=True,
            expose_headers="*",
            allow_headers="*",
        )
  })
  for route in list(app.router.routes()):
    cors.add(route)

  socket.attach(app)

  web.run_app(app, port=os.getenv("PORT", 3000), access_log=logger)
Ejemplo n.º 26
0
def apispecs_server(loop, aiohttp_server, api_specs_dir):
    app = web.Application()
    app.add_routes([
        web.static("/", api_specs_dir),
    ])
    server = loop.run_until_complete(aiohttp_server(app))
    return server
Ejemplo n.º 27
0
def init_app():
    middleware = session_middleware(SimpleCookieStorage())
    app = web.Application(middlewares=[middleware])

    # create a global dict of identity -> (folder object, active ws connections)
    cache = {}
    app['folders'] = cache

    app.on_startup.append(model.startup)
    app.on_shutdown.append(shutdown)

    policy = aiohttp_security.SessionIdentityPolicy()
    aiohttp_security.setup(app, policy, SimpleAuthorizationPolicy(cache))

    app.add_routes([
        web.get('/ws', ws),
        web.post('/signup', signup),
        web.post('/login', login),
        web.post('/logout', logout),
        web.get('/auth', allow),
        web.post('/files', upload),
        web.get('/files', download),
        # below are static files that should be served by NGINX
        web.get(
            '/', index,
            name='index'),  # static does not support redirect / to /index.html
        web.get('/index.html', index),  # serve a single static file with auth
        web.static('/', os.path.join(dir_path, 'static'), name='static')
    ])  # handle static files such as html, js, css

    return app
Ejemplo n.º 28
0
    def __init__(
        self,
        *,
        session_type: Type[SESSION_TYPE],
        master_host: str,
        external_url: Url,
        sockets_dir_at_master: Path,
        master_username: str,
        oidc_client: Optional[OidcClient],
    ):
        self.session_type = session_type
        self.sockets_dir_at_master = sockets_dir_at_master
        self.master_username = master_username
        self.master_host = master_host
        self.external_url = external_url
        self.oidc_client = oidc_client

        self.sessions: Dict[uuid.UUID, Session] = {}

        self.app = web.Application()
        self.app.add_routes([
            web.get('/check_login', self.check_login),
            web.get('/login_then_close', self.login_then_close),
            web.get('/hello', self.hello),
            web.post('/session', self.spawn_session),
            web.get('/session/{session_id}', self.session_status),
            web.static('/',
                       Path(__file__) / "../../../public",
                       follow_symlinks=True,
                       show_index=True),
        ])
Ejemplo n.º 29
0
def initialise_routes(app):
    app.add_routes([
        static('/DATA', os.path.join('..', 'data', 'files'), show_index=True),
        get('/ui/favicon.ico', favicon, allow_head=False),
        get('/ui/test', usn_ui, allow_head=False),
        get('/input/usn', single_usn, allow_head=False),
        get('/ui/list', list_ui, allow_head=False),
        get('/', root, allow_head=False),
        post('/input/list', list_inp),
        get('/queue', queue_get, allow_head=False),
        delete('/queue/{request_id}', queue_cancel),
        get('/history', history_get, allow_head=False),
        get('/history/{request_id}', history_instance_get, allow_head=False),
        delete('/history/{request_id}', history_instance_delete),
        get('/data/url', url_get, allow_head=False),
        get('/data/exam', exam_get, allow_head=False),
        get('/data/exam/{exam_id}/file', files_get, allow_head=False),
        get('/data/exam/{exam_id}/file/{file_name}',
            send_file,
            allow_head=False),
        get('/data/exam/{exam_id}/usn', usn_get, allow_head=False),
        get('/data/exam/{exam_id}/usn/{usn}',
            usn_instance_get,
            allow_head=False),
        get('/data/vtu_links', get_links, allow_head=False),
    ])
Ejemplo n.º 30
0
async def make_app(loop, info_dem, addr='0.0.0.0', port='8008'):
    logging.basicConfig(level=logging.INFO)
    app = web.Application(
        loop=loop,
        client_max_size=17408**2,
        middlewares=[error_middleware],
    )
    app['logger'] = logging.getLogger("features.main")
    app['path_info'] = init_grass(info_dem)
    app['info_dem'] = info_dem
    app.add_routes([
        web.get('/sun', sun_wrapper),
        web.get('/sunmask', sunmask_wrapper),
        web.get('/viewshed', interviz_wrapper),
        web.get('/activity-features/{category}', handler_activity_features),
        web.get('/features/{category}/{bbox}', handler_features),
        web.post('/features/{category}', handler_features_post),
        web.post('/parse-clue', handler_clue),
        web.post('/{op}', handler_geom_op),
        web.get('/', index),
        web.static('/', 'dist/'),
    ])
    handler = app.make_handler()
    srv = await loop.create_server(handler, addr, port)
    return srv, app, handler
Ejemplo n.º 31
0
def test_static(router):
    folder = pathlib.Path(__file__).parent
    router.add_routes([web.static('/prefix', folder)])
    assert len(router.resources()) == 1  # 2 routes: for HEAD and GET

    resource = list(router.resources())[0]
    info = resource.get_info()
    assert info['prefix'] == '/prefix'
    assert info['directory'] == folder
    url = resource.url_for(filename='sample.key')
    assert url == URL('/prefix/sample.key')
Ejemplo n.º 32
0
def setup_routes(app: web.Application) -> None:
    app.add_routes([web.view('/connect/authorize', AuthorizeView),
                    web.view('/connect/token', TokenView),
                    web.view('/client', ClientListView),
                    web.view('/client/register', RegisterClientView),
                    web.view('/account', AccountListView),
                    web.view('/account/create', CreateAccountView),
                    web.view('/account/{username}', GetAccountView),
                    web.route('*', '/{tail:.*}', catch_all)])

    project_root = pathlib.Path(__file__).parent.parent
    app.add_routes([web.static('/static/',
                               path=project_root / 'static',
                               name='static')])
Ejemplo n.º 33
0
        return web.Response(text="Resource not found", status=404)

    sd = SimpleTextLineTestDecorator()
    html = sd.render(res)
    return web.Response(text=html, content_type="text/html")


routes = [
    web.get   ("/", web_top),
    web.get("/logs", web_log),
    web.get("/reset", web_reset),
    web.get("/scenarios", web_list_scenarios),
    web.get("/scenarios/{id}", web_detail_scenarios),
    web.get("/run/id/{id}", web_run_by_id),
    web.get("/results/{id}", web_results_by_id),
    web.static("/static", "./static"),
]


# Jinja2 Filter: ログの整形用
def j2_filter_date(date: datetime):
    return date.strftime('%H:%M:%S.%f')

j2_filters = dict()
j2_filters["strftime"] = j2_filter_date

app = web.Application()
app["static_root_url"] = "/static"
aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader("./"), filters=j2_filters)
app.add_routes(routes)