Пример #1
0
def create_app():
    app = Sanic(__name__, log_config=current_config.LOG_SETTINGS)
    configure_sentry(app)
    logger = logging.getLogger(__file__)
    logger.info("Server started successfully", {
        "text": "testing logging",
        "nested": {
            "more": "data"
        }
    })

    @app.listener('before_server_start')
    async def setup_db(app, loop):
        logger.info(
            'before server start...............setting up middleware, DB')
        connect('test_starscream')

    @app.listener('before_server_start')
    async def register_middleware(app, loop):
        logger.info(
            'before server start...............setting up middleware, blueprints'
        )
        from app.api.routes.routes_v1 import api_v1_blueprint
        # @TODO: Implement attach_middleware(adds client's device info)
        # attach_middleware(app)
        app.blueprint(api_v1_blueprint)

    # adds /metrics endpoint to your Sanic server
    monitor(app).expose_endpoint()
    return app
Пример #2
0
def serve():
    monitor(app, endpoint_type="url").expose_endpoint()
    app.run(host="0.0.0.0", port=app.config.PORT, debug=app.config.DEBUG)
    loop = asyncio.get_event_loop()
    if not loop.is_closed():
        pending = asyncio.Task.all_tasks()
        loop.run_until_complete(asyncio.gather(*pending))
Пример #3
0
def launch_server():
    app = Sanic('test_mp')

    @app.route('/test')
    async def test(request):
        return json({'a': 'b'})

    monitor(app).expose_endpoint()
    app.run(port=TEST_PORT, workers=2)
    def __init__(self,
                 log_namespace: str,
                 name=None,
                 router=None,
                 error_handler=None,
                 load_env=True,
                 request_class=Request,
                 strict_slashes=False,
                 log_config=sanic_log_config,
                 configure_logging=True):
        super(Server, self).__init__(name=name,
                                     router=router,
                                     error_handler=error_handler,
                                     load_env=load_env,
                                     request_class=request_class,
                                     strict_slashes=strict_slashes,
                                     log_config=log_config,
                                     configure_logging=configure_logging)

        self.config.from_object(sanic_config)

        # Set logging namespace
        CONFIG.LOGGING.namespace = log_namespace

        # Enable prometheus metrics?
        if CONFIG.APP.prometheus_metrics_enabled:
            logging.info(
                "Prometheus metrics enabled: Enabling /metrics endpoint.")
            monitor(self).expose_endpoint()

        logging.info("Initialised Sanic server",
                     extra={
                         "params": {
                             "name": name,
                             "router": router,
                             "error_handler": error_handler,
                             "load_env": load_env,
                             "request_class": request_class,
                             "strict_slashes": strict_slashes,
                             "log_config": log_config,
                             "configure_logging": configure_logging
                         }
                     })
Пример #5
0
 def test_start_server_should_not_work_with_mp(self):
     app = Sanic('test_mp')
     self.assertRaises(SanicPrometheusError, monitor(app).start_server)
Пример #6
0
@app.route('/errors')
async def raise_exception(request):
    raise ServerError("Ooops, sh*t happened!", status_code=500)


@app.route('/health')
async def healthcheck(request):
    try:
        async with app.pool.acquire() as conn:
            async with conn.transaction():
                resp = await conn.fetchval('SELECT 1;')
                if resp:
                    return response.json({
                        'db_access_ok': True,
                        'version': VERSION
                    })
                else:
                    raise
    except Exception as e:
        return response.json({
            'db_access_ok': False,
            'info': str(e),
            'version': VERSION
        })


if __name__ == '__main__':
    monitor(app).expose_endpoint()
    app.run(host='0.0.0.0', debug=os.getenv('DEBUG'))
Пример #7
0

app = Sanic(__name__)
CORS(app, automatic_options=True)
app.static("/", "client/dist/index.html")
app.static("/main.css", "client/dist/main.css")
app.static("/main.js", "client/dist/main.js")
app.static("/assets", "client/dist/assets")
ldap = LDAPAuth(os.environ["GD_LDAP_DSN"])


try:
    try:
        monitor_port = int(os.environ["GD_PROMETHEUS_PORT"])
    except (KeyError, ValueError):
        monitor(app).expose_endpoint()
    else:
        monitor(app).start_server(addr="0.0.0.0", port=monitor_port)
except OSError as exc:
    # https://github.com/prometheus/client_python/issues/155
    if exc.errno != 98:  # TODO: Remove all this OSError workaround
        raise            # after this Prometheus client bug gets fixed


class AuthError(Exception):
    pass


async def authenticate(username, password):
    if not (isinstance(username, str) and isinstance(password, str)):
        raise AuthError("Invalid data type")
Пример #8
0
app.error_handler.add(UniqueViolationError, unique_violation_error_handler)


async def init_plugins(app, loop):
    await db.gino.create_all()
    # await cache.clear()


# Register the listeners
app.register_listener(init_plugins, "after_server_start")

# Register background tasks
from ora_backend.tasks.assign import check_for_reassign_chats_every_half_hour

app.add_task(check_for_reassign_chats_every_half_hour())

# Register Prometheus
try:
    # import prometheus_client as prometheus
    from sanic_prometheus import monitor
except Exception:
    pass
else:
    if MODE == "production":
        # Adds /metrics endpoint to the Sanic server
        monitor(
            app,
            endpoint_type="url",
            latency_buckets=[0.01, 0.05, 0.1, 0.25, 0.5, 1, 10, 30, 60, 120],
        ).expose_endpoint()