コード例 #1
0
from aiohttp import web
from aiohttp.web_request import Request
from sqlalchemy.ext.asyncio import AsyncSession

from ..business_models.couriers import (
    CouriersPostRequest,
    CouriersUpdateRequest,
)
from ..business_models.couriers.get import CouriersGetRequest
from ..db.db import get_session

couriers_router = web.RouteTableDef()


@couriers_router.post("/couriers")
@get_session
async def create_couriers(request: Request, session: AsyncSession):

    response = await CouriersPostRequest.create_couriers(session=session,
                                                         request=request)
    return web.json_response(
        data=response.response_data.dict(),
        status=response.status_code,
        reason=response.reason,
    )


@couriers_router.patch("/couriers/{courier_id}")
@get_session
async def patch_courier(request: Request, session: AsyncSession):
    response = await CouriersUpdateRequest.patch_courier(session=session,
コード例 #2
0
'''
Authentication module.
'''
from aiohttp import web
from os import path
import re

import aiofiles
import db.psql_auth_client as pg_cli

PREFIX = '/auth'
ROUTES = web.RouteTableDef()


@ROUTES.get(PREFIX)
async def root_handle(req):
    '''
    Serves documentation.
    '''
    try:
        file_path = path.join(path.dirname(path.abspath(__file__)),
                              '../static/auth.html')
        async with aiofiles.open(file_path, mode='r') as f:
            content = await f.read()
            return web.Response(
                body=content,
                headers={'Content-Type': 'text/html'},
            )
    except Exception:
        return web.Response(status=500)
コード例 #3
0
import json

from aiohttp import web
from aiohttp.web_request import Request
from sqlalchemy.ext.asyncio import AsyncSession

from ..business_models.orders.post import (
    OrdersPostRequest,
    OrdersAssignPostRequest,
    OrdersCompletePostRequest,
)
from ..db.db import get_session

orders_router = web.RouteTableDef()


@orders_router.post("/orders")
@get_session
async def create_orders(request: Request, session: AsyncSession):
    response = await OrdersPostRequest.create_orders(session=session,
                                                     request=request)
    return web.json_response(
        data=response.response_data.dict(),
        status=response.status_code,
        reason=response.reason,
    )


@orders_router.post("/orders/assign")
@get_session
async def assign_orders(request: Request, session: AsyncSession):
コード例 #4
0
import json
import peewee
from playhouse.shortcuts import model_to_dict, dict_to_model
from aiohttp import web
from models import User, Group
from .common import BaseView

app_routes = web.RouteTableDef()
app = web.Application()


@app_routes.view('', name='user')
class UserView(BaseView):
    """
    List users or add a user to the database

    Expects:
        * GET: Nothing
        * POST: A JSON object that has all the fields to the model

    Returns:
        * GET: 200: A dictionary of users to permissions
        * POST: 204: Created successfully

    Errors on:
        * POST:
            * 400: No JSON found or the JSON is malformed
            * 401: User is not an admin
            * 409: User already in database

    POST is available to only admins
コード例 #5
0
import asyncio
import io
import sqlite3
from pathlib import Path
from typing import Any, AsyncIterator, Dict

import aiohttp_jinja2
import aiosqlite
import jinja2
import PIL
import PIL.Image
from aiohttp import web

router = web.RouteTableDef()


@router.get("/")
@aiohttp_jinja2.template("index.html")
async def index(request: web.Request) -> Dict[str, Any]:
    ret = []
    db = request.config_dict["DB"]
    async with db.execute(
            "SELECT id, owner, editor, title FROM posts") as cursor:
        async for row in cursor:
            ret.append({
                "id": row["id"],
                "owner": row["owner"],
                "editor": row["editor"],
                "title": row["title"],
            })
    return {"posts": ret}
コード例 #6
0
from aiohttp.web_response import Response
import aiohttp_cors
from api import api_routes


app = web.Application()

cors = aiohttp_cors.setup(app, defaults={
    "*": aiohttp_cors.ResourceOptions(
            allow_credentials=True,
            expose_headers="*",
            allow_headers="*",
        )
})

frontend_routes = web.RouteTableDef()


@frontend_routes.get('/')
@frontend_routes.get('/{path:.*}')
async def test(request):
    with open('dist/index.html') as file:
        return Response(text=file.read(), content_type='text/html')


app.router.add_static('/_nuxt', path='dist/_nuxt')
app.add_routes(api_routes)
app.add_routes(frontend_routes)

for route in list(app.router.routes()):
    cors.add(route)
コード例 #7
0
ファイル: __init__.py プロジェクト: reidswan/auxify
from aiohttp import web
from aiohttp.web import Request, Response, json_response
from typing import Mapping, Any
import logging
import jsonschema

from auxify.controllers import err
from auxify import config
from auxify.utils import jwt, json_dumps_with_default

logger = logging.getLogger(__name__)

routes_tab = web.RouteTableDef()


def error(message: str, status: int) -> Response:
    return json_response({
        "error": True,
        "status": status,
        "message": message
    },
                         status=status,
                         dumps=json_dumps_with_default)


def json_router(verb: str):
    register_route = routes_tab.__getattribute__(verb)

    def json_endpoint(url_pattern: str,
                      url_variable_types: Mapping[str, type] = {},
                      accepts_body: bool = False,
コード例 #8
0
def init_func(argv=None, **kwargs):
    num_devices = kwargs.get('num_devices', 1)
    leave_published = kwargs.get('leave_published', False)
    port_offset = kwargs.get('port_offset', 0)
    no_publish = kwargs.get('no_publish', False)

    app = web.Application()
    routes = web.RouteTableDef()
    app['servers'] = {}
    app['zeroconf'] = ZeroconfPublisher()

    async def on_startup(app):
        APP_LEVEL.set(APP_LEVEL.get() + 1)
        lvl = APP_LEVEL.get()
        logger.debug(f'APP_LEVEL: {lvl}')
        if lvl > 0:
            return
        zc = app['zeroconf']
        await zc.open()
        coros = []
        for _ in range(num_devices):
            coros.append(
                build_device(app,
                             port_offset=port_offset,
                             no_publish=no_publish))
        await asyncio.gather(*coros)
        logger.success('Servers ready')

    async def on_shutdown(app):
        APP_LEVEL.set(APP_LEVEL.get() - 1)
        lvl = APP_LEVEL.get()
        logger.debug(f'APP_LEVEL: {lvl}')
        zc = app['zeroconf']
        await zc.close()

    app.on_startup.append(on_startup)
    if not leave_published:
        app.on_shutdown.append(on_shutdown)

    @routes.post('/cgi-bin/api.cgi')
    async def handle_command_req(request):
        hostaddr, port = request.host.split(':')
        s_id = (hostaddr, int(port))
        servers = request.app['servers']
        d = request.app['servers'].get(s_id)
        if d is not None:
            device = d['device']
            return await device.handle_command_req(request)
        return web.Response(status=404, reason='Not Found', text='Not found')

    @routes.get('/api.php')
    async def handle_auth_req(request):
        resp = web.Response(text='Ok')
        resp.set_cookie('SessionID', '1234')
        return resp

    @routes.get('/cgi-bin/get_jpg.cgi')
    async def handle_jpg_req(request):
        hostaddr, port = request.host.split(':')
        s_id = (hostaddr, int(port))
        servers = request.app['servers']
        d = request.app['servers'].get(s_id)
        if d is not None:
            device = d['device']
            return await device.handle_jpg_req(request)
        return web.Response(status=404, reason='Not Found', text='Not found')

    app.add_routes(routes)

    return app
コード例 #9
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging;
logging.basicConfig(level=logging.INFO)
import asyncio, os, json, time
from datetime import datetime
from aiohttp import web
from jinja2 import Environment, FileSystemLoader
from www import orm
from www.coroweb import add_routes, add_static
from www.handlers import cookie2user,COOKIE_NAME

ro = web.RouteTableDef()

def init_jinja2(app, **kw):
    logging.info('init jinja2...')
    options = dict(
        autoescape = kw.get('autoescape', True),
        block_start_string = kw.get('block_start_string', '{%'),
        block_end_string = kw.get('block_end_string', '%}'),
        variable_start_string = kw.get('variable_start_string', '{{'),
        variable_end_string = kw.get('variable_end_string', '}}'),
        auto_reload = kw.get('auto_reload', True)
    )
    path = kw.get('path', None)
    if path is None:
        path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
    logging.info('set jinja2 template path: %s' % path)
    env = Environment(loader=FileSystemLoader(path), **options)
    filters = kw.get('filters', None)
    if filters is not None:
コード例 #10
0
def build_app():
    app = web.Application()
    routes = web.RouteTableDef()

    @routes.get('/{token}/')
    async def main(request):
        return jinja2.render_template(f'game.html', request, {})

    @routes.post('/{token}/reset')
    async def reset_game(request):
        session = await get_session(request)
        ship = random_state(FIELD_FROM, FIELD_TO)
        session["ship"] = ship.to_dict()
        session["start"] = datetime.now(timezone.utc).isoformat()
        session["tries"] = GAME_TRIES
        return web.json_response({"status": "ok", "tries_left": GAME_TRIES})

    @routes.post('/{token}/fire')
    async def fire_rocket(request):
        token = request.match_info["token"]
        session = await get_session(request)
        if "ship" not in session or "start" not in session or "tries" not in session:
            return web.json_response({"status": "game_not_started"},
                                     status=400)
        curr_time = datetime.now(timezone.utc)
        start_time = datetime.fromisoformat(session["start"])
        seconds_passed = (curr_time - start_time).total_seconds()
        if seconds_passed >= MAX_GAME_TIME:
            clear_session(session)
            return web.json_response({"status": "game_over"}, status=400)
        ship = State.from_dict(session["ship"])
        tries = session["tries"]
        form = await request.post()
        point = np.array([float(form["x"]), float(form["y"])])

        while ship.time + GAME_DT < seconds_passed:
            new_ship = random_step(ship, SHIP_SPEED, GAME_DT)
            print(
                f"Stepping the ship, old position: {ship.position}, new position: {new_ship.position}"
            )
            ship = new_ship

        if (ship.position > point - ROCKET_SIZE / 2).all() and (
                ship.position < point + ROCKET_SIZE / 2).all():
            clear_session(session)
            return web.json_response({
                "status": "hit",
                "treasure": get_flag(token)
            })
        elif tries <= 1:
            clear_session(session)
            return web.json_response({"status": "rockets_ran_out"})
        else:
            tries -= 1
            session["ship"] = ship.to_dict()
            session["tries"] = tries
            distance = np.linalg.norm(ship.position - point)
            return web.json_response({
                "status": "miss",
                "time_passed": seconds_passed,
                "tries_left": tries,
                "distance": distance,
            })

    app.add_routes(routes)

    aiohttp_session.setup(
        app, EncryptedCookieStorage(base64.b64decode(COOKIE_SECRET)))
    jinja2.setup(app,
                 loader=FileSystemLoader(os.path.join(BASE_DIR, 'templates')))

    return app
コード例 #11
0
def client(
    event_loop: asyncio.AbstractEventLoop,
    unused_tcp_port_factory,
    aiohttp_client,
    api_version_prefix,
    mock_environment: None,
):

    routes = web.RouteTableDef()

    @routes.get("/error")
    async def unexpected_error(request: web.Request):
        raise Exception("boom shall produce 500")

    @routes.get(r"/fail")
    async def expected_failure(request: web.Request):
        raise web.HTTPServiceUnavailable()

    @routes.get(r"/slow")
    async def blocking_slow(request: web.Request):
        time.sleep(SLOW_HANDLER_DELAY_SECS * 1.1)
        return web.json_response({"data": True, "error": None})

    @routes.get(r"/cancel")
    async def cancelled_task(request: web.Request):
        task: asyncio.Task = request.app.loop.create_task(asyncio.sleep(10))
        task.cancel()  # raise CancelledError

    @routes.get(r"/timeout/{secs}")
    async def time_out(request: web.Request):
        secs = float(request.match_info.get("secs", 0))
        await asyncio.wait_for(asyncio.sleep(10 * secs),
                               timeout=secs)  # raises TimeOutError

    @routes.get(r"/delay/{secs}")
    async def delay_response(request: web.Request):
        secs = float(request.match_info.get("secs", 0))
        await asyncio.sleep(secs)  # non-blocking slow
        return web.json_response({"data": True, "error": None})

    # -----
    main = {"port": unused_tcp_port_factory(), "host": "localhost"}
    cfg = {
        "main": main,
        "rest": {
            "enabled": True,
            "version": api_version_prefix
        },
        "diagnostics": {
            "enabled": True
        },
    }

    app = create_safe_application(cfg)

    # activates some sub-modules
    assert setup_settings(app)
    setup_security(app)
    setup_rest(app)

    setup_diagnostics(app)

    settings: DiagnosticsSettings = app[APP_SETTINGS_KEY].WEBSERVER_DIAGNOSTICS
    assert settings.DIAGNOSTICS_MAX_AVG_LATENCY == 2.0

    app.router.add_routes(routes)

    cli = event_loop.run_until_complete(
        aiohttp_client(
            app, server_kwargs={key: main[key]
                                for key in ("host", "port")}))
    return cli
コード例 #12
0
def app_main(main_thread=False):
    # try:
    #     asyncio.get_event_loop()
    # except RuntimeError:
    #     asyncio.set_event_loop(asyncio.new_event_loop())
    # Remark: behavior changes after 3.10
    # This code only works for main_thread + asyncio.ensure_future(server.run())
    # Not setting event_loop OR using create_task will fail for no running event loop

    logging.basicConfig(format='[{asctime}]{levelname}:{message}',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        level=logging.WARNING,
                        style='{')

    base_path = os.getcwd()
    # Serve static content from /static
    sio = socketio.AsyncServer(async_mode='aiohttp')
    app = web.Application()
    aiohttp_jinja2.setup(app,
                         loader=jinja2.FileSystemLoader(
                             os.path.join(base_path, 'templates')))
    sio.attach(app)
    app.router.add_static(prefix='/static',
                          path=os.path.join(base_path, 'static'))
    routeTable = web.RouteTableDef()
    # app = Flask(__name__,
    #             static_url_path='/static',
    #             static_folder=os.path.join(base_path, 'static'),
    #             template_folder=os.path.join(base_path, 'templates'))

    # app.config['SECRET_KEY'] = '3mlf4j8um6mg2-qlhyzk4ngxxk$8t4hh&$r)%968koxd3i(j#f'
    # socketio = SocketIO(app, async_mode='gevent')
    # socketio = SocketIO(app, async_mode='threading')
    # server = Server.start_server(sio.emit)
    server = Server(sio.emit)
    last_ping_data = b''

    def render_template(template_name, request, **kwargs):
        return aiohttp_jinja2.render_template(template_name,
                                              request,
                                              context=kwargs)

    def redirect(route_name, request, **kwargs):
        raise web.HTTPFound(
            request.app.router[route_name].url_for().with_query(kwargs))

    @routeTable.get('/')
    async def index(request):
        nfd_state = server.connection_test()
        return render_template('index.html',
                               request,
                               refer_name='/',
                               nfd_state=nfd_state)

    @routeTable.get('/forwarder-status')
    async def forwarder_status(request):
        def convert_time(timestamp):
            ret = datetime.fromtimestamp(float(timestamp) / 1000.0)
            return str(ret)

        name = "/localhost/nfd/status/general"
        try:
            _, _, data = await server.app.express_interest(name,
                                                           lifetime=1000,
                                                           can_be_prefix=True,
                                                           must_be_fresh=True)
        except (InterestCanceled, InterestTimeout, InterestNack,
                ValidationFailure, NetworkError):
            logging.info("No response: forwarder status")
            raise web.HTTPFound('/')
        msg = GeneralStatus.parse(data)
        status = decode_dict(msg)
        status['start_timestamp'] = convert_time(status['start_timestamp'])
        status['current_timestamp'] = convert_time(status['current_timestamp'])
        return render_template('forwarder-status.html',
                               request,
                               refer_name='/forwarder-status',
                               name=name,
                               status=status)

    @routeTable.post('/faces/add')
    async def faces_add(request):
        if not server.connection_test():
            raise web.HTTPFound('/')

        form = await request.post()
        uri = form['ip']
        ret = await server.add_face(uri)
        if ret is None:
            logging.info("No response: add face")
            ret = {'status_code': -1, 'status_text': 'No response'}
        else:
            logging.info("Added face %s %s %s", uri, ret['status_code'],
                         ret['status_text'])
        return redirect('faces',
                        request,
                        st_code=ret['status_code'],
                        st_text=ret['status_text'])

    @routeTable.post('/faces/remove')
    async def faces_remove(request):
        if not server.connection_test():
            raise web.HTTPFound('/')

        form = await request.post()
        face_id = int(form['face_id'])
        ret = await server.remove_face(face_id)
        if ret is None:
            logging.info("No response: remove face")
            ret = {'status_code': -1, 'status_text': 'No response'}
        else:
            logging.info("Removed face %s %s %s", face_id, ret['status_code'],
                         ret['status_text'])
        return redirect('faces',
                        request,
                        st_code=ret['status_code'],
                        st_text=ret['status_text'])

    @routeTable.get('/faces', name='faces')
    async def faces(request):
        face_list = await server.get_face_list()
        fields = list(face_list[0].keys())
        fields_collapse = [field for field in set(fields) - {'face_id', 'uri'}]
        face_data = None
        if 'face_id' in request.query:
            for f in face_list:
                if str(f['face_id']) == request.query['face_id']:
                    face_data = f
                    break
        route_data = []
        if face_data is not None:
            fib = await server.get_fib_list()
            for fe in fib:
                for nh in fe['next_hop_records']:
                    if str(nh['face_id']) == request.query['face_id']:
                        route_data.append({
                            'route': fe['name'],
                            'cost': nh['cost']
                        })
        return render_template('faces.html',
                               request,
                               refer_name='/faces',
                               face_list=face_list,
                               fields_collapse=fields_collapse,
                               face_data=face_data,
                               route_data=route_data,
                               **request.query)

    @routeTable.get('/face-events')
    async def face_events(request):
        return render_template('face-events.html',
                               request,
                               refer_name='/face-events',
                               event_list=server.event_list)

    @routeTable.post('/routing/add')
    async def routing_add(request):
        if not server.connection_test():
            raise web.HTTPFound('/')

        form = await request.post()
        name = form['name']
        try:
            face_id = int(form['face_id'])
        except ValueError:
            return redirect('routing',
                            request,
                            st_code='-1',
                            st_text=f'Invalid number {form["face_id"]}')

        ret = await server.add_route(name, face_id)
        if ret is None:
            logging.info("No response: add route")
            ret = {'status_code': -1, 'status_text': 'No response'}
        else:
            logging.info("Added route %s->%s %s %s", name, face_id,
                         ret['status_code'], ret['status_text'])
        return redirect('routing',
                        request,
                        st_code=ret['status_code'],
                        st_text=ret['status_text'])

    @routeTable.post('/routing/remove')
    async def routing_remove(request):
        if not server.connection_test():
            raise web.HTTPFound('/')

        form = await request.post()
        name = form['name']
        face_id = int(form['face_id'])
        ret = await server.remove_route(name, face_id)
        if ret is None:
            logging.info("No response: remove route")
            ret = {'status_code': -1, 'status_text': 'No response'}
        else:
            logging.info("Removed route %s->%s %s %s", name, face_id,
                         ret['status_code'], ret['status_text'])
        return redirect('routing',
                        request,
                        st_code=ret['status_code'],
                        st_text=ret['status_text'])

    @routeTable.get('/routing', name='routing')
    async def routing(request):
        # Get list of faces to map FaceIds to FaceUris
        face_list = await server.get_face_list()
        face_map = {}
        for face in face_list:
            face_map[face['face_id']] = face['uri']
        fib_list = await server.get_fib_list()
        rib_list = await server.get_rib_list()

        fib_routes = []
        rib_routes = []
        request_name = None
        if 'name' in request.query:
            request_name = request.query['name']
            for ent in fib_list:
                if ent['name'] == request_name:
                    fib_routes = ent['next_hop_records']
                    break
            for ent in rib_list:
                if ent['name'] == request_name:
                    rib_routes = ent['routes']
                    break

        return render_template('routing.html',
                               request,
                               refer_name='/routing',
                               rib_list=rib_list,
                               fib_list=fib_list,
                               face_map=face_map,
                               fib_routes=fib_routes,
                               rib_routes=rib_routes,
                               request_name=request_name,
                               **request.query)

    @routeTable.get('/strategies', name='strategies')
    async def strategies(request):
        def decode_strategy(msg):
            return [{
                "name": Name.to_str(item.name),
                "strategy": Name.to_str(item.strategy.name),
            } for item in msg]

        name = "/localhost/nfd/strategy-choice/list"
        try:
            _, _, data = await server.app.express_interest(name,
                                                           lifetime=1000,
                                                           can_be_prefix=True,
                                                           must_be_fresh=True)
        except (InterestCanceled, InterestTimeout, InterestNack,
                ValidationFailure, NetworkError):
            logging.info("No response: strategy-list")
            raise web.HTTPFound('/')
        msg = StrategyChoiceMsg.parse(data)
        strategy_list = decode_strategy(msg.strategy_choices)
        return render_template('strategies.html',
                               request,
                               refer_name='/strategies',
                               strategy_list=strategy_list,
                               **request.query)

    @routeTable.post('/strategies/set')
    async def strategies_set(request):
        if not server.connection_test():
            raise web.HTTPFound('/')

        form = await request.post()
        name = form['name']
        strategy = form['strategy']
        ret = await server.set_strategy(name, strategy)
        if ret is None:
            logging.info("No response: set strategy")
            return redirect('strategies',
                            request,
                            st_code='-1',
                            st_text='No response')
        else:
            logging.info("Set strategy %s->%s %s %s", name, strategy,
                         ret['status_code'], ret['status_text'])
            return redirect('strategies',
                            request,
                            st_code=ret['status_code'],
                            st_text=ret['status_text'])

    @routeTable.post('/strategies/unset')
    async def strategies_unset(request):
        if not server.connection_test():
            raise web.HTTPFound('/')

        form = await request.post()
        name = form['name']
        ret = await server.unset_strategy(name)
        if ret is None:
            logging.info("No response: unset strategy")
            return redirect('strategies',
                            request,
                            st_code='-1',
                            st_text='No response')
        else:
            logging.info("Unset strategy %s %s %s", name, ret['status_code'],
                         ret['status_text'])
            return redirect('strategies',
                            request,
                            st_code=ret['status_code'],
                            st_text=ret['status_text'])

    @routeTable.get('/autoconf', name='autoconf')
    async def autoconf(request):
        return render_template('autoconf.html',
                               request,
                               refer_name='/autoconf',
                               **request.query)

    @routeTable.get('/autoconf/perform')
    async def autoconf_perform(request):
        if not server.connection_test():
            raise web.HTTPFound('/')

        ret, msg = await server.autoconf()
        return redirect('autoconf', request, msg=msg)

    @routeTable.get('/certificate-requests')
    async def certificate_requests(request):
        return render_template('certificate-requests.html',
                               request,
                               refer_name='/certificate-requests')

    @routeTable.get('/key-management', name='key_management')
    async def key_management(request):
        key_tree = server.list_key_tree()
        return render_template('key-management.html',
                               request,
                               refer_name='/key-management',
                               key_tree=key_tree)

    @routeTable.get('/ndnsec-delete')
    async def ndnsec_delete(request):
        args = request.query
        name = args.get('name', None)
        kind = args.get('type', 'n')
        if name is not None:
            server.delete_security_object(name, kind)
            time.sleep(0.1)
            return redirect('key_management', request)

    @routeTable.get('/ndnsec-keygen')
    async def ndnsec_keygen(request):
        args = request.query
        name = args.get('name', None)
        if name is not None:
            server.create_identity(name)
            time.sleep(0.1)
            return redirect('key_management', request)

    @routeTable.get('/ndn-ping', name='ndn_ping')
    async def ndn_ping(request):
        return render_template('ndn-ping.html',
                               request,
                               refer_name='/ndn-ping',
                               **request.query)

    @routeTable.post('/exec/ndn-ping')
    async def exec_ndn_ping(request):
        def decode_nack_reason(reason) -> str:
            codeset = {
                0: 'NONE',
                50: 'CONGESTION',
                100: 'DUPLICATE',
                150: 'NO_ROUTE'
            }
            if reason in codeset:
                return codeset[reason]
            else:
                return str(reason)

        def decode_content_type(content_type) -> str:
            codeset = ["BLOB", "LINK", "KEY", "NACK"]
            if content_type <= 3:
                return codeset[content_type]
            else:
                return str(content_type)

        def decode_signature_type(signature_type) -> str:
            codeset = [
                "DIGEST_SHA256", "SHA256_WITH_RSA", "SHA256_WITH_ECDSA",
                "HMAC_WITH_SHA256"
            ]
            if signature_type <= 3:
                return codeset[signature_type]
            else:
                return str(content_type)

        signature_type = None

        async def validator(_, sig):
            nonlocal signature_type
            signature_type = sig.signature_info.signature_type
            return True

        nonlocal last_ping_data
        form = await request.post()
        name = form['name']
        can_be_prefix = form['can_be_prefix'] == 'true'
        must_be_fresh = form['must_be_fresh'] == 'true'
        try:
            interest_lifetime = float(form['interest_lifetime']) * 1000.0
        except ValueError:
            interest_lifetime = 4000.0

        st_time = time.time()
        try:
            data_name, meta_info, data = await server.app.express_interest(
                name,
                validator=validator,
                lifetime=int(interest_lifetime),
                can_be_prefix=can_be_prefix,
                must_be_fresh=must_be_fresh)
            ed_time = time.time()
            response_time = '{:.3f}s'.format(ed_time - st_time)
            response_type = 'Data'
            name = Name.to_str(data_name)
            if meta_info.content_type is not None:
                content_type = decode_content_type(meta_info.content_type)
            else:
                content_type = "None"
            if meta_info.freshness_period is not None:
                freshness_period = "{:.3f}s".format(
                    meta_info.freshness_period / 1000.0)
            else:
                freshness_period = "None"
            if meta_info.final_block_id is not None:
                final_block_id = Component.to_str(meta_info.final_block_id)
            else:
                final_block_id = "None"
            if signature_type:
                signature_type = decode_signature_type(signature_type)
            else:
                signature_type = "None"
            last_ping_data = bytes(data)
            return redirect('ndn_ping',
                            request,
                            response_time=response_time,
                            response_type=response_type,
                            name=name,
                            content_type=content_type,
                            freshness_period=freshness_period,
                            final_block_id=final_block_id,
                            signature_type=signature_type,
                            download='/download/ping-data')
        except ValueError as e:
            logging.info("Illegal name")
            return redirect('ndn_ping',
                            request,
                            response_time='ERROR',
                            response_type=str(e),
                            name=name)
        except (InterestCanceled, ValidationFailure, NetworkError):
            logging.info("No response: ndn-peek")
            raise web.HTTPFound('/')
        except InterestNack as nack:
            ed_time = time.time()
            response_time = '{:.3f}s'.format(ed_time - st_time)
            response_type = 'NetworkNack'
            reason = decode_nack_reason(nack.reason)
            return redirect('ndn_ping',
                            request,
                            response_time=response_time,
                            response_type=response_type,
                            name=name,
                            reason=reason)
        except InterestTimeout:
            ed_time = time.time()
            response_time = '{:.3f}s'.format(ed_time - st_time)
            response_type = 'Timeout'
            return redirect('ndn_ping',
                            request,
                            response_time=response_time,
                            response_type=response_type,
                            name=name)

    @routeTable.get('/download/ping-data')
    async def download_ping_data(_request):
        return web.Response(body=last_ping_data,
                            content_type='application/octet-stream',
                            headers={
                                'Content-Disposition':
                                'attachment; filename="{ping.data}"'
                            })

    app.add_routes(routeTable)

    # asyncio.ensure_future(server.run())
    async def run_app():
        runner = web.AppRunner(app)
        await runner.setup()
        site = web.TCPSite(runner, "localhost", 5000)
        await site.start()
        # WebServer will be closed if this function returns
        if main_thread:
            print('======== Running on http://localhost:5000 ========')
            print('(Press CTRL+C twice to quit)')
        await server.run()  # Blocks here

    try:
        asyncio.run(run_app())
    except KeyboardInterrupt:
        return
コード例 #13
0
import asyncio
from aiohttp import web
from . import Response
import json
import asyncpg.exceptions
from .users import validate_api_key

album_routes = web.RouteTableDef()

@album_routes.view('/albums/{id}')
@album_routes.view('/albums')
class Album(web.View):

    async def get(self):
        valid, result, user_id = await validate_api_key(self.request)
        if not valid:
            return Response.error(result)
        
        album_id = None
        if "id" in self.request.match_info:
            album_id = int(self.request.match_info['id'])

        async with ( self.request.app['db'].acquire() ) as conn:
            async with conn.transaction():
                await conn.set_type_codec(
                    'json',
                    encoder=json.dumps,
                    decoder=json.loads,
                    schema='pg_catalog'
                )
                
コード例 #14
0
from aiohttp import web
from aiohttp_jwt import check_permissions, match_any
from scripts.help_functions import json_response, db_connect, JWT_ALGORITHM, JWT_SECRET
from scripts.help_functions_zbx import async_zabbix_conn
import ipaddress
import asyncssh
import jwt
import asyncio

MonitoringAddDiRoutes = web.RouteTableDef()


async def change_power_di(host_ip, source, tag, status, user, logger):
    try:
        zapi = await async_zabbix_conn(source)
        ip_hosts = await zapi.hostinterface.get(output=['ip'],
                                                selectHosts=['hostid'],
                                                filter={'ip': host_ip})

        status = status.lower() == 'true'

        host_ids_ip = [x['hosts'][0]['hostid'] for x in ip_hosts]
        if host_ids_ip:
            result = await zapi.host.massupdate(hosts=[{
                'hostid': x
            } for x in host_ids_ip],
                                                status=int(not status))
            await zapi.close()
            return True, result['hostids']
        else:
            await zapi.close()
コード例 #15
0
from aiohttp import web
from aiohttp_session import get_session
from aiohttp_security import check_authorized, forget, permits, remember, authorized_userid
from aiohttp_jinja2 import template, render_template

from .events import event_routes
from ..githubhandler import Event
from ..circleci import SlackMessage
from .worker import capp
from .config import APP_SECRET, BOT_BASEURL
from .commands import command_routes

logger = logging.getLogger(__name__)  # pylint: disable=invalid-name

#: List of routes from url path to handler defined in this module
web_routes = web.RouteTableDef()  # pylint: disable=invalid-name

#: List of navigation bar entries defined by this module
navigation_bar = []  # pylint: disable=invalid-name


def add_to_navbar(title):
    """Decorator adding a view to the navigation bar

    Must be "above" the ``@web_routes`` decorator.

    Arguments:
      title: Title to register for this page. Will be the HTML title
             and the name in the navbar.

    """
コード例 #16
0
from aiohttp import web

from apps.folders.models import Folder, FolderMaterial
from apps.folders.serializers import FolderSerializer, FolderDetailSerializer
from utils import views
from utils.exceptions import PermissionDenied

folder_routes = web.RouteTableDef()


@folder_routes.view('/api/folders/')
class FoldersView(views.ListView):
    model = Folder
    serializer_class = FolderSerializer
    pagination_class = None
    order_by = 'name'

    def get_queryset(self):
        user = self.request.query.get('user', self.request['user'].id)
        parent = self.request.query.get('parent')
        queryset = (Folder.c.user == user) & (Folder.c.parent == parent)
        if int(user) != self.request['user'].id:
            queryset &= Folder.c.is_open == True
        return queryset


@folder_routes.view(r'/api/folders/{pk:\d+}/')
class FolderView(views.DetailView):
    model = Folder

    def get_queryset(self):
コード例 #17
0
from typing import Any

from aiohttp import web
from aiohttp.web_request import Request
from asyncpg.protocol.protocol import Record

from client import fetch
from settings import REDIS_CONNECTION, SESSION
from utils import generic_conversion_view_decorator_factory, python_to_json_response, psql_to_python, \
    handle_none_view_decorator, execute_sql, bytes_to_string, json_string_to_python

decorated_routes = web.RouteTableDef()

@generic_conversion_view_decorator_factory(python_to_json_response)
@generic_conversion_view_decorator_factory(psql_to_python)
@handle_none_view_decorator(list)
async def handle(request: Request) -> Record:
    # name = request.match_info.get('name', "Anonymous")
    # text = "Hello, " + name
    # return web.Response(text=text)
    name = request.query.get('name', '*')
    result: Record = await execute_sql(request, 'SELECT * FROM users WHERE name = $1;', name)
    # return web.json_response(result, dumps=date_enabled_json_dumps)
    return result


@decorated_routes.post('/redis/')
@generic_conversion_view_decorator_factory(python_to_json_response)
async def set_redis(request: Request) -> Any:
    post_params = await request.post()
    await request.app[REDIS_CONNECTION].execute('set', post_params.get('key'), post_params.get('value'))
コード例 #18
0
async def _test_client(config, in_app_config=True):
    from aiohttp.test_utils import TestServer, TestClient

    db = Gino()
    app = web.Application(middlewares=[db])
    config.update({
        'kwargs':
        dict(
            max_inactive_connection_lifetime=_MAX_INACTIVE_CONNECTION_LIFETIME,
        ),
    })
    if in_app_config:
        app['config'] = dict(gino=config)
        db.init_app(app)
    else:
        db.init_app(app, config)

    class User(db.Model):
        __tablename__ = 'gino_users'

        id = db.Column(db.BigInteger(), primary_key=True)
        nickname = db.Column('name', db.Unicode(), default='noname')

    routes = web.RouteTableDef()

    @routes.get('/')
    async def root(request):
        conn = await request['connection'].get_raw_connection()
        # noinspection PyProtectedMember
        assert conn._holder._max_inactive_time == \
            _MAX_INACTIVE_CONNECTION_LIFETIME
        return web.Response(text='Hello, world!')

    @routes.get('/users/{uid}')
    async def get_user(request):
        uid = int(request.match_info['uid'])
        method = request.query.get('method')
        q = User.query.where(User.id == uid)
        if method == '1':
            return web.json_response((await q.gino.first_or_404()).to_dict())
        elif method == '2':
            return web.json_response(
                (await request['connection'].first_or_404(q)).to_dict())
        elif method == '3':
            return web.json_response((await db.bind.first_or_404(q)).to_dict())
        elif method == '4':
            return web.json_response(
                (await request.app['db'].first_or_404(q)).to_dict())
        else:
            return web.json_response((await User.get_or_404(uid)).to_dict())

    @routes.post('/users')
    async def add_user(request):
        form = await request.post()
        u = await User.create(nickname=form.get('name'))
        await u.query.gino.first_or_404()
        await db.first_or_404(u.query)
        await db.bind.first_or_404(u.query)
        await request['connection'].first_or_404(u.query)
        return web.json_response(u.to_dict())

    app.router.add_routes(routes)

    e = await gino.create_engine(PG_URL)
    try:
        try:
            await db.gino.create_all(e)
            async with TestClient(TestServer(app)) as rv:
                await yield_(rv)
        finally:
            await db.gino.drop_all(e)
    finally:
        await e.close()
コード例 #19
0
"""HTTP API route tables."""

from __future__ import annotations

from aiohttp import web

__all__ = ["internal_routes", "routes", "init_internal_routes", "init_routes"]

internal_routes = web.RouteTableDef()
"""Routes for the root application that serves from ``/``

Application-specific routes don't get attached here. In practice, only routes
for metrics and health checks get attached to this table. Attach public APIs
to ``routes`` instead since those are accessible from the public API gateway
and are prefixed with the application name.
"""

routes = web.RouteTableDef()
"""Routes for the public API that serves from ``/<api_name>/``."""


def init_external_routes() -> web.RouteTableDef:
    """Initialize the route table for the routes served at ``/<api_name>/``."""
    # Import handlers so that they are registered with the routes table via
    # decorators. This isn't a global import to avoid circular dependencies.
    import checkerboard.handlers.external  # noqa: F401

    return routes


def init_internal_routes() -> web.RouteTableDef:
コード例 #20
0
async def main():
    logging.basicConfig(level=logging.DEBUG)

    parser = argparse.ArgumentParser()
    parser.add_argument('-c', '--config', default='config.json')
    args = parser.parse_args()

    try:
        global_config = read_config(args.config)
    except (OSError, ValueError) as e:
        print(f'ERROR: Failed to read config: {e}', file=sys.stderr)
        sys.exit(1)

    config: dict = global_config.get('hue')
    if not config:
        print('ERROR: Config is missing "hue" section', file=sys.stderr)
        sys.exit(2)

    ipaddress: str = config.get('ipaddress')
    if not ipaddress:
        print('ERROR: Config is missing "hue.ipaddress"', file=sys.stderr)
        sys.exit(2)

    username: dict = config.get('username')
    if not username:
        print('ERROR: Config is missing "hue.username" section',
              file=sys.stderr)
        sys.exit(2)

    routes = web.RouteTableDef()

    @routes.get('/')
    async def _index(_: web.Response):
        html = '<a href="/metrics">Metrics</a>'
        return web.Response(text=html, content_type='text/html')

    @routes.get('/metrics')
    async def _metrics(_: web.Request):
        body = prometheus_client.generate_latest()
        return web.Response(body=body,
                            content_type='text/plain; version=0.0.4',
                            charset='utf-8')

    app = web.Application()
    app.add_routes(routes)
    runner = web.AppRunner(app)
    await runner.setup()

    host, port = '127.0.0.1', PROMETHEUS_PORT
    url = f'http://{host or "127.0.0.1"}:{port}/metrics'
    logging.info('Listening on %s:%d (%s)', host, port, url)
    site = web.TCPSite(runner, host, port)
    await site.start()

    update_interval = 60  # sec
    async with aiohttp.ClientSession() as s:
        api = HueAPI(s, ipaddress, username)

        while True:
            sensors = await api.sensors()
            for sensorid, sensor in sensors.items():
                if sensor['type'] == 'ZLLTemperature':
                    update_temperature_metrics(sensor, sensorid=sensorid)
                elif sensor['type'] == 'ZLLLightLevel':
                    update_lightlevel_metrics(sensor, sensorid=sensorid)

            await asyncio.sleep(update_interval)
コード例 #21
0
ファイル: views.py プロジェクト: jakubclark/title-explorer
import asyncio
import re

from aiohttp import web
from aiohttp_jinja2 import render_template

from .graph import get_title, insert_to_db
from .json_serializer import dumps, title_to_json

views = web.RouteTableDef()


@views.get('/')
async def index(request: web.Request):
    response = render_template('index.jinja', request, context={})
    return response


@views.get('/search')
async def search(request: web.Request):
    scraper = request.app['movie_scraper']
    params = request.rel_url.query

    if 'title' in params:
        search_str = params['title']
        search_results = await scraper.search_by_title(search_str)

        for i, entry in enumerate(search_results):
            id_ = entry['id']
            url = re.search('.*/search', str(request.url))[0]
            search_results[i]['url'] = f'{url}?id={id_}'
コード例 #22
0
LOGO_URL: str = 'https://freeiconshop.com/wp-content/uploads/edd/bank-flat.png'
CONFIG_PATH: str = 'verity-context.json'
WALLET_NAME: str = 'examplewallet1'
WALLET_KEY: str = 'examplewallet1'

context: Context
issuer_did: str = ''
issuer_verkey: str = ''

server: Server
port: int = 4000
handlers: Handlers = Handlers()
handlers.set_default_handler(default_handler)
handlers.add_handler('trust_ping', '1.0', noop)

routes: RouteTableDef = web.RouteTableDef()


async def example(loop):
    logging.info('Starting setup')
    await setup(loop)

    rel_did = await create_relationship(loop)
    await create_connection(loop)

    await ask_question(loop, rel_did)

    schema_id = await write_ledger_schema(loop)
    cred_def_id = await write_ledger_cred_def(loop, schema_id)

    await issue_credential(loop, rel_did, cred_def_id)
コード例 #23
0
    def start_web(self):
        routes = web.RouteTableDef()
        routes.static('/map', './views')
        routes.static('/js', './views/js')
        routes.static('/css', './views/css')
        routes.static('/res', './res')

        @routes.get('/api/local/map/{info}')
        async def map_info(request):
            item = request.match_info['info']
            if item == 'enabled':
                return web.json_response(self.roomba.drawmap)
            elif item == 'mapsize':
                if self.roomba.mapSize:
                    value = {
                        'x': self.roomba.mapSize[0],
                        'y': self.roomba.mapSize[1],
                        'off_x': self.roomba.mapSize[2],
                        'off_y': self.roomba.mapSize[3],
                        'angle': self.roomba.mapSize[4],
                        'roomba_angle': self.roomba.mapSize[5],
                        'update': 3000
                    }
                    if len(self.roomba.mapSize) >= 7:
                        value['invert_x'] = self.roomba.mapSize[6]
                    if len(self.roomba.mapSize) >= 8:
                        value['invert_y'] = self.roomba.mapSize[7]
                else:
                    value = {
                        'x': 2000,
                        'y': 2000,
                        'off_x': 0,
                        'off_y': 0,
                        'angle': 0,
                        'roomba_angle': 0,
                        'invert_x': 0,
                        'invert_y': 0,
                        'update': 3000
                    }
                return web.json_response(value)
            elif item == 'floorplansize':
                if self.roomba.floorplan_size:
                    scale = self.roomba.floorplan_size[3]
                    if isinstance(scale, (int, float)):
                        scale = (float(scale), float(scale))
                    value = {
                        'fp_file': self.roomba.floorplan_size[0],
                        'x': scale[0],
                        'y': scale[1],
                        'off_x': self.roomba.floorplan_size[1],
                        'off_y': self.roomba.floorplan_size[2],
                        'angle': self.roomba.floorplan_size[4],
                        'trans': self.roomba.floorplan_size[5]
                    }
                else:
                    value = None
                return web.json_response(value)
            elif item == 'clear_outline':
                self.roomba.clear_outline()
                return web.Response(text="ok")
            elif item == 'outline':
                if not self.roomba.roomOutline:
                    img = None
                else:
                    img = self.roomba.img_to_png(self.roomba.room_outline)
                return web.Response(body=self.b64_encode(img))
            elif item == 'floorplan':
                img = self.roomba.img_to_png(self.roomba.floorplan)
                return web.Response(body=self.b64_encode(img))
            raise web.HTTPBadRequest(
                reason='bad api call {}'.format(str(request.rel_url)))

        @routes.get('/api/local/info/{info}')
        async def info(request):
            item = request.match_info['info']
            items = self.get_items(item)
            value = await self.roomba.get_settings(items)
            if value:
                return web.json_response(value)
            raise web.HTTPBadRequest(
                reason='bad api call {}'.format(str(request.rel_url)))

        @routes.get('/api/local/action/{command}')
        async def action(request):
            command = request.match_info['command']
            command = self.get_items(command)
            value = request.query
            if command and value:
                newcommand = {'command': command}
                newcommand.update(value)
                self.log.info('received: {}'.format(newcommand))
                self.roomba.send_region_command(newcommand)
                return web.Response(text="ok")
            await self.roomba.async_send_command(command)
            return web.Response(text="ok")

        @routes.get('/api/local/config/{config}')
        async def config(request):
            config = request.match_info['config']
            config = self.get_items(config)
            value = await self.loop.run_in_executor(None,
                                                    self.roomba.get_property,
                                                    config)
            return web.json_response(value)

        @routes.get('/api/local/config/{config}/{setting}')
        async def set_config(request):
            config = request.match_info['config']
            setting = request.match_info['setting']
            settings = self.post_items(config, setting)
            for k, v in settings.items():
                await self.roomba.async_set_preference(k, v)
            return web.Response(text="ok")

        @routes.post('/api/local/action/{command}')
        async def send_command(request):
            command = request.match_info['command']
            value = {}
            if request.can_read_body:
                value = await request.json()
                self.log.info('received: {}'.format(value))
            command = self.post_items(command)
            if command and value:
                value['command'] = command
                self.roomba.send_region_command(value)
                return web.Response(text="sent: {}".format(value))
            raise web.HTTPBadRequest(
                reason='bad api call {}'.format(str(request.rel_url)))

        @routes.post('/map/{command}')
        async def map_values(request):
            command = request.match_info['command']
            value = {}
            if request.can_read_body:
                value = await request.text()
                self.log.info('received: {}'.format(value))
            if command == 'display_values':
                return web.Response(
                    text="copy this to config.ini: {}".format(value))
            elif command == 'set_fp_values':
                post = await request.post()
                for key in iter(post):
                    self.log.info('received key: {} : value: {}'.format(
                        key, post.get(key, None)))
                self.roomba.floorplan_size = (post.get('filename'),
                                              int(post.get('fpoffsetx')),
                                              int(post.get('fpoffsety')),
                                              (float(post.get('fpw')),
                                               float(post.get('fph'))),
                                              int(post.get('fprot')),
                                              float(post.get('fptrans')))

                self.roomba.load_floorplan(
                    self.roomba.floorplan_size[0],
                    new_center=(self.roomba.floorplan_size[1],
                                self.roomba.floorplan_size[2]),
                    scale=self.roomba.floorplan_size[3],
                    angle=self.roomba.floorplan_size[4],
                    transparency=self.roomba.floorplan_size[5])

                return web.Response(text="set fp values to: {}".format(value))
            raise web.HTTPBadRequest(
                reason='bad api call {}'.format(str(request.rel_url)))

        self.app = web.Application()
        self.app.add_routes(routes)
        self.log.info('starting api WEB Server V{} on port {}'.format(
            self.__version__, self.webport))
        self.web_task = self.loop.create_task(
            web._run_app(self.app,
                         host='0.0.0.0',
                         port=self.webport,
                         print=None,
                         access_log=self.log))
コード例 #24
0
class User(BaseUser):
    method = "github"
    routes = web.RouteTableDef()

    def __init__(self, redirect_uri, code_challenge):
        super().__init__(redirect_uri, code_challenge)

        if not GITHUB_CLIENT_ID or not GITHUB_CLIENT_SECRET:
            raise Exception(
                "GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET should be set via environment"
            )

        self._github = GithubClient(client_id=GITHUB_CLIENT_ID,
                                    client_secret=GITHUB_CLIENT_SECRET)

    def get_authorize_page(self):
        # Chance on collision is really low, but would be really annoying. So
        # simply protect against it by looking for an unused UUID.
        state = secrets.token_hex(16)
        while state in _github_states:
            state = secrets.token_hex(16)
        self._state = state

        _github_states[self._state] = self

        # We don't set any scope, as we only want the username + id
        authorize_url = self._github.get_authorize_url(state=self._state)
        return web.HTTPFound(location=authorize_url)

    @staticmethod
    def get_by_state(state):
        if state not in _github_states:
            return None

        user = _github_states[state]
        user._forget_github_state()

        return user

    def logout(self):
        self._forget_github_state()

        super().logout()

    def _forget_github_state(self):
        if self._state:
            del _github_states[self._state]

        self._state = None

    async def get_user_information(self, code):
        # Validate the code and fetch the user info
        await self._github.get_access_token(code)
        user, _ = await self._github.user_info()

        self.display_name = user.username
        self.id = str(user.id)

    @staticmethod
    @routes.get("/user/github-callback")
    async def login_github_callback(request):
        code = in_query_github_code(request.query.get("code"))
        state = in_query_github_state(request.query.get("state"))

        user = User.get_by_state(state)
        if user is None:
            return web.HTTPNotFound()

        await user.get_user_information(code)

        return web.HTTPFound(location=f"{user.redirect_uri}?code={user.code}")

    @staticmethod
    def get_description():
        return "Login via GitHub"

    @staticmethod
    def get_settings_url():
        return f"https://github.com/settings/connections/applications/{GITHUB_CLIENT_ID}"
コード例 #25
0
ファイル: robot.py プロジェクト: LFLab/aio-hubot
 def __init__(self):
     self.holds = dict()
     self.router = web.RouteTableDef()
     self.robot = None
コード例 #26
0
from aiohttp import web, ClientSession, TCPConnector
from aiohttp_jwt import check_permissions, match_any
import re
import json
import sqlalchemy as sa
import datetime
from scripts.help_functions_zbx import async_zabbix_conn, zabbix_conn, get_showed_zabbix, get_zabbix_conf
from views.ws import sio
from scripts.help_functions import json_response, db_connect, JWT_ALGORITHM, JWT_SECRET
import jwt
import pymysql
import asyncio

EventDashboardRoutes = web.RouteTableDef()

metadata = sa.MetaData()
tbl_eventdashboard_filters = sa.Table(
    'eventdashboard_filters', metadata,
    sa.Column('author', sa.String(100), primary_key=True),
    sa.Column('name', sa.String(128), primary_key=True),
    sa.Column('query', sa.String(500), unique=True),
    sa.Column('time', sa.String(128), unique=True),
    sa.Column('row_count', sa.String(30), unique=True),
    sa.Column('severities', sa.String(500), unique=True),
    sa.Column('selected_cols', sa.String(500), unique=True),
    sa.Column('colors', sa.String(1000), unique=True),
    sa.Column('width', sa.String(500), unique=True))


def eventsortkey(val):
    return val['clock']
コード例 #27
0
import asyncio
from aiohttp import web
from . import Response
import json
import asyncpg.exceptions
from .users import validate_api_key

track_routes = web.RouteTableDef()


@track_routes.view('/tracks/{id}')
@track_routes.view('/tracks')
class Track(web.View):
    async def get(self):
        valid, result, user_id = await validate_api_key(self.request)
        if not valid:
            return Response.error(result)

        track_id = None
        if "id" in self.request.match_info:
            track_id = int(self.request.match_info['id'])

        async with (self.request.app['db'].acquire()) as conn:
            async with conn.transaction():
                if not track_id:
                    results = await conn.fetch(
                        '''
                        SELECT id as trck_id, name, album_id, created, updated
                        FROM tracks, 
                            (SELECT id as albm_id
                            FROM albums
コード例 #28
0
ファイル: auth.py プロジェクト: torkve/sorokdva-smarthome
import json
import typing

import aiohttp_jinja2
from aiohttp import web
from aiohttp_security import (
    remember,
    forget,
    authorized_userid,
    check_authorized,
)

from dialogs import db, oauth

route = web.RouteTableDef()


@route.get('/auth', name='auth')
@aiohttp_jinja2.template('index.jinja2')
async def index(request: web.Request):
    user_id = await authorized_userid(request)

    user = None
    clients: typing.List[db.App] = []
    tokens: typing.List[db.Token] = []
    codes: typing.List[db.AuthorizationCode] = []
    if user_id:
        db_session = db.Session()
        user = db_session.query(db.User).get(user_id)
        clients = db_session.query(db.App).all()
        codes = db_session.query(
コード例 #29
0
from aiohttp import web

from openapi.spec.server import server_urls

base_routes = web.RouteTableDef()


@base_routes.get("/")
async def urls(request) -> web.Response:
    paths = set()
    for route in request.app.router.routes():
        route_info = route.get_info()
        path = route_info.get("path", route_info.get("formatter", None))
        paths.add(path)
    return web.json_response(server_urls(request, sorted(paths)))


@base_routes.get("/status")
async def status(request) -> web.Response:
    return web.json_response({})


@base_routes.get("/error")
async def error(request) -> web.Response:
    1 / 0  # noqa
コード例 #30
0
from aiohttp import web
from server.utility import tokens, config

endpoints = web.RouteTableDef()


@endpoints.get("/download")
async def download(request):
    if 'token' not in request.query:
        return web.json_response({'error': "You must provide 'token' field"})

    try:
        secret_key = config(request.app, 'SECRET_KEY')
        target_function, request_args = tokens.parse_request_token(
            secret_key, request.query['token'])
        return await target_function(request, request_args)
    except (ValueError, KeyError):
        return web.json_response({'error': "Invalid token"})