Python quart.Quart() Examples

The following are 30 code examples of quart.Quart(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module quart , or try the search function .
Example #1
Source File: test_helpers.py    From quart with MIT License 7 votes vote down vote up
def test_stream_with_context() -> None:
    app = Quart(__name__)

    @app.route("/")
    async def index() -> AsyncGenerator[bytes, None]:
        @stream_with_context
        async def generator() -> AsyncGenerator[bytes, None]:
            yield request.method.encode()
            yield b" "
            yield request.path.encode()

        return generator()

    test_client = app.test_client()
    response = await test_client.get("/")
    result = await response.get_data(raw=True)
    assert result == b"GET /"  # type: ignore 
Example #2
Source File: test_views.py    From quart with MIT License 6 votes vote down vote up
def test_view_decorators(app: Quart) -> None:
    def decorate_status_code(func: Callable) -> Callable:
        async def wrapper(*args: Any, **kwargs: Any) -> ResponseReturnValue:
            response = await func(*args, **kwargs)
            return response, 201

        return wrapper

    class Views(View):
        decorators = [decorate_status_code]
        methods = ["GET"]

        async def dispatch_request(self, *args: Any, **kwargs: Any) -> ResponseReturnValue:
            return request.method

    app.add_url_rule("/", view_func=Views.as_view("simple"))

    test_client = app.test_client()
    response = await test_client.get("/")
    assert response.status_code == 201 
Example #3
Source File: test_helpers.py    From quart with MIT License 6 votes vote down vote up
def app() -> Quart:
    app = Quart(__name__)
    app.config["SERVER_NAME"] = SERVER_NAME
    app.secret_key = "secret"

    @app.route("/")
    async def index() -> str:
        return ""

    async def index_post() -> str:
        return ""

    app.add_url_rule("/post", view_func=index_post, methods=["POST"], endpoint="index_post")

    @app.route("/resource/<int:id>")
    async def resource(id: int) -> str:
        return str(id)

    return app 
Example #4
Source File: test_templating.py    From quart with MIT License 6 votes vote down vote up
def test_template_tests(app: Quart, blueprint: Blueprint) -> None:
    @blueprint.app_template_test()
    def blueprint_test(value: int) -> bool:
        return value == 5

    @app.template_test()
    def app_test(value: int) -> bool:
        return value == 3

    app.register_blueprint(blueprint)

    async with app.app_context():
        rendered = await render_template_string("{% if 3 is app_test %}foo{% endif %}")
    assert rendered == "foo"

    async with app.test_request_context("/"):
        rendered = await render_template_string("{% if 5 is blueprint_test %}bar{% endif %}")
    assert rendered == "bar" 
Example #5
Source File: __init__.py    From code-jam-5 with MIT License 6 votes vote down vote up
def create_app(test_config=None):
    app = Quart(__name__, instance_relative_config=True)
    app.config.from_mapping(SECRET_KEY='dev')
    app.config.from_pyfile('config.py', silent=True)

    if test_config is not None:
        app.config.from_mapping(test_config)

    app.register_blueprint(view.bp)

    app.azavea = azavea.Client(app.config['AZAVEA_TOKEN'])

    @app.after_serving
    async def teardown(*args):
        await app.azavea.teardown()

    return app 
Example #6
Source File: main.py    From FlowKit with Mozilla Public License 2.0 6 votes vote down vote up
def create_app():
    app = Quart(__name__)

    app.config.from_mapping(get_config())

    jwt = JWTManager(app)
    app.before_serving(connect_logger)
    app.before_serving(create_db)
    app.before_request(add_uuid)
    app.before_request(connect_zmq)
    app.teardown_request(close_zmq)

    @app.route("/")
    async def root():
        return ""

    app.register_blueprint(query_endpoints_blueprint, url_prefix="/api/0")
    app.register_blueprint(geography_blueprint, url_prefix="/api/0")
    app.register_blueprint(spec_blueprint, url_prefix="/api/0/spec")

    register_logging_callbacks(jwt)
    jwt.user_loader_callback_loader(user_loader_callback)

    return app 
Example #7
Source File: test_templating.py    From quart with MIT License 6 votes vote down vote up
def test_template_filters(app: Quart, blueprint: Blueprint) -> None:
    @blueprint.app_template_filter()
    def blueprint_filter(value: str) -> str:
        return value.upper()

    @app.template_filter()
    def app_filter(value: str) -> str:
        return value.lower()

    app.register_blueprint(blueprint)

    async with app.app_context():
        rendered = await render_template_string("{{ 'App' | app_filter }}")
    assert rendered == "app"

    async with app.test_request_context("/"):
        rendered = await render_template_string("{{ 'App' | blueprint_filter }}")
    assert rendered == "APP" 
Example #8
Source File: test_asgi.py    From quart with MIT License 6 votes vote down vote up
def test_websocket_accept_connection(
    scope: dict, headers: Headers, subprotocol: Optional[str], has_headers: bool
) -> None:
    connection = ASGIWebsocketConnection(Quart(__name__), scope)
    mock_send = CoroutineMock()
    await connection.accept_connection(mock_send, headers, subprotocol)

    if has_headers:
        mock_send.assert_called_with(
            {
                "subprotocol": subprotocol,
                "type": "websocket.accept",
                "headers": _encode_headers(headers),
            }
        )
    else:
        mock_send.assert_called_with({"subprotocol": subprotocol, "type": "websocket.accept"}) 
Example #9
Source File: test_templating.py    From quart with MIT License 6 votes vote down vote up
def test_template_globals(app: Quart, blueprint: Blueprint) -> None:
    @blueprint.app_template_global()
    def blueprint_global(value: str) -> str:
        return value.upper()

    @app.template_global()
    def app_global(value: str) -> str:
        return value.lower()

    app.register_blueprint(blueprint)

    async with app.app_context():
        rendered = await render_template_string(
            "{{ app_global('BAR') }} {{ blueprint_global('foo') }}"
        )
    assert rendered == "bar FOO" 
Example #10
Source File: test_testing.py    From quart with MIT License 6 votes vote down vote up
def test_cookie_jar() -> None:
    app = Quart(__name__)
    app.secret_key = "secret"

    @app.route("/", methods=["GET"])
    async def echo() -> Response:
        foo = session.get("foo")
        bar = request.cookies.get("bar")
        session["foo"] = "bar"
        response = jsonify({"foo": foo, "bar": bar})
        response.set_cookie("bar", "foo")
        return response

    client = Client(app)
    response = await client.get("/")
    assert (await response.get_json()) == {"foo": None, "bar": None}
    response = await client.get("/")
    assert (await response.get_json()) == {"foo": "bar", "bar": "foo"} 
Example #11
Source File: test_testing.py    From quart with MIT License 6 votes vote down vote up
def test_session_transactions() -> None:
    app = Quart(__name__)
    app.secret_key = "secret"

    @app.route("/")
    async def index() -> str:
        return str(session["foo"])

    test_client = app.test_client()

    async with test_client.session_transaction() as local_session:
        assert len(local_session) == 0
        local_session["foo"] = [42]
        assert len(local_session) == 1
    response = await test_client.get("/")
    assert (await response.get_data()) == b"[42]"  # type: ignore
    async with test_client.session_transaction() as local_session:
        assert len(local_session) == 1
        assert local_session["foo"] == [42] 
Example #12
Source File: test_testing.py    From quart with MIT License 5 votes vote down vote up
def test_build_headers_path_and_query_string_with_query_string_error() -> None:
    with pytest.raises(ValueError):
        make_test_headers_path_and_query_string(Quart(__name__), "/?a=b", None, {"c": "d"}) 
Example #13
Source File: test_helpers.py    From quart with MIT License 5 votes vote down vote up
def test_url_for_scheme(app: Quart) -> None:
    async with app.test_request_context("/"):
        with pytest.raises(ValueError):
            url_for("index", _scheme="https")
        assert url_for("index", _scheme="https", _external=True) == "https://localhost/"
        assert (
            url_for("resource", id=5, _scheme="https", _external=True)
            == "https://localhost/resource/5"
        ) 
Example #14
Source File: homepage.py    From yobot with GNU General Public License v3.0 5 votes vote down vote up
def register_routes(self, app: Quart):

        @app.route(self.public_basepath, ["GET"])
        async def yobot_homepage():
            return await render_template(
                "homepage.html",
                verinfo=self.setting["verinfo"]["ver_name"],
                show_icp=self.setting["show_icp"],
                icp_info=self.setting["icp_info"],
                gongan_info=self.setting["gongan_info"],
            )

        @app.route(
            urljoin(self.public_basepath, 'about/'),
            methods=['GET'])
        async def yobot_about():
            return await render_template(
                "about.html",
                verinfo=self.setting["verinfo"]["ver_name"],
            )

        @app.route("/favicon.ico", ["GET"])
        async def yobot_favicon():
            return await send_from_directory(static_folder, "small.ico")

        @app.route(
            urljoin(self.public_basepath, 'help/'),
            methods=['GET'])
        async def yobot_help():
            return await send_from_directory(template_folder, "help.html")

        @app.route(
            urljoin(self.public_basepath, 'manual/'),
            methods=['GET'])
        async def yobot_manual():
            return await send_from_directory(template_folder, "manual.html") 
Example #15
Source File: test_sync.py    From quart with MIT License 5 votes vote down vote up
def test_sync_request_context(app: Quart) -> None:
    test_client = app.test_client()
    response = await test_client.get("/")
    assert b"GET" in (await response.get_data())  # type: ignore
    response = await test_client.post("/")
    assert b"POST" in (await response.get_data())  # type: ignore 
Example #16
Source File: test_sync.py    From quart with MIT License 5 votes vote down vote up
def test_sync_generator(app: Quart) -> None:
    test_client = app.test_client()
    response = await test_client.get("/gen")
    result = await response.get_data()
    assert result[-2:] == b"bb"  # type: ignore
    assert int(result[:-2]) != threading.current_thread().ident 
Example #17
Source File: main.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def connect_logger():
    log_level = current_app.config["FLOWAPI_LOG_LEVEL"]
    logger = root_logger.getChild("debug")
    logger.setLevel(log_level)
    ch = logging.StreamHandler()
    ch.setLevel(log_level)
    logger.addHandler(ch)
    # Debug logger. Quart doesn't allow us to override current_app.logger, but won't use it by default.
    current_app.flowapi_logger = structlog.wrap_logger(logger)
    current_app.flowapi_logger.debug("Started")

    # Logger for authentication

    logger = root_logger.getChild("access")
    logger.setLevel(logging.INFO)
    ch = logging.StreamHandler(sys.stdout)
    ch.setLevel(log_level)
    logger.addHandler(ch)
    # Debug logger. Quart doesn't allow us to override current_app.logger, but won't use it by default.
    current_app.access_logger = structlog.wrap_logger(logger)

    # Logger for all queries run or accessed
    logger = root_logger.getChild("query")
    logger.setLevel(logging.INFO)
    ch = logging.StreamHandler(sys.stdout)
    ch.setLevel(log_level)
    logger.addHandler(ch)
    current_app.query_run_logger = structlog.wrap_logger(logger) 
Example #18
Source File: gacha.py    From yobot with GNU General Public License v3.0 5 votes vote down vote up
def register_routes(self, app: Quart):

        @app.route(
            urljoin(self.setting['public_basepath'], 'gacha/'),
            methods=['GET'])
        async def yobot_gacha():
            return await render_template('gacha.html') 
Example #19
Source File: test_testing.py    From async-asgi-testclient with MIT License 5 votes vote down vote up
def test_exception_quart(quart_app):
    @quart_app.route("/raiser")
    async def error():
        assert 1 == 0

    async with TestClient(quart_app) as client:
        resp = await client.get("/raiser")
        # Quart suppresses all type of exceptions
        assert resp.status_code == 500 
Example #20
Source File: test_testing.py    From quart with MIT License 5 votes vote down vote up
def test_with_usage() -> None:
    app = Quart(__name__)
    app.secret_key = "secret"

    @app.route("/")
    async def index() -> str:
        session["hello"] = "world"
        return "Hello"

    async with app.test_client() as client:
        await client.get("/")
        assert request.method == "GET"
        assert session["hello"] == "world" 
Example #21
Source File: custom.py    From yobot with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self,
                 glo_setting: Dict[str, Any],
                 scheduler: AsyncIOScheduler,
                 app: Quart,
                 bot_api: Api,
                 *args, **kwargs):
        '''
        初始化,只在启动时执行一次

        参数:
            glo_setting 包含所有设置项,具体见default_config.json
            bot_api 是调用机器人API的接口,具体见<https://python-aiocqhttp.cqp.moe/>
            scheduler 是与机器人一同启动的AsyncIOScheduler实例
            app 是机器人后台Quart服务器实例
        '''
        # 注意:这个类加载时,asyncio事件循环尚未启动,且bot_api没有连接
        # 此时不要调用bot_api
        # 此时没有running_loop,不要直接使用await,请使用asyncio.ensure_future并指定loop=asyncio.get_event_loop()

        # 如果需要启用,请注释掉下面一行
        return

        # 这是来自yobot_config.json的设置,如果需要增加设置项,请修改default_config.json文件
        self.setting = glo_setting

        # 这是cqhttp的api,详见cqhttp文档
        self.api = bot_api

        # # 注册定时任务,详见apscheduler文档
        # @scheduler.scheduled_job('cron', hour=8)
        # async def good_morning():
        #     await self.api.send_group_msg(group_id=123456, message='早上好')

        # # 注册web路由,详见flask与quart文档
        # @app.route('/is-bot-running', methods=['GET'])
        # async def check_bot():
        #     return 'yes, bot is running' 
Example #22
Source File: test_testing.py    From quart with MIT License 5 votes vote down vote up
def test_build_headers_path_and_query_string(
    path: str, query_string: Optional[dict], expected_path: str, expected_query_string: bytes
) -> None:
    headers, result_path, result_qs = make_test_headers_path_and_query_string(
        Quart(__name__), path, None, query_string
    )
    assert result_path == expected_path
    assert headers["Remote-Addr"] == "127.0.0.1"
    assert headers["User-Agent"] == "Quart"
    assert headers["host"] == "localhost"
    assert result_qs == expected_query_string 
Example #23
Source File: test_testing.py    From quart with MIT License 5 votes vote down vote up
def test_methods() -> None:
    app = Quart(__name__)

    methods = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "TRACE"]

    @app.route("/", methods=methods)
    async def echo() -> str:
        return request.method

    client = Client(app)

    for method in methods:
        func = getattr(client, method.lower())
        response = await func("/")
        assert method in (await response.get_data(raw=False)) 
Example #24
Source File: test_helpers.py    From quart with MIT License 5 votes vote down vote up
def test_url_for_anchor(app: Quart) -> None:
    async with app.test_request_context("/"):
        assert url_for("index", _anchor="&foo") == "/#%26foo"
        assert url_for("resource", id=5, _anchor="&foo") == "/resource/5#%26foo" 
Example #25
Source File: test_testing.py    From quart with MIT License 5 votes vote down vote up
def test_query_string() -> None:
    app = Quart(__name__)

    @app.route("/", methods=["GET"])
    async def echo() -> Response:
        data = request.args
        return jsonify(**data)

    client = Client(app)
    response = await client.get("/", query_string={"a": "b"})
    assert (await response.get_json()) == {"a": "b"} 
Example #26
Source File: test_helpers.py    From quart with MIT License 5 votes vote down vote up
def test_url_for_external(app: Quart) -> None:
    async with app.test_request_context("/"):
        assert url_for("index") == "/"
        assert url_for("index", _external=True) == "http://localhost/"
        assert url_for("resource", id=5, _external=True) == "http://localhost/resource/5"
        assert url_for("resource", id=5, _external=False) == "/resource/5"

    async with app.app_context():
        assert url_for("index") == "http://localhost/"
        assert url_for("index", _external=False) == "/" 
Example #27
Source File: test_helpers.py    From quart with MIT License 5 votes vote down vote up
def test_url_for_host_matching(host_matched_app: Quart) -> None:
    async with host_matched_app.app_context():
        assert url_for("index", _external=True) == "http:///"
        assert url_for("host", _external=True) == "http://quart.com/" 
Example #28
Source File: test_helpers.py    From quart with MIT License 5 votes vote down vote up
def test_url_for(app: Quart) -> None:
    async with app.test_request_context("/"):
        assert url_for("index") == "/"
        assert url_for("index_post", _method="POST") == "/post"
        assert url_for("resource", id=5) == "/resource/5" 
Example #29
Source File: test_helpers.py    From quart with MIT License 5 votes vote down vote up
def test_flash_category(app: Quart) -> None:
    async with app.test_request_context("/"):
        await flash("bar", "error")
        await flash("foo", "info")
        assert get_flashed_messages(with_categories=True) == [("error", "bar"), ("info", "foo")]
        assert get_flashed_messages() == [] 
Example #30
Source File: test_helpers.py    From quart with MIT License 5 votes vote down vote up
def test_flash(app: Quart) -> None:
    async with app.test_request_context("/"):
        await flash("message")
        assert get_flashed_messages() == ["message"]
        assert get_flashed_messages() == []