コード例 #1
0
ファイル: server.py プロジェクト: zzBBc/rasa
def configure_cors(app: Sanic, cors_origins: Union[Text, List[Text]] = "") -> None:
    """Configure CORS origins for the given app."""

    # Workaround so that socketio works with requests from other origins.
    # https://github.com/miguelgrinberg/python-socketio/issues/205#issuecomment-493769183
    app.config.CORS_AUTOMATIC_OPTIONS = True
    app.config.CORS_SUPPORTS_CREDENTIALS = True

    CORS(app, resources={r"/*": {"origins": cors_origins}}, automatic_options=True)
コード例 #2
0
def configure_cors(app: Sanic,
                   cors_origins: Union[Text, List[Text], None] = "") -> None:
    """Configure CORS origins for the given app."""

    CORS(app,
         resources={r"/*": {
             "origins": cors_origins or ""
         }},
         automatic_options=True)
コード例 #3
0
    def __init__(self):

        self.app = Sanic()
        CORS(self.app)
        self.document = Document()

        self.app.add_route(self.verify, '/verify', methods=['GET'])
        self.app.add_route(self.publish, '/publish', methods=['POST'])
        self.app.add_route(self.details, '/details', methods=['GET'])
コード例 #4
0
ファイル: run.py プロジェクト: wangy1986/rasa
def configure_app(
    input_channels=None,
    cors=None,
    auth_token=None,
    enable_api=True,
    jwt_secret=None,
    jwt_method=None,
    route="/webhooks/",
    port=None,
):
    """Run the agent."""
    from rasa.core import server

    if enable_api:
        app = server.create_app(
            cors_origins=cors,
            auth_token=auth_token,
            jwt_secret=jwt_secret,
            jwt_method=jwt_method,
        )
    else:
        app = Sanic(__name__)
        CORS(app,
             resources={r"/*": {
                 "origins": cors or ""
             }},
             automatic_options=True)

    if input_channels:
        rasa.core.channels.channel.register(input_channels, app, route=route)
    else:
        input_channels = []

    if logger.isEnabledFor(logging.DEBUG):
        utils.list_routes(app)

    # configure async loop logging
    async def configure_logging():
        if logger.isEnabledFor(logging.DEBUG):
            rasa.utils.io.enable_async_loop_debugging(asyncio.get_event_loop())

    app.add_task(configure_logging)

    if "cmdline" in {c.name() for c in input_channels}:

        async def run_cmdline_io(running_app: Sanic):
            """Small wrapper to shut down the server once cmd io is done."""
            await asyncio.sleep(1)  # allow server to start
            await console.record_messages(
                server_url=constants.DEFAULT_SERVER_FORMAT.format(port))

            logger.info("Killing Sanic server now.")
            running_app.stop()  # kill the sanic serverx

        app.add_task(run_cmdline_io)

    return app
コード例 #5
0
def create_app():
    app = Sanic(__name__)

    CORS(app, resources={r"/api/*": {"origins": "*"}})

    from .controllers import api_blueprint

    app.register_blueprint(api_blueprint)
    return app
コード例 #6
0
def create_app() -> Sanic:
    error_handler = CustomHandler()
    app: Sanic = Sanic(name="stock", error_handler=error_handler)
    app.config.from_object(settings)  # 导入 Sanic 配置
    configure_blueprints(app)  # 配置蓝图
    configure_listeners(app)  # 配置监听:redis
    configure_middlewares(app)  # 配置中间件
    configure_exception_handlers(app)  # 配置异常处理Handler
    CORS(app, automatic_options=True)
    return app
コード例 #7
0
def create_app() -> Sanic:
    error_handler = CustomHandler()
    app: Sanic = Sanic(error_handler=error_handler)
    app.config.PROXIES_COUNT = settings.PROXIES_COUNT
    configure_blueprints(app)
    configure_listeners(app)
    configure_middlewares(app)
    configure_exception_handlers(app)
    CORS(app, automatic_options=True)
    return app
コード例 #8
0
ファイル: sanic.py プロジェクト: sourcery-ai-bot/idom
    def _setup_application(self, app: Sanic, config: Config) -> None:
        cors_config = config["cors"]
        if cors_config:
            cors_params = cors_config if isinstance(cors_config, dict) else {}
            CORS(app, **cors_params)

        bp = Blueprint(f"idom_renderer_{id(self)}",
                       url_prefix=config["url_prefix"])
        self._setup_blueprint_routes(bp, config)
        app.blueprint(bp)
コード例 #9
0
def run(host, port):
    path = os.path.join(os.getcwd(), 'tmp/')
    if not os.path.exists(path):
        os.mkdir(path)

    global app
    app = Sanic()
    CORS(app)
    app.add_route(index, '/', methods=['GET'])
    stage_add_route(app)
    app.run(host=host, port=port)
コード例 #10
0
ファイル: app.py プロジェクト: pratamayuzar/sample-product
def create_app(config):
    """
    Set blueprint for app sanic
    :param config: config decouple
    :return: app sanic
    """
    app = Sanic(__name__)
    app.config.from_object(config)
    app.blueprint(bp_products)
    CORS(app, automatic_options=True)

    return app
コード例 #11
0
ファイル: server.py プロジェクト: furious-luke/polecat
 def __init__(self, project=None, production=False):
     self.project = project or load_project()
     self.project.prepare()
     self.production = production
     self.port = 80 if production else 8000
     self.sanic_app = Sanic()
     CORS(self.sanic_app, automatic_options=True)
     self.sanic_app.add_route(self.index, '/', methods=['GET'])
     self.sanic_app.add_route(
         self.index,
         '/<path:path>',
         methods=['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTION'])
コード例 #12
0
ファイル: app.py プロジェクト: RBozydar/pdrpy4
def init_app(config=None):
    app = Sanic(__name__)
    app.config.update(config or {})
    app.db = functools.partial(
        _get_db,
        host=app.config.get('MONGO_HOST'),
        port=app.config.get('MONGO_PORT'),
        user=app.config.get('MONGO_USER'),
        passwd=app.config.get('MONGO_PASSWD'),
        db_name=app.config.get('MONGO_DB_NAME'),
    )
    CORS(app)
    return app
コード例 #13
0
ファイル: app.py プロジェクト: symbiotes/rpc-proxy
def __app_setup():
    global app

    app = Sanic(__name__)
    CORS(app)

    @app.route("/", methods=["POST"])
    async def index(request: Request):
        return await tunnel(request.json)

    @app.route("/", methods=["GET"])
    async def index_get(request: Request):
        return response.json({"Ecency": "Aspire to greatness", "jussi_num": -1, "status": "OK"})
コード例 #14
0
def main():
    """RBAC API server main event loop"""

    app = Sanic(__name__)
    app.blueprint(AUTH_BP)
    app.blueprint(BLOCKS_BP)
    app.blueprint(CHATBOT_BP)
    app.blueprint(ERRORS_BP)
    app.blueprint(FEED_BP)
    app.blueprint(PACKS_BP)
    app.blueprint(PROPOSALS_BP)
    app.blueprint(ROLES_BP)
    app.blueprint(SEARCH_BP)
    app.blueprint(SWAGGER_BP)
    app.blueprint(TASKS_BP)
    app.blueprint(USERS_BP)
    app.blueprint(WEBHOOKS_BP)
    app.blueprint(APP_BP)

    load_config(app)

    CORS(
        app,
        automatic_options=True,
        supports_credentials=True,
        resources={
            r"/api/*": {
                "origins": "*"
            },
            r"/webhooks/*": {
                "origins": "*"
            }
        },
    )

    zmq = ZMQEventLoop()
    asyncio.set_event_loop(zmq)
    server = app.create_server(host="0.0.0.0",
                               port=app.config.PORT,
                               debug=False,
                               access_log=False)
    loop = asyncio.get_event_loop()
    asyncio.ensure_future(server)
    asyncio.ensure_future(init(app, loop))
    signal(SIGINT, lambda s, f: loop.close())
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        finish(app)
        loop.stop()
コード例 #15
0
    def __init__(self, config=None):
        self.slave_registry = {}
        self.config = config or self._load_config_from_cli()

        self.master_host = self.config[
            'MASTER_HOST'] or self.DEFAULT_MASTER_HOST
        self.master_port = self.config[
            'MASTER_PORT'] or self.DEFAULT_MASTER_PORT
        self.http_port = self.config[
            'MASTER_HTTP_PORT'] or self.DEFAULT_HTTP_PORT

        self.http_server = Sanic(__name__)
        CORS(self.http_server)
        self.create_http_app()
コード例 #16
0
def configure_cors(app: Sanic,
                   cors_origins: Union[Text, List[Text], None] = "") -> None:
    """
    解决跨域问题
    :param app:
    :param cors_origins:
    :return:
    """

    CORS(app,
         resources={r"/*": {
             "origins": cors_origins or ""
         }},
         automatic_options=True)
コード例 #17
0
def configure_extensions(sanic_app):
    """
    Register All of Extensions
    :param sanic_app: sanic app
    :return:
    """
    for extension in core.__all__:
        obj = getattr(core, extension)
        if hasattr(obj, 'init_app'):
            obj.init_app(sanic_app)

    # cors
    if sanic_app.config.get('ENABLE_CORS'):
        CORS(sanic_app)
コード例 #18
0
def create_app(env):
    app = Sanic("auth-center")
    app.config.from_object(env)
    CORS(app, automatic_options=True)
    Redis(app)
    orm = AioOrm(app)
    orm.init_proxys(defaultdb=db)
    orm.create_tables(User=[{
        "_id": uuid.uuid4(),
        "username": "******",
        "password": '******',
        "main_email": "*****@*****.**",
        "ctime": datetime.datetime.now()
    }],
                      Role=[{
                          "service_name": app.name
                      }, {
                          "service_name": "msg_reverse_indexing"
                      }])
    app.serializer = URLSafeTimedSerializer(app.config['SECRET_KEY'],
                                            salt=app.config['SALT'])
    app.blueprint(api, url_prefix='/api')
    app.blueprint(auth, url_prefix='/auth')
    app.blueprint(captcha, url_prefix='/captcha')

    @app.listener('after_server_start')
    async def creat_relationship(app, loop):
        realtionship_table = AioOrm._regist_classes['UserRoleThrough']
        if (await realtionship_table.select().count()) == 0:
            user = await User.get(User.username == "admin")
            roles = await Role.select()
            for role in roles:
                await user.roles.add(role)

    @app.listener('after_server_start')
    async def creat_zmq_client(app, loop):
        #zmq.asyncio.install()
        context = zmq.asyncio.Context()
        socket = context.socket(zmq.REQ)
        print("Connecting to server...")
        socket.connect(app.config["ZMQ_URLS"]['captcha-gene'])
        app.ZMQ_Sockets = {}
        app.ZMQ_Sockets["captcha-gene"] = socket

    @app.get("/ping")
    async def ping(request):
        return json({"message": "pong"})

    return app
コード例 #19
0
ファイル: __init__.py プロジェクト: luckyzwei/xcx-project
def create_app(settings):
    app = Sanic(__name__, log_config=settings['LOGGING_CONFIG_FILE_HANDLER'])
    CORS(app, automatic_options=True)
    app.config.update(**settings)
    app.config.update({'LOGO': None})
    app.blueprint(bp_dog)

    from app.receiver import on_message_common, on_ad_message
    from app.temp_receiver import temp_ad_on_message_commom

    @app.listener('before_server_start')
    async def before_server_start(_app, _loop):
        _app.db = await db.init_app(_loop, _app.config['DATABASES'])
        _app.redis = redis.init_app(_loop, _app.config['REDIS'])
        _app.client_session = csa.init_session(loop=_loop)
        # gbot mq connect
        _app.mq = await sanic_mq.init_app(_loop, _app.config['MQ_CONFIG'])
        await sanic_mq.channel()
        await sanic_mq.exchange('gemii.gbot.topic')
        await sanic_mq.bind_async_receiver('queue.bot.common.dog',
                                           'queue.bot.common.dog',
                                           on_message_common)
        await sanic_mq.bind_async_receiver('queue.bot.common.temp_ad',
                                           'queue.bot.common.temp_ad',
                                           temp_ad_on_message_commom)

        # gdog mq connect
        _app.inner_mq = await inner_mq.init_app(_loop,
                                                _app.config['INNER_MQ_CONFIG'])
        await inner_mq.channel()
        await inner_mq.exchange('gemii.gdog.topic')
        await inner_mq.bind_async_receiver('queue.rs.msg_class',
                                           'queue.rs.msg_class', on_ad_message)

    @app.listener('after_server_stop')
    async def after_server_stop(_app, _loop):
        await _app.client_session.close()
        await _app.db.close()
        _app.redis.connection_pool.disconnect()
        await sanic_mq.disconnection()

    Initialize(app,
               authentication_class=CustomAuthentication,
               responses_class=CustomerResponses,
               refresh_token_enabled=False,
               secret=settings['JWT_SECRET'],
               expiration_delta=1 * 60 * 60)
    return app
コード例 #20
0
async def init_app():
    # 初始化服务进程
    init_pid_name()

    app = Application.current()

    from sanic_cors import CORS

    # 跨域处理
    CORS(app, automatic_options=True)

    from kervice.app.config import init_config
    init_config()

    from kervice.utils.redis_util import init_redis
    init_redis()

    from kervice.app.urls import init_url
    init_url()

    from kervice.utils.log_util import KLog
    from kervice.bussiness.log import log_callback
    KLog(callback=log_callback).init_log()

    # 把服务添加到redis
    app.url = "{}:{}".format(get_host_ip(), app.port)
    st, _ = await app.redis.execute("sadd", "{}.urls".format(app.name),
                                    app.url)
    assert st != 0

    await pp("info:\n  注册服务{} ok".format(app.url), yellow, print)

    # 检查服务状态,检查配置更改,检查队列
    asyncio.run_coroutine_threadsafe(service_check(), asyncio.get_event_loop())
    asyncio.run_coroutine_threadsafe(service_handler(),
                                     asyncio.get_event_loop())

    # 处理服务退出后的问题
    from signal import signal, SIGTERM, SIGINT, SIGQUIT
    _func = lambda sig, stack_frame: asyncio.ensure_future(
        close_service(sig, stack_frame))
    signal(SIGTERM, _func)
    signal(SIGINT, _func)
    signal(SIGQUIT, _func)

    @app.middleware('response')
    async def custom_banner(request, response):
        response.headers["content-type"] = "application/json"
コード例 #21
0
ファイル: server.py プロジェクト: BigJerBD/kankei-backend
def start_server():
    app = get_app()
    config = app.config
    set_logging(config)
    inject_endpoints(app=app, config=config)
    inject_exceptions_responses(app=app, config=config)

    CORS(app, resources={r"/api/*": {"origins": "*"}})

    *host, port = app.config.BACKEND_URL.split(":")
    app.run(
        host="".join(host),
        port=int(port),
        workers=config.WORKER_COUNT,
        debug=config.SANIC_DEBUG,
    )
コード例 #22
0
ファイル: __init__.py プロジェクト: issone/sanic_blog
def create_app():
    app = Sanic(__name__, request_class=Request)
    app.config.from_object(config)

    auth.setup(app)
    CORS(app, automatic_options=True)
    register_blueprints('app.views', app)

    @app.listener('before_server_start')
    async def server_init(app, loop):
        app.db = await db_setup()
        app.redis = await aioredis.create_redis_pool(app.config['REDIS_URL'])
        session.init_app(app=app,
                         interface=AIORedisSessionInterface(app.redis))

    return app
コード例 #23
0
ファイル: routes.py プロジェクト: soda-profiler/backend
def setup_routes(app):
    app.add_route(UserView.as_view(), '/api/v1.0/users')
    app.add_route(ProjectView.as_view(), '/api/v1.0/projects')
    app.add_route(RecordView.as_view(),
                  '/api/v1.0/records',
                  methods=['GET', 'POST', 'OPTIONS'])
    app.add_route(healthView, '/api/v1.0/version', methods=[
        'GET',
    ])
    # app.router.add_static('/static/', path='../static', name='static')
    CORS(app, resources={
        r"/*": {
            "origins": "*"
        },
    }, automatic_options=True)

    return app
コード例 #24
0
ファイル: sanic_app.py プロジェクト: LuanSena/mcPhee
def get_app(session):
    Config.REQUEST_TIMEOUT = 9999999999
    app = Sanic()

    person = PersonBP(session)
    school = SchoolBP(session)
    student = StudentBP(session)
    diary = DiaryBP(session)
    classes = ClassesBP(session)

    app.blueprint(person.blueprint)
    app.blueprint(school.blueprint)
    app.blueprint(student.blueprint)
    app.blueprint(diary.blueprint)
    app.blueprint(classes.blueprint)

    CORS(app)
    return app
コード例 #25
0
def create_app():
    _app = Sanic(__name__)
    _app.config.from_object(DevConfig)
    JWTManager(_app)
    CORS(_app, automatic_options=True)

    _app.blueprint(swagger_blueprint)

    from motor.motor_asyncio import AsyncIOMotorClient

    @_app.listener('before_server_start')
    def init(app, loop):
        _app.db = AsyncIOMotorClient(_app.config.MONGO_URI)['inu']

    from server.api import api
    _app.blueprint(api)

    return _app
コード例 #26
0
ファイル: server_sanic.py プロジェクト: zdong1/allennlp
def run(port: int,
        workers: int,
        trained_models: Dict[str, str],
        static_dir: str = None) -> None:
    """Run the server programatically"""
    print("Starting a sanic server on port {}.".format(port))

    app = make_app(static_dir)
    CORS(app)  # It is acceptible to enable CORS because we have no auth.

    if port != 8000:
        logger.warning("The demo requires the API to be run on port 8000.")

    for predictor_name, archive_file in trained_models.items():
        archive = load_archive(archive_file)
        predictor = Predictor.from_archive(archive, predictor_name)
        app.predictors[predictor_name] = predictor

    app.run(port=port, host="0.0.0.0", workers=workers)
コード例 #27
0
    def _setup_application(self, config: Config, app: Sanic) -> None:
        bp = Blueprint(f"idom_dispatcher_{id(self)}",
                       url_prefix=config["url_prefix"])

        self._setup_blueprint_routes(config, bp)

        self._did_stop = did_stop = Event()

        @app.listener("before_server_stop")  # type: ignore
        async def server_did_stop(app: Sanic,
                                  loop: asyncio.AbstractEventLoop) -> None:
            did_stop.set()

        cors_config = config["cors"]
        if cors_config:  # pragma: no cover
            cors_params = cors_config if isinstance(cors_config, dict) else {}
            CORS(bp, **cors_params)

        app.blueprint(bp)
コード例 #28
0
ファイル: run.py プロジェクト: RobusGauli/ServerProfiler
    def __init__(self, config=None):
        #this object will kep track of all the nodes
        #including the agent nodes and parent Node
        self.nodes = {}
        
        # we will make sure that only one instance of the node
        #is active at any request to the web socket
        
        #get the config object(dict)
        self.config = self._load_args_config()
        self.app = None
        self.clients_alias = None

        self.http_server = Sanic(__name__)
        CORS(self.http_server)

        self.master_server = None
        self.slave_server = None
        self._create_app()
コード例 #29
0
def main():
    parser = argparse.ArgumentParser(description='Fast VectorTile server with PostGIS backend')
    parser.add_argument('--tm2', type=str, help='TM2 source file (yaml)')
    parser.add_argument('--style', type=str, help='GL Style to serve at /style.json')
    parser.add_argument('--pgdatabase', type=str, help='database name', default='osm')
    parser.add_argument('--pghost', type=str, help='postgres hostname', default='')
    parser.add_argument('--pgport', type=int, help='postgres port', default=5432)
    parser.add_argument('--pguser', type=str, help='postgres user', default='')
    parser.add_argument('--pgpassword', type=str, help='postgres password', default='')
    parser.add_argument('--listen', type=str, help='listen address', default='127.0.0.1')
    parser.add_argument('--listen-port', type=str, help='listen port', default=8080)
    parser.add_argument('--cors', action='store_true', help='make cross-origin AJAX possible')
    parser.add_argument('--debug', action='store_true', help='activate sanic debug mode')
    parser.add_argument('--fonts', type=str, help='fonts location')
    args = parser.parse_args()

    if args.tm2:
        if not os.path.exists(args.tm2):
            print(f'file does not exists: {args.tm2}')
            sys.exit(1)
        # build the SQL query for all layers found in TM2 file
        Config.tm2query = prepared_query(args.tm2)
        # add route dedicated to tm2 queries
        app.add_route(get_tile_tm2, r'/<z:int>/<x:int>/<y:int>.pbf', methods=['GET'])

    else:
        # no tm2 file given, switching to direct connection to postgis layers
        app.add_route(get_tile_postgis, r'/<layer>/<z:int>/<x:int>/<y:int>.pbf', methods=['GET'])

    Config.style = args.style
    Config.fonts = args.fonts

    # interpolate values for postgres connection
    Config.dsn = Config.dsn.format(**args.__dict__)

    if args.cors:
        CORS(app)

    app.run(
        host=args.listen,
        port=args.listen_port,
        debug=args.debug)
コード例 #30
0
ファイル: server_sanic.py プロジェクト: zxsted/allennlp
def run(port: int, workers: int,
        trained_models: Dict[str, DemoModel],
        static_dir: str = None) -> None:
    """Run the server programatically"""
    print("Starting a sanic server on port {}.".format(port))

    if port != 8000:
        logger.warning("The demo requires the API to be run on port 8000.")

    # This will be ``None`` if all the relevant environment variables are not defined.
    demo_db = PostgresDemoDatabase.from_environment()

    app = make_app(static_dir, demo_db)
    CORS(app)

    for name, demo_model in trained_models.items():
        predictor = demo_model.predictor()
        app.predictors[name] = predictor

    app.run(port=port, host="0.0.0.0", workers=workers)