Ejemplo n.º 1
0
def test_config_rewrite_keep_alive():
    config = Config()
    assert config.KEEP_ALIVE == DEFAULT_CONFIG["KEEP_ALIVE"]
    config = Config(keep_alive=True)
    assert config.KEEP_ALIVE is True
    config = Config(keep_alive=False)
    assert config.KEEP_ALIVE is False

    # use defaults
    config = Config(defaults={"KEEP_ALIVE": False})
    assert config.KEEP_ALIVE is False
    config = Config(defaults={"KEEP_ALIVE": True})
    assert config.KEEP_ALIVE is True
Ejemplo n.º 2
0
    def __init__(self, name=None, router=None, error_handler=None):
        # Only set up a default log handler if the
        # end-user application didn't set anything up.
        if not logging.root.handlers and log.level == logging.NOTSET:
            formatter = logging.Formatter(
                "%(asctime)s: %(levelname)s: %(message)s")
            handler = logging.StreamHandler()
            handler.setFormatter(formatter)
            log.addHandler(handler)
            log.setLevel(logging.INFO)

        # Get name from previous stack frame
        if name is None:
            frame_records = stack()[1]
            name = getmodulename(frame_records[1])

        self.name = name
        self.router = router or Router()
        self.error_handler = error_handler or ErrorHandler()
        self.config = Config()
        self.request_middleware = deque()
        self.response_middleware = deque()
        self.blueprints = {}
        self._blueprint_order = []
        self.debug = None
        self.sock = None
        self.listeners = defaultdict(list)
        self.is_running = False
        self.websocket_enabled = False
        self.websocket_tasks = []

        # Register alternative method names
        self.go_fast = self.run
Ejemplo n.º 3
0
def test_config_custom_defaults_with_env():
    """
    test that environment variables has higher priority than DEFAULT_CONFIG
    and passed defaults dict
    """
    custom_defaults = {
        "REQUEST_MAX_SIZE123": 1,
        "KEEP_ALIVE123": False,
        "ACCESS_LOG123": False,
    }

    environ_defaults = {
        "SANIC_REQUEST_MAX_SIZE123": "2",
        "SANIC_KEEP_ALIVE123": "True",
        "SANIC_ACCESS_LOG123": "False",
    }

    for key, value in environ_defaults.items():
        environ[key] = value

    conf = Config(defaults=custom_defaults)
    for key, value in DEFAULT_CONFIG.items():
        if "SANIC_" + key in environ_defaults.keys():
            value = environ_defaults["SANIC_" + key]
            try:
                value = int(value)
            except ValueError:
                if value in ["True", "False"]:
                    value = value == "True"

        assert getattr(conf, key) == value

    for key, value in environ_defaults.items():
        del environ[key]
Ejemplo n.º 4
0
Archivo: app.py Proyecto: astagi/sanic
    def __init__(
        self,
        name: str = None,
        router: Router = None,
        error_handler: ErrorHandler = None,
        load_env: bool = True,
        request_class: Type[Request] = None,
        strict_slashes: bool = False,
        log_config: Optional[Dict[str, Any]] = None,
        configure_logging: bool = True,
        register: Optional[bool] = None,
        dumps: Optional[Callable[..., str]] = None,
    ) -> None:
        super().__init__()

        if name is None:
            raise SanicException(
                "Sanic instance cannot be unnamed. "
                "Please use Sanic(name='your_application_name') instead.", )
        # logging
        if configure_logging:
            logging.config.dictConfig(log_config or LOGGING_CONFIG_DEFAULTS)

        self.name = name
        self.asgi = False
        self.router = router or Router()
        self.request_class = request_class
        self.error_handler = error_handler or ErrorHandler()
        self.config = Config(load_env=load_env)
        self.request_middleware: Deque[MiddlewareType] = deque()
        self.response_middleware: Deque[MiddlewareType] = deque()
        self.blueprints: Dict[str, Blueprint] = {}
        self._blueprint_order: List[Blueprint] = []
        self.configure_logging = configure_logging
        self.debug = None
        self.sock = None
        self.strict_slashes = strict_slashes
        self.listeners: Dict[str, List[ListenerType]] = defaultdict(list)
        self.is_stopping = False
        self.is_running = False
        self.websocket_enabled = False
        self.websocket_tasks: Set[Future] = set()
        self.named_request_middleware: Dict[str, Deque[MiddlewareType]] = {}
        self.named_response_middleware: Dict[str, Deque[MiddlewareType]] = {}
        self._test_manager = None
        self._test_client = None
        self._asgi_client = None
        # Register alternative method names
        self.go_fast = self.run

        if register is not None:
            self.config.REGISTER = register

        if self.config.REGISTER:
            self.__class__.register_app(self)

        self.router.ctx.app = self

        if dumps:
            BaseHTTPResponse._dumps = dumps
Ejemplo n.º 5
0
def load_config():
    conf = Config()
    module = os.environ.get('SANIC_SETTINGS_MODULE', 'settings')
    if module:
        path = '%s.py' % module.replace('.', '/')
        conf.from_pyfile(path)
    return conf
Ejemplo n.º 6
0
def load_config():
    conf = Config()
    module = os.environ.get("SANIC_SETTINGS_MODULE", "settings")
    if module:
        path = "%s.py" % module.replace(".", "/")
        conf.from_pyfile(path)
    return conf
Ejemplo n.º 7
0
    def __init__(self, name=None, router=None, error_handler=None,
                 load_env=True, request_class=None,
                 strict_slashes=False, log_config=None,
                 configure_logging=True):

        # Get name from previous stack frame
        if name is None:
            frame_records = stack()[1]
            name = getmodulename(frame_records[1])

        # logging
        if configure_logging:
            logging.config.dictConfig(log_config or LOGGING_CONFIG_DEFAULTS)

        self.name = name
        self.router = router or Router()
        self.request_class = request_class
        self.error_handler = error_handler or ErrorHandler()
        self.config = Config(load_env=load_env)
        self.request_middleware = deque()
        self.response_middleware = deque()
        self.blueprints = {}
        self._blueprint_order = []
        self.configure_logging = configure_logging
        self.debug = None
        self.sock = None
        self.strict_slashes = strict_slashes
        self.listeners = defaultdict(list)
        self.is_running = False
        self.is_request_stream = False
        self.websocket_enabled = False
        self.websocket_tasks = set()

        # Register alternative method names
        self.go_fast = self.run
Ejemplo n.º 8
0
def test_config_defaults():
    """
    load DEFAULT_CONFIG
    """
    conf = Config()
    for key, value in DEFAULT_CONFIG.items():
        assert getattr(conf, key) == value
Ejemplo n.º 9
0
def test_env_w_custom_converter():
    environ["SANIC_TEST_ANSWER"] = "42"

    config = Config(converters=[UltimateAnswer])
    app = Sanic(name=__name__, config=config)
    assert isinstance(app.config.TEST_ANSWER, UltimateAnswer)
    assert app.config.TEST_ANSWER.answer == 42
    del environ["SANIC_TEST_ANSWER"]
Ejemplo n.º 10
0
def load_config():
    conf = Config()
    module = os.environ.get('SANIC_CONFIG_MODULE', None)
    if module:
        path = '%s.py' % module.replace('.', '/')
        conf.from_pyfile(path)
    else:
        import sanicms.config
        conf.from_object(config)
    return conf
Ejemplo n.º 11
0
def auth_func(public_key, request):
    config = Config()
    config.PUBLIC_KEY = public_key
    if request.param:
        config.ALGORITHM = request.param

    @authorized(config)
    async def f(request):
        return json({'status': 'OK'}, 200)

    return f
Ejemplo n.º 12
0
def make_auth_func(public_key, alg=None):
    config = Config()
    config.PUBLIC_KEY = public_key
    if alg:
        config.ALGORITHM = alg

    @authorized(config)
    async def f(request):
        return json({'status': 'OK'}, 200)

    return f
Ejemplo n.º 13
0
    def __init__(self, default_settings):
        """
        Requests for configuration variables not in this class are satisfied
        from the module specified in default_settings (if possible).
        """
        self.__dict__["_deleted"] = set()

        final_settings = Config()
        final_settings.from_object(global_settings)
        final_settings.from_object(default_settings)

        self.default_settings = final_settings
Ejemplo n.º 14
0
    def __init__(
        self,
        name=None,
        router=None,
        error_handler=None,
        load_env=True,
        request_class=None,
        strict_slashes=False,
        log_config=None,
        configure_logging=True,
        register=None,
    ):

        # Get name from previous stack frame
        if name is None:
            raise SanicException(
                "Sanic instance cannot be unnamed. "
                "Please use Sanic(name='your_application_name') instead.", )

        # logging
        if configure_logging:
            logging.config.dictConfig(log_config or LOGGING_CONFIG_DEFAULTS)

        self.name = name
        self.asgi = False
        self.router = router or Router(self)
        self.request_class = request_class
        self.error_handler = error_handler or ErrorHandler()
        self.config = Config(load_env=load_env)
        self.request_middleware = deque()
        self.response_middleware = deque()
        self.blueprints = {}
        self._blueprint_order = []
        self.configure_logging = configure_logging
        self.debug = None
        self.sock = None
        self.strict_slashes = strict_slashes
        self.listeners = defaultdict(list)
        self.is_stopping = False
        self.is_running = False
        self.is_request_stream = False
        self.websocket_enabled = False
        self.websocket_tasks = set()
        self.named_request_middleware = {}
        self.named_response_middleware = {}
        # Register alternative method names
        self.go_fast = self.run

        if register is not None:
            self.config.REGISTER = register

        if self.config.REGISTER:
            self.__class__.register_app(self)
Ejemplo n.º 15
0
    def __init__(
        self,
        name=None,
        router=None,
        error_handler=None,
        load_env=True,
        request_class=None,
        strict_slashes=False,
        log_config=None,
        configure_logging=True,
    ):

        # Get name from previous stack frame
        if name is None:
            warnings.warn(
                "Sanic(name=None) is deprecated and None value support "
                "for `name` will be removed in the next release. "
                "Please use Sanic(name='your_application_name') instead.",
                DeprecationWarning,
                stacklevel=2,
            )
            frame_records = stack()[1]
            name = getmodulename(frame_records[1])

        # logging
        if configure_logging:
            logging.config.dictConfig(log_config or LOGGING_CONFIG_DEFAULTS)

        self.name = name
        self.asgi = False
        self.router = router or Router()
        self.request_class = request_class
        self.error_handler = error_handler or ErrorHandler()
        self.config = Config(load_env=load_env)
        self.request_middleware = deque()
        self.response_middleware = deque()
        self.blueprints = {}
        self._blueprint_order = []
        self.configure_logging = configure_logging
        self.debug = None
        self.sock = None
        self.strict_slashes = strict_slashes
        self.listeners = defaultdict(list)
        self.is_stopping = False
        self.is_running = False
        self.is_request_stream = False
        self.websocket_enabled = False
        self.websocket_tasks = set()
        self.named_request_middleware = {}
        self.named_response_middleware = {}
        # Register alternative method names
        self.go_fast = self.run
Ejemplo n.º 16
0
def test_add_converter_multiple_times(caplog):
    def converter():
        ...

    message = (
        "Configuration value converter 'converter' has already been registered"
    )
    config = Config()
    config.register_type(converter)
    with caplog.at_level(logging.WARNING):
        config.register_type(converter)

    assert ("sanic.error", logging.WARNING, message) in caplog.record_tuples
    assert len(config._converters) == 5
Ejemplo n.º 17
0
def create(params=None, load_env=True):
    config = Config(load_env=False)
    config.update(
        dict([(k, v.default) for k, v in DefaultConfig.__fields__.items()]))

    if load_env:
        if isinstance(load_env, bool):
            load_env = SANIC_ENV_PREFIX
        config.load_environment_vars(prefix=load_env)

    if params:
        config.update(params)
    DefaultConfig.validate(config)
    return config
Ejemplo n.º 18
0
def test_config_custom_defaults():
    """
    we should have all the variables from defaults rewriting them with custom defaults passed in
    Config
    """
    custom_defaults = {
        "REQUEST_MAX_SIZE": 1,
        "KEEP_ALIVE": False,
        "ACCESS_LOG": False,
    }
    conf = Config(defaults=custom_defaults)
    for key, value in DEFAULT_CONFIG.items():
        if key in custom_defaults.keys():
            value = custom_defaults[key]
        assert getattr(conf, key) == value
Ejemplo n.º 19
0
    def get_sanic_config(self) -> Config:
        c = Config()
        c.LOGO = self.logo
        c.REQUEST_MAX_SIZE = self.request_max_size
        c.REQUEST_TIMEOUT = self.request_timeout
        c.RESPONSE_TIMEOUT = self.response_timeout
        c.KEEP_ALIVE = self.keep_alive
        c.KEEP_ALIVE_TIMEOUT = self.keep_alive_timeout
        c.WEBSOCKET_MAX_SIZE = self.websocket_max_size
        c.WEBSOCKET_MAX_QUEUE = self.websocket_max_queue
        c.WEBSOCKET_READ_LIMIT = self.websocket_read_limit
        c.WEBSOCKET_WRITE_LIMIT = self.websocket_write_limit
        c.GRACEFUL_SHUTDOWN_TIMEOUT = self.graceful_shutdown_timeout
        c.ACCESS_LOG = self.access_log

        return c
Ejemplo n.º 20
0
def make_app(view=None, database=None):
    if not view:
        view = View({"HTML_TEMPLATES_DIR": settings.TEMPLATES_DIR})
    if not database:
        database = PostgresqlDatabase(database=settings.DATABASE)

    app = Sanic(__name__)
    app.config = Config()
    app.config.LOGO = "Atlantis! Go FAST!"
    app.config.REQUEST_MAX_SIZE = 2000000  # 2 megababies
    app.config.REQUEST_TIMEOUT = 60 * 5  # 5 min
    app.static('/static', settings.STATIC_DIR)

    @app.middleware('response')
    async def halt_response(request, response):
        response.headers['Content-Security-Policy'] = \
            "default-src 'self' 'unsafe-inline';"

    return app
Ejemplo n.º 21
0
 def __init__(self, name=None, router=None,
              error_handler=None, logger=None):
     if logger is None:
         logging.basicConfig(
             level=logging.INFO,
             format="%(asctime)s: %(levelname)s: %(message)s"
         )
     if name is None:
         frame_records = stack()[1]
         name = getmodulename(frame_records[1])
     self.name = name
     self.router = router or Router()                    # 路由
     self.error_handler = error_handler or Handler(self)   # 错误处理
     self.config = Config()                                # 默认配置项
     self.loop = None
     self.debug = None
     self.sock = None
     self.processes = None
     self.request_middleware = deque()                   # 请求中间件
     self.response_middleware = deque()                  # 响应中间件
     self.blueprints = {}  # 蓝图
     self._blueprint_order = []
Ejemplo n.º 22
0
def run_migrations_online():
    """Run migrations in 'online' mode.

    In this scenario we need to create an Engine
    and associate a connection with the context.

    """

    alembic_config = config.get_section(config.config_ini_section)
    app_config_file = config.get_section('app')['config_file']
    app_config = Config()
    app_config.from_pyfile(app_config_file)
    alembic_config['sqlalchemy.url'] = app_config.DATABASE_URL

    engine = engine_from_config(alembic_config)

    with engine.connect() as connection:
        context.configure(connection=connection,
                          target_metadata=target_metadata)

        with context.begin_transaction():
            context.run_migrations()
Ejemplo n.º 23
0
def passwd():
    """ Change UNIX password for a user.

	This is required if the password changed on the backend
	"""

    import asyncio
    from getpass import getpass
    from tortoise import Tortoise
    from sanic.config import Config
    from .user import User

    parser = argparse.ArgumentParser(description='Change user password.')
    parser.add_argument('user', help='Unix username of user')
    args = parser.parse_args()

    config = Config()
    config.from_envvar('BAWWAB_SETTINGS')
    User.setup(config.DATABASE_PASSWORD_KEY)

    async def run():
        await Tortoise.init(db_url=config.DATABASE_URL,
                            modules={'models': ['bawwab.user']})
        try:
            user = await User.get_or_none(name=args.user)
            pass1 = getpass('Enter new password: '******'Re-enter new password: '******'Passwords do not match', file=sys.stderr)
                return 1
            user.password = pass1.strip()
            await user.save()
            return 0
        finally:
            await Tortoise.close_connections()

    return asyncio.run(run())
Ejemplo n.º 24
0
async def prepare_configs(before_start, app, loop):
    app.configs = {}

    app.pool = await prepare_database({'dsn': ADMIN_SERVICE_DATABASE_URL})

    # mainnet
    mainnet_eth = await create_pool(MAINNET_ETH_SERVICE_DATABASE_URL,
                                    min_size=1,
                                    max_size=3)
    mainnet_id = await create_pool(MAINNET_ID_SERVICE_DATABASE_URL,
                                   min_size=1,
                                   max_size=3)
    mainnet_dir = None  # await create_pool(MAINNET_DIR_SERVICE_DATABASE_URL, min_size=1, max_size=3)
    mainnet_rep = await create_pool(MAINNET_REP_SERVICE_DATABASE_URL,
                                    min_size=1,
                                    max_size=3)
    app.configs['mainnet'] = Config(
        "mainnet", mainnet_eth, mainnet_id, mainnet_dir, mainnet_rep,
        MAINNET_ETHEREUM_NODE_URL, MAINNET_ID_SERVICE_URL,
        MAINNET_ETH_SERVICE_URL, MAINNET_DIR_SERVICE_URL,
        MAINNET_REP_SERVICE_URL)

    # dev
    dev_eth = await create_pool(DEV_ETH_SERVICE_DATABASE_URL,
                                min_size=1,
                                max_size=3)
    dev_id = await create_pool(DEV_ID_SERVICE_DATABASE_URL,
                               min_size=1,
                               max_size=3)
    dev_dir = None  # await create_pool(DEV_DIR_SERVICE_DATABASE_URL, min_size=1, max_size=3)
    dev_rep = await create_pool(DEV_REP_SERVICE_DATABASE_URL,
                                min_size=1,
                                max_size=3)
    app.configs['dev'] = Config("dev", dev_eth, dev_id, dev_dir, dev_rep,
                                DEV_ETHEREUM_NODE_URL, DEV_ID_SERVICE_URL,
                                DEV_ETH_SERVICE_URL, DEV_DIR_SERVICE_URL,
                                DEV_REP_SERVICE_URL)

    # internal
    internal_eth = await create_pool(INTERNAL_ETH_SERVICE_DATABASE_URL,
                                     min_size=1,
                                     max_size=3)
    internal_id = await create_pool(INTERNAL_ID_SERVICE_DATABASE_URL,
                                    min_size=1,
                                    max_size=3)
    internal_dir = None  # await create_pool(INTERNAL_DIR_SERVICE_DATABASE_URL, min_size=1, max_size=3)
    internal_rep = await create_pool(INTERNAL_REP_SERVICE_DATABASE_URL,
                                     min_size=1,
                                     max_size=3)
    app.configs['internal'] = Config(
        "internal", internal_eth, internal_id, internal_dir, internal_rep,
        INTERNAL_ETHEREUM_NODE_URL, INTERNAL_ID_SERVICE_URL,
        INTERNAL_ETH_SERVICE_URL, INTERNAL_DIR_SERVICE_URL,
        INTERNAL_REP_SERVICE_URL)

    # configure http client
    app.http = aiohttp.ClientSession()
    if before_start:
        f = before_start()
        if asyncio.iscoroutine(f):
            await f
Ejemplo n.º 25
0
    def __init__(
        self,
        name: str = None,
        config: Optional[Config] = None,
        ctx: Optional[Any] = None,
        router: Optional[Router] = None,
        signal_router: Optional[SignalRouter] = None,
        error_handler: Optional[ErrorHandler] = None,
        load_env: Union[bool, str] = True,
        env_prefix: Optional[str] = SANIC_PREFIX,
        request_class: Optional[Type[Request]] = None,
        strict_slashes: bool = False,
        log_config: Optional[Dict[str, Any]] = None,
        configure_logging: bool = True,
        register: Optional[bool] = None,
        dumps: Optional[Callable[..., str]] = None,
    ) -> None:
        super().__init__(name=name)

        # logging
        if configure_logging:
            logging.config.dictConfig(log_config or LOGGING_CONFIG_DEFAULTS)

        if config and (load_env is not True or env_prefix != SANIC_PREFIX):
            raise SanicException(
                "When instantiating Sanic with config, you cannot also pass "
                "load_env or env_prefix")

        self._asgi_client = None
        self._blueprint_order: List[Blueprint] = []
        self._test_client = None
        self._test_manager = None
        self.asgi = False
        self.auto_reload = False
        self.blueprints: Dict[str, Blueprint] = {}
        self.config = config or Config(load_env=load_env,
                                       env_prefix=env_prefix)
        self.configure_logging = configure_logging
        self.ctx = ctx or SimpleNamespace()
        self.debug = None
        self.error_handler = error_handler or ErrorHandler()
        self.is_running = False
        self.is_stopping = False
        self.listeners: Dict[str, List[ListenerType]] = defaultdict(list)
        self.named_request_middleware: Dict[str, Deque[MiddlewareType]] = {}
        self.named_response_middleware: Dict[str, Deque[MiddlewareType]] = {}
        self.request_class = request_class
        self.request_middleware: Deque[MiddlewareType] = deque()
        self.response_middleware: Deque[MiddlewareType] = deque()
        self.router = router or Router()
        self.signal_router = signal_router or SignalRouter()
        self.sock = None
        self.strict_slashes = strict_slashes
        self.websocket_enabled = False
        self.websocket_tasks: Set[Future] = set()

        # Register alternative method names
        self.go_fast = self.run

        if register is not None:
            self.config.REGISTER = register
        if self.config.REGISTER:
            self.__class__.register_app(self)

        self.router.ctx.app = self

        if dumps:
            BaseHTTPResponse._dumps = dumps
Ejemplo n.º 26
0
from sanic.config import Config

from . import base as base_config
from .log import get_log_config

config = Config(load_env=False)
config.from_object(base_config)
config.load_environment_vars('SIP_')

log_config = get_log_config(config)
Ejemplo n.º 27
0
from sanic import Sanic
from sanic.config import Config
from sanic.exceptions import (NotFound, ServerError, RequestTimeout,
                              InvalidUsage)
from sanic.request import Request
from sanic.response import (json, HTTPResponse)
from sanic.router import REGEX_TYPES

from science.celeryconfig import CeleryConfig
from science.config import (configs, environment)
from science.tools.protocols import Protocol
from science.tools.utils import imgur_parser

log: Logger = Logger("__ml_web__")
app: Sanic = Sanic("__ml_web__")
app.config: Config = Config()
app.config.LOGO: Optional[str] = None
app.config.REQUEST_TIMEOUT: int = 300  # 5 mins
app.config.REQUEST_MAX_SIZE: int = 1_048_576  # 1 MB
celery: Celery = Celery("tasks")
celery.config_from_object(CeleryConfig)

UUID4_REGEX: str = r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\Z"
REGEX_TYPES.update({"uuid": (str, UUID4_REGEX)})


@app.exception(RequestTimeout)
def error_408(request: Request, exception: RequestTimeout) -> HTTPResponse:
    """Request Time out.
    :param request: Request
    :param exception: RequestTimeout
Ejemplo n.º 28
0
 def _init_config(self):
     self.config = Config(load_env=True)
     self.config.from_object(GeneralConfig)
Ejemplo n.º 29
0
def create_development_app() -> Sanic:
    """Return a :class:`Sanic` app instance in debug mode"""
    return Sanic(f"idom_development_app_{uuid4().hex}", Config())
Ejemplo n.º 30
0
 def __init__(self):
     self.config = Config()