Пример #1
0
def app():
    try:
        app = sanic.Sanic("test_sanic_app", register=False)
    except TypeError as e:
        if str(e
               ) != "__init__() got an unexpected keyword argument 'register'":
            raise
        app = sanic.Sanic("test_sanic_app")
    yield app
Пример #2
0
def create_api_app(name='api', limit=5, public=tuple()):
    app = sanic.Sanic(name=name)

    app.public = public
    app.logger = sanic.log.logger
    app.limiter = create_api_limit_handler(app, limit)

    app.error_handler = create_api_error_handler()
    app.error_handler.add(sanic.exceptions.NotFound,
                          lambda r, e: sanic.response.empty(status=404))

    @app.middleware('request')
    async def api_query_params(request):
        request.ctx.params = get_request_params(request)

    @app.middleware('request')
    async def api_query_session(request):
        request.ctx.conn = await engine.connect().__aenter__()

    @app.middleware('request')
    async def api_auth(request):
        if request.path not in request.app.public:
            if (token := request.ctx.params.get('token')) is None:
                token = request.headers.get('token')
            try:
                assert token is not None, 'authentication token is missing'
                # TODO: Validate JWT_ADMIN_SECRET, JWT_SECRET
                # TODO: Decode token and set user id
                #jwt_auth_validate(token, request.path)
            except AssertionError as e:
                raise sanic.exceptions.Unauthorized(str(e))
            except Exception as e:
                raise ValueError('invalid token format')
Пример #3
0
def start(config, task):
    """
    Start a simple server with the specified configuration. If an app needs
    more elaborate setup, then just copy this function and modify.
    """
    start_cfg = config['start']
    log.info('Starting app with ' +
             ', '.join(['{}={}'.format(k, v) for k, v in start_cfg.items()]))
    app = sanic.Sanic(log_config=None)
    app.config.RESPONSE_TIMEOUT = 3600
    app.config.KEEP_ALIVE_TIMEOUT = 75

    # Websocket handling
    @app.websocket('/ws')
    async def handle_ws(request, ws):
        log.info('New websocket client')
        ws_handler = WebsocketHandler(ws, config['features'])
        await ws_handler.handle_incoming_requests()

    # Static file handling
    static_dir = location + start_cfg['static_dir']
    app.static('/static', static_dir)

    @app.route('/')
    async def home_page(request):
        return await sanic.response.file(static_dir + '/index.html')

    # Optionally invoke a caller-specified task once the event loop is up
    if task is not None:
        app.add_task(task)

    # Enter event loop
    app.run(host=start_cfg['host'], port=start_cfg['port'])
Пример #4
0
def start(config, task):
    """
    Start a simple server with the specified configuration. If an app needs
    more elaborate setup, then just copy this function and modify.
    """
    start_cfg = config["start"]
    log.info(
        "Starting app with %s",
        ", ".join(["{}={}".format(k, v) for k, v in start_cfg.items()]),
    )
    app = sanic.Sanic(name="entrance-app", log_config=None)
    app.config.RESPONSE_TIMEOUT = 3600
    app.config.KEEP_ALIVE_TIMEOUT = 75

    # Websocket handling
    @app.websocket("/ws")
    async def handle_ws(request, ws):
        log.info("New websocket client")
        ws_handler = WebsocketHandler(ws, config["features"])
        await ws_handler.handle_incoming_requests()

    # Static file handling
    static_dir = location + start_cfg["static_dir"]
    app.static("/", static_dir)

    @app.route("/")
    async def home_page(request):
        return await sanic.response.file(static_dir + "/index.html")

    # Optionally invoke a caller-specified task once the event loop is up
    if task is not None:
        app.add_task(task)

    # Enter event loop
    app.run(host=start_cfg["host"], port=start_cfg["port"])
Пример #5
0
def json_tb_app():
    # Create app
    app = sanic.Sanic("json_tb_app")
    TestManager(app)
    from sanic_json_logging import LOGGING_CONFIG_DEFAULTS as cfg

    cfg["formatters"]["generic"]["class"] = "sanic_json_logging.formatters.JSONTracebackJSONFormatter"
    setup_json_logging(app, config=cfg)

    @app.route("/test_exception", methods=["GET"])
    async def test_exception(request):
        raise Exception("foo")
        return response.text("")

    @app.route("/test_get", methods=["GET"])
    async def test_get(request):
        logger = logging.getLogger("sanic.info")

        class MyClass:
            def __str__(self):
                return "my class"

        logger.info(MyClass())
        return response.text("")

    return app
Пример #6
0
    def __init__(self, config, *, loop=None):
        self.app = app = sanic.Sanic(__name__, configure_logging=False)
        self.config = app.cfg = config

        self.loop = loop = loop or asyncio.get_event_loop()

        self.session = app.session = None
        self.fish = app.fish = None
        self.db = app.db = None

        app.config['LOGO'] = None

        app.blueprint(api.bp_group)
        app.blueprint(spoopy.spoopy.bp)
        app.blueprint(spoopy.websocket.bp)

        app.static("/", "./spoopy-site/build/index.html")
        app.static("/static", "./spoopy-site/build/static")
        app.static("/site", "./spoopy-site/build/index.html")
        app.static("/docs", "./spoopy-site/build/index.html")
        app.static("/faq", "./spoopy-site/build/index.html")
        app.static("/about", "./spoopy-site/build/index.html")
        app.static("/robots.txt", "./spoopy-site/robots.txt")

        app.error_handler.add(sanic.exceptions.NotFound, ignore_404s)
        app.error_handler.add(sanic.exceptions.MethodNotSupported,
                              ignore_methods)

        # Register middleware which starts database connections
        app.register_listener(self.worker_stop, 'after_server_stop')
        app.register_listener(self.worker_init, 'before_server_start')

        app.add_task(download_phish_test)
Пример #7
0
def create_app():
    app = sanic.Sanic(__name__)
    app.blueprint(views.bp)
    app.add_websocket_route(notify.feed, '/_notify/<paste_id:[A-Za-z0-9]+>')
    app.config.from_object(base_config)
    if 'DISCODE_CONFIG' in os.environ:
        app.config.from_envvar('DISCODE_CONFIG')
    app.static('/static', './static')

    app.middleware('request')(session.add_to_request)
    app.middleware('response')(session.save_session)

    sentry_dsn = app.config['SENTRY_DSN']
    sentry_client = raven.Client(sentry_dsn)

    @app.exception(Exception)
    def handle_exceptions(request, exception):
        sentry_client.captureException()

    @app.listener('before_server_start')
    async def setup_connection(app, loop):
        app.config.DB = await db.create_engine(app.config.DATABASE, loop=loop)

    @app.listener('after_server_stop')
    async def close_connection(app, loop):
        app.config.DB.close()
        await app.config.DB.wait_closed()

    return app
Пример #8
0
def app(loop):
    args = jussi.serve.parse_args(args=[])
    # run app
    app = sanic.Sanic('testApp')
    app.config.args = args
    app.config.args.server_port = 42101
    app.config.args.websocket_pool_minsize = 0
    app.config.args.websocket_pool_maxsize = 1
    app = jussi.logging_config.setup_logging(app)
    app = jussi.serve.setup_routes(app)
    app = jussi.middlewares.setup_middlewares(app)
    app = jussi.errors.setup_error_handlers(app)
    app = jussi.listeners.setup_listeners(app)

    try:
        loop.run_until_complete(app.config.cache_group.clear())
    except BaseException:
        pass

    yield app

    try:
        loop.run_until_complete(app.config.cache_group.clear())
    except BaseException:
        pass

    del app.config
Пример #9
0
async def _app(config):
    app = sanic.Sanic()
    app.config.update(config)
    app.config.update({
        'DB_KWARGS':
        dict(
            max_inactive_connection_lifetime=_MAX_INACTIVE_CONNECTION_LIFETIME,
        ),
    })

    db = Gino(app)

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

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

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

    @app.route('/users/<uid:int>')
    async def get_user(request, uid):
        method = request.args.get('method')
        q = User.query.where(User.id == uid)
        if method == '1':
            return json((await q.gino.first_or_404()).to_dict())
        elif method == '2':
            return json((await
                         request['connection'].first_or_404(q)).to_dict())
        elif method == '3':
            return json((await db.bind.first_or_404(q)).to_dict())
        elif method == '4':
            return json((await db.first_or_404(q)).to_dict())
        else:
            return json((await User.get_or_404(uid)).to_dict())

    @app.route('/users', methods=['POST'])
    async def add_user(request):
        u = await User.create(nickname=request.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 json(u.to_dict())

    e = await gino.create_engine(PG_URL)
    try:
        try:
            await db.gino.create_all(e)
            await yield_(app)
        finally:
            await db.gino.drop_all(e)
    finally:
        await e.close()
Пример #10
0
    def __init__(self,
                 schemas_path: str,
                 base_uri: str,
                 schema_includes: dict,
                 sanic_config: dict,
                 app_name: str = "schemas"):
        # Mapping of path name to schema
        schemas = {}
        paths = os.path.join(schemas_path, "**", "*.json")
        for path in glob.iglob(paths, recursive=True):
            with open(path) as fd:
                schema = json.load(fd)
            includes = {**schema_includes, 'base': base_uri}
            subpath = os.path.relpath(path, schemas_path)
            schemas[subpath] = _format_schema(schema, includes)

        async def root(request, path: str = ''):
            if path not in schemas:
                return sanic.response.raw(b'', status=404)
            return sanic.response.json(schemas[path])

        app = sanic.Sanic(app_name)
        app.add_route(root, "/")
        app.add_route(root, "/<path:path>")
        app.run(**sanic_config)
Пример #11
0
def make_sanic_app(config,
                   username,
                   password,
                   prefix=PREFIX,
                   blueprint_namespace="rq_dashboard",
                   redis_url='redis://127.0.0.1:6379'):
    """Return Sanic app with default configuration and registered blueprint."""
    app = sanic.Sanic(__name__)

    # Used in testing
    if redis_url:
        app.config['RQ_DASHBOARD_REDIS_URL'] = 'redis://127.0.0.1:6379'

    # Override with any settings in config file, if given.
    if config:
        app.config.from_object(importlib.import_module(config))

    # Override from a configuration file in the env variable, if present.
    if "RQ_DASHBOARD_SETTINGS" in os.environ:
        app.config.from_envvar("RQ_DASHBOARD_SETTINGS")

    # Optionally add basic auth to blueprint and register with app.
    blueprint = setup(app, prefix, blueprint_namespace, username, password)
    app.blueprint(blueprint)
    return app
Пример #12
0
def generic_app():
    # Create app
    app = sanic.Sanic("generic_app")
    TestManager(app)
    setup_json_logging(app)

    logger = logging.getLogger("myapplogger")

    async def log():
        logger.info("some informational message", extra={"test1": "test"})

    @app.route("/test_get", methods=["GET"])
    async def test_get(request):
        await log()
        return response.text("")

    @app.route("/test_exception", methods=["GET"])
    async def test_exception(request):
        try:
            raise ValueError("ugh")
        except ValueError as err:
            logger.exception("some exception", exc_info=err)

        return response.text("")

    return app
Пример #13
0
async def _app(config):
    app = sanic.Sanic()
    app.config.update(config)
    app.config.update({
        "DB_KWARGS":
        dict(
            max_inactive_connection_lifetime=_MAX_INACTIVE_CONNECTION_LIFETIME,
        ),
    })

    db = Gino(app)

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

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

    @app.route("/")
    async def root(request):
        conn = await request["connection"].get_raw_connection()
        # noinspection PyProtectedMember
        assert conn._holder._max_inactive_time == _MAX_INACTIVE_CONNECTION_LIFETIME
        return text("Hello, world!")

    @app.route("/users/<uid:int>")
    async def get_user(request, uid):
        method = request.args.get("method")
        q = User.query.where(User.id == uid)
        if method == "1":
            return json((await q.gino.first_or_404()).to_dict())
        elif method == "2":
            return json((await
                         request["connection"].first_or_404(q)).to_dict())
        elif method == "3":
            return json((await db.bind.first_or_404(q)).to_dict())
        elif method == "4":
            return json((await db.first_or_404(q)).to_dict())
        else:
            return json((await User.get_or_404(uid)).to_dict())

    @app.route("/users", methods=["POST"])
    async def add_user(request):
        u = await User.create(nickname=request.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 json(u.to_dict())

    e = await gino.create_engine(PG_URL)
    try:
        try:
            await db.gino.create_all(e)
            yield app
        finally:
            await db.gino.drop_all(e)
    finally:
        await e.close()
Пример #14
0
 def serve(self, host, port):
     self.app = sanic.Sanic()
     self.app.add_route(self.log_handler, '/', methods=['POST'])
     self.app.add_route(self.read_handler, '/', methods=['GET'])
     self.app.add_route(self.ping_handler, '/ping', methods=['POST'])
     self.app.add_route(self.remove_handler, '/', methods=['DELETE'])
     # todo: need a file serving url
     self.app.run(host=host, port=port, debug=Params.debug)
Пример #15
0
def get_app():
    app = sanic.Sanic(__name__)

    @app.route('/')
    async def hello(request):
        return text('hello')

    return app
Пример #16
0
 def __init__(self, loop, postCallback):
     super().__init__()
     self._app = sanic.Sanic(__name__, configure_logging=False)
     self._app.add_route(self.handle_post, "/", methods=["POST"])
     self._app.add_route(self.handle_get, "/", methods=["GET"])
     self._host = "0.0.0.0"
     self._port = 8000
     self._loop = loop
     self._postCallback = postCallback
Пример #17
0
async def app():
    app = sanic.Sanic()
    app.config['DB_HOST'] = DB_ARGS['host']
    app.config['DB_PORT'] = DB_ARGS['port']
    app.config['DB_USER'] = DB_ARGS['user']
    app.config['DB_PASSWORD'] = DB_ARGS['password']
    app.config['DB_DATABASE'] = DB_ARGS['database']

    db = Gino(app)

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

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

    @app.route('/')
    async def root(request):
        return text('Hello, world!')

    @app.route('/users/<uid:int>')
    async def get_user(request, uid):
        method = request.args.get('method')
        q = User.query.where(User.id == uid)
        if method == '1':
            return json((await q.gino.first_or_404()).to_dict())
        elif method == '2':
            return json((await
                         request['connection'].first_or_404(q)).to_dict())
        elif method == '3':
            return json((await db.bind.first_or_404(q)).to_dict())
        elif method == '4':
            return json((await db.first_or_404(q)).to_dict())
        else:
            return json((await User.get_or_404(uid)).to_dict())

    @app.route('/users', methods=['POST'])
    async def add_user(request):
        u = await User.create(nickname=request.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 json(u.to_dict())

    e = await gino.create_engine(PG_URL)
    try:
        try:
            await db.gino.create_all(e)
            yield app
        finally:
            await db.gino.drop_all(e)
    finally:
        await e.close()
Пример #18
0
 def serve(self, host, port, workers):
     import sanic
     self.app = sanic.Sanic("ml_logger.server")
     self.app.add_route(self.log_handler, '/', methods=['POST'])
     self.app.add_route(self.read_handler, '/', methods=['GET'])
     self.app.add_route(self.stream_handler, '/stream', methods=['GET'])
     self.app.add_route(self.ping_handler, '/ping', methods=['POST'])
     self.app.add_route(self.glob_handler, '/glob', methods=['POST'])
     self.app.add_route(self.remove_handler, '/', methods=['DELETE'])
     # todo: need a file serving url
     self.app.run(host=host, port=port, workers=workers, debug=Params.debug)
Пример #19
0
def app():
    args = jussi.serve.parse_args(args=[])
    # run app
    app = sanic.Sanic('testApp')
    app.config.args = args
    app.config.args.server_port = 42101
    app = jussi.logging_config.setup_logging(app)
    app = jussi.serve.setup_routes(app)
    app = jussi.middlewares.setup_middlewares(app)
    app = jussi.errors.setup_error_handlers(app)
    app = jussi.listeners.setup_listeners(app)
    yield app
    def __init__(self, config, *, loop=None):
        self.app = app = sanic.Sanic(configure_logging=False)
        self.config = app.cfg = config

        self.loop = loop = loop or asyncio.get_event_loop()

        self.db = app.db = None
        self.session = app.session = aiohttp.ClientSession(loop=loop)

        app.config['LOGO'] = None

        app.blueprint(api_routes)
        app.add_route(self.root, '/', methods=['GET', 'HEAD'])
Пример #21
0
    def __init__(self, host, port, job_queue, sample_factory,
                 request_queue_size, db_con):
        """ Initialise a new server and start it. All error conditions are
        returned as exceptions.

        @param host: The local address to bind the socket to.
        @type host: String
        @param port: The local port to listen on for client connections.
        @type port: int
        @param job_queue: A reference to the job queue for submission of
                          samples.
        @type job_queue: JobQueue
        @param sample_factory: A reference to a sample factory for creating new
                               samples.
        @type sample_factory: SampleFactory
        @param request_queue_size: Number of requests that may be pending on
                                   the socket.
        @type request_queue_size: int
        """
        logger.debug('Starting up server.')
        self.app = sanic.Sanic("PeekabooAV", configure_logging=False)
        self.app.config.FALLBACK_ERROR_FORMAT = "json"

        # silence sanic to a reasonable amount
        logging.getLogger('sanic.root').setLevel(logging.WARNING)
        logging.getLogger('sanic.access').setLevel(logging.WARNING)

        self.loop = asyncio.get_event_loop()
        self.server_coroutine = self.app.create_server(
            host=host,
            port=port,
            return_asyncio_server=True,
            backlog=request_queue_size,
            asyncio_server_kwargs=dict(start_serving=False))
        self.server = None
        self.job_queue = job_queue
        self.sample_factory = sample_factory
        self.db_con = db_con
        # remember for diagnostics
        self.host = host
        self.port = port

        self.app.add_route(self.hello, '/')
        self.app.add_route(self.ping, '/ping')
        self.app.add_route(self.scan, "/v1/scan", methods=['POST'])
        self.app.add_route(self.report,
                           '/v1/report/<job_id:int>',
                           methods=['GET'])
    def create_app():
        app = sanic.Sanic(__name__)

        @app.route('/')
        def index(request):
            return json('test sanic trace')  # pragma: NO COVER

        @app.route('/_ah/health')
        def health_check(request):
            return json('test health check')  # pragma: NO COVER

        @app.route('/error')
        def error(request):
            raise Exception('error')

        return app
def _user_logging(headers, extra, expected, provide_request=False):
    app = sanic.Sanic(__name__)

    @app.route('/test/user/logging')
    async def _logging_correlation_id_route(request):
        logger, stream = config_logger('user.logging')
        new_extra = extend(extra,
                           {'request': request}) if provide_request else extra
        logger.info('in route headers', extra=new_extra)
        assert check_log_record(stream, JOB_LOG_SCHEMA, expected) == {}
        return text('ok')

    _set_up_sanic_logging(app)
    client = app.test_client
    _check_expected_response(
        client.get('/test/user/logging', headers=headers)[1])
Пример #24
0
def creates_app():
    """Create the application

    Returns:
        [sanic.Sanic]: the main application
    """

    LOGGER.info("Create application %s", app_version.RELEASE)
    app = sanic.Sanic(__name__)
    app.static('/static', './static')
    errors.add_exceptions_handlers(app)
    app.blueprint(version.bp)
    app.blueprint(health.bp)
    setup_openapi(app)
    setup_metrics(app)

    return app
Пример #25
0
def test_middleware_error_handler(loop, rpc_req, error, expected):
    app = sanic.Sanic('test_text')
    # pylint: disable=unused-argument,unused-variable
    @app.post('/')
    def handler(request):
        return sanic.response.text('Hello')

    @app.middleware('request')
    @handle_middleware_exceptions
    async def error_middleware(request):
        raise error

    req, response = app.test_client.post('/', json=rpc_req)
    assert response.headers['Content-Type'] == 'application/json'
    assert response.status == 200
    response_json = loop.run_until_complete(response.json())
    assert response_json == expected
Пример #26
0
def custom_log_app():
    # Create app
    app = sanic.Sanic("custom_log_app")
    TestManager(app)
    setup_json_logging(app)

    logger = logging.getLogger("myapplogger")

    @app.route("/test_get", methods=["GET"])
    async def test_get(request):
        class MyClass:
            def __str__(self):
                return "my class"

        logger.info(MyClass())
        return response.text("")

    return app
Пример #27
0
def pytest_collection_modifyitems(session, config, items):
    base_port = sanic.testing.PORT

    worker_id = getattr(config, 'slaveinput', {}).get('slaveid', 'master')
    m = re.search(r'[0-9]+', worker_id)
    if m:
        num_id = int(m.group(0)) + 1
    else:
        num_id = 0
    new_port = base_port + num_id

    def new_test_client(app, port=new_port):
        return sanic.testing.SanicTestClient(app, port)

    sanic.Sanic.test_port = new_port
    sanic.Sanic.test_client = property(new_test_client)

    app = sanic.Sanic()
    assert app.test_client.port == new_port
Пример #28
0
def get_app():
    app = sanic.Sanic(__name__)

    from .db import init_app
    init_app(app)

    from .redis.aioredis import init_app
    init_app(app)

    from .session.redis import Session
    Session.install(app)

    from .auth.api import init_app
    init_app(app)

    from .auth.login import init_app
    init_app(app)

    return app
Пример #29
0
def test_middleware_error_handler(rpc_req, error, expected):
    app = sanic.Sanic('test_text')

    # pylint: disable=unused-argument,unused-variable

    @app.post('/')
    def handler(request):
        return sanic.response.text('Hello')

    @app.middleware('request')
    @handle_middleware_exceptions
    async def error_middleware(request):
        raise error

    req, response = app.test_client.post('/', json=rpc_req)
    assert response.headers['Content-Type'] == 'application/json'
    assert response.status == 200
    if response.json['error']['data']['error_id'] != '123':
        response.json['error']['data']['error_id'] = '123'
    assert response.json == expected
Пример #30
0
    def __init__(self, *, loop=None):
        self.app = app = sanic.Sanic(__name__, configure_logging=False)

        self.loop = loop = loop or asyncio.get_event_loop()

        self.secret = app.secret = secrets.token_urlsafe(256)
        self.session = app.session = None
        self.db = app.db = None
        self.last_worker_update = self.app.last_worker_update = datetime.datetime.now() - datetime.timedelta(minutes=30)

        app.config['LOGO'] = None

        app.blueprint(api.bp_group)

        app.error_handler.add(sanic.exceptions.NotFound, ignore_404s)
        app.error_handler.add(sanic.exceptions.MethodNotSupported, ignore_methods)

        # Register middleware which starts database connections
        app.register_listener(self.worker_stop, 'after_server_stop')
        app.register_listener(self.worker_init, 'before_server_start')