Exemplo n.º 1
0
async def test_nested_blueprint() -> None:
    app = Quart(__name__)

    parent = Blueprint("parent", __name__, url_prefix="/parent")
    child = Blueprint("child", __name__)
    grandchild = Blueprint("grandchild", __name__)
    sibling = Blueprint("sibling", __name__)

    @parent.errorhandler(403)
    async def forbidden(_: Exception) -> ResponseReturnValue:
        return "Parent no", 403

    @parent.route("/")
    async def parent_index() -> ResponseReturnValue:
        return "Parent yes"

    @parent.route("/no")
    async def parent_no() -> ResponseReturnValue:
        abort(403)

    @child.route("/")
    async def child_index() -> ResponseReturnValue:
        return "Child yes"

    @child.route("/no")
    async def child_no() -> ResponseReturnValue:
        abort(403)

    @grandchild.errorhandler(403)
    async def grandchild_forbidden(_: Exception) -> ResponseReturnValue:
        return "Grandchild no", 403

    @grandchild.route("/")
    async def grandchild_index() -> ResponseReturnValue:
        return "Grandchild yes"

    @grandchild.route("/no")
    async def grandchild_no() -> ResponseReturnValue:
        abort(403)

    @sibling.route("/sibling")
    async def sibling_index() -> ResponseReturnValue:
        return "Sibling yes"

    child.register_blueprint(grandchild, url_prefix="/grandchild")
    parent.register_blueprint(child, url_prefix="/child")
    parent.register_blueprint(sibling)
    app.register_blueprint(parent)
    app.register_blueprint(parent, url_prefix="/alt", name="alt")

    client = app.test_client()

    assert (await (await client.get("/parent/")).get_data()) == b"Parent yes"  # type: ignore
    assert (await (await client.get("/parent/child/")).get_data()) == b"Child yes"  # type: ignore
    assert (await (await client.get("/parent/sibling")).get_data()) == b"Sibling yes"  # type: ignore  # noqa: E501
    assert (await (await client.get("/alt/sibling")).get_data()) == b"Sibling yes"  # type: ignore
    assert (await (await client.get("/parent/child/grandchild/")).get_data()) == b"Grandchild yes"  # type: ignore  # noqa: E501
    assert (await (await client.get("/parent/no")).get_data()) == b"Parent no"  # type: ignore
    assert (await (await client.get("/parent/child/no")).get_data()) == b"Parent no"  # type: ignore
    assert (await (await client.get("/parent/child/grandchild/no")).get_data()) == b"Grandchild no"  # type: ignore  # noqa: E501
Exemplo n.º 2
0
async def test_blueprint_renaming() -> None:
    app = Quart(__name__)

    bp = Blueprint("bp", __name__)
    bp2 = Blueprint("bp2", __name__)

    @bp.get("/")
    async def index() -> str:
        return request.endpoint

    @bp.get("/error")
    async def error() -> str:
        abort(403)

    @bp.errorhandler(403)
    async def forbidden(_: Exception) -> ResponseReturnValue:
        return "Error", 403

    @bp2.get("/")
    async def index2() -> str:
        return request.endpoint

    bp.register_blueprint(bp2, url_prefix="/a", name="sub")
    app.register_blueprint(bp, url_prefix="/a")
    app.register_blueprint(bp, url_prefix="/b", name="alt")

    client = app.test_client()

    assert (await (await client.get("/a/")).get_data()) == b"bp.index"  # type: ignore
    assert (await (await client.get("/b/")).get_data()) == b"alt.index"  # type: ignore
    assert (await (await client.get("/a/a/")).get_data()) == b"bp.sub.index2"  # type: ignore
    assert (await (await client.get("/b/a/")).get_data()) == b"alt.sub.index2"  # type: ignore
    assert (await (await client.get("/a/error")).get_data()) == b"Error"  # type: ignore
    assert (await (await client.get("/b/error")).get_data()) == b"Error"  # type: ignore
async def test_blueprint_url_prefix(app: Pint) -> None:
    blueprint = Blueprint('blueprint', __name__)
    prefix = Blueprint('prefix', __name__, url_prefix='/prefix')

    @app.route('/page/')
    @blueprint.route('/page/')
    @prefix.route('/page/')
    async def route() -> ResponseReturnValue:
        return 'OK'

    app.register_blueprint(blueprint, url_prefix='/blueprint')
    app.register_blueprint(prefix)

    async with app.test_request_context('GET', '/'):
        assert '/page/' == url_for('route')
        assert '/prefix/page/' == url_for('prefix.route')
        assert '/blueprint/page/' == url_for('blueprint.route')

    async with app.test_request_context('GET', '/page/'):
        assert request.blueprint is None

    async with app.test_request_context('GET', '/prefix/page/'):
        assert request.blueprint == 'prefix'

    async with app.test_request_context('GET', '/blueprint/page/'):
        assert request.blueprint == 'blueprint'
Exemplo n.º 4
0
def test_unique_blueprint_names() -> None:
    app = Quart(__name__)
    bp = Blueprint("bp", __name__)
    bp2 = Blueprint("bp", __name__)

    app.register_blueprint(bp)
    app.register_blueprint(bp)  # Should not error
    with pytest.raises(ValueError):
        app.register_blueprint(bp2, url_prefix="/a")
    app.register_blueprint(bp, name="alt")
Exemplo n.º 5
0
    def run(self):

        if (self['Key'] == 'data/key.pem') and (self['Cert']
                                                == 'data/cert.pem'):
            if not os.path.exists(self['Key']) or not os.path.exists(
                    self['Cert']) or self['RegenCert']:
                create_self_signed_cert()

        config = Config()
        config.ciphers = 'ALL'
        config.accesslog = './data/logs/access.log'
        config.bind = f"{self['BindIP']}:{self['Port']}"
        config.certfile = self['Cert']
        config.keyfile = self['Key']
        config.include_server_header = False  # This doesn't seem to do anything?
        config.use_reloader = False
        config.debug = False
        """
        While we could use the standard decorators to register these routes, 
        using add_url_rule() allows us to create diffrent endpoint names
        programmatically and pass the classes self object to the routes
        """

        http_blueprint = Blueprint(__name__, 'https')
        http_blueprint.before_request(self.check_if_naughty)
        #http_blueprint.after_request(self.make_normal)

        http_blueprint.add_url_rule('/<uuid:GUID>',
                                    'key_exchange',
                                    self.key_exchange,
                                    methods=['POST'])
        http_blueprint.add_url_rule('/<uuid:GUID>',
                                    'stage',
                                    self.stage,
                                    methods=['GET'])
        http_blueprint.add_url_rule('/<uuid:GUID>/jobs',
                                    'jobs',
                                    self.jobs,
                                    methods=['GET'])
        http_blueprint.add_url_rule('/<uuid:GUID>/jobs/<job_id>',
                                    'job_result',
                                    self.job_result,
                                    methods=['POST'])

        # Add a catch all route
        http_blueprint.add_url_rule('/',
                                    'unknown_path',
                                    self.unknown_path,
                                    defaults={'path': ''})
        http_blueprint.add_url_rule('/<path:path>',
                                    'unknown_path',
                                    self.unknown_path,
                                    methods=['GET', 'POST'])

        #logging.getLogger('quart.app').setLevel(logging.DEBUG if state.args['--debug'] else logging.ERROR)
        #logging.getLogger('quart.serving').setLevel(logging.DEBUG if state.args['--debug'] else logging.ERROR)

        self.app = Quart(__name__)
        self.app.register_blueprint(http_blueprint)
        asyncio.run(serve(self.app, config))
    def run(self):

        """
        While we could use the standard decorators to register these routes, 
        using add_url_rule() allows us to create diffrent endpoint names
        programmatically and pass the classes self object to the routes
        """

        config = Config()
        config.accesslog = os.path.join(get_path_in_data_folder("logs"), "access.log")
        config.bind = f"{self['BindIP']}:{self['Port']}"
        config.insecure_bind = True
        config.include_server_header = False
        config.use_reloader = False
        config.debug = False

        http_blueprint = Blueprint(__name__, 'http')
        http_blueprint.before_request(self.check_if_naughty)
        #http_blueprint.after_request(self.make_normal)

        http_blueprint.add_url_rule('/<uuid:GUID>', 'key_exchange', self.key_exchange, methods=['POST'])
        http_blueprint.add_url_rule('/<uuid:GUID>', 'stage', self.stage, methods=['GET'])
        http_blueprint.add_url_rule('/<uuid:GUID>/jobs', 'jobs', self.jobs, methods=['GET'])
        http_blueprint.add_url_rule('/<uuid:GUID>/jobs/<job_id>', 'job_result', self.job_result, methods=['POST'])

        # Add a catch all route
        http_blueprint.add_url_rule('/', 'unknown_path', self.unknown_path, defaults={'path': ''})
        http_blueprint.add_url_rule('/<path:path>', 'unknown_path', self.unknown_path, methods=['GET', 'POST'])

        #logging.getLogger('quart.app').setLevel(logging.DEBUG if state.args['--debug'] else logging.ERROR)
        #logging.getLogger('quart.serving').setLevel(logging.DEBUG if state.args['--debug'] else logging.ERROR)

        self.app = Quart(__name__)
        self.app.register_blueprint(http_blueprint)
        asyncio.run(serve(self.app, config))
Exemplo n.º 7
0
def handler(doc):
    from quart import Blueprint, request
    from quart.json import jsonify

    swagger_blueprint = Blueprint(doc.blueprint_name,
                                  __name__,
                                  url_prefix=doc.url_prefix,
                                  static_url_path=doc.static_uri_relative,
                                  static_folder=doc.static_dir,
                                  root_path=doc.static_dir)

    @swagger_blueprint.route(doc.root_uri_relative(slashes=True),
                             methods=['GET'])
    async def swagger_blueprint_doc_handler():
        return doc.doc_html

    if doc.editor:

        @swagger_blueprint.route(doc.editor_uri_relative(slashes=True),
                                 methods=['GET'])
        async def swagger_blueprint_editor_handler():
            return doc.editor_html

    @swagger_blueprint.route(doc.swagger_json_uri_relative, methods=['GET'])
    async def swagger_blueprint_config_handler():
        return jsonify(doc.get_config(request.host))

    doc.app.register_blueprint(blueprint=swagger_blueprint,
                               url_prefix=doc.url_prefix)
Exemplo n.º 8
0
    def blueprint(self):
        libp2p = Blueprint('libp2p', __name__, url_prefix='/libp2p')

        @libp2p.route("/subscribe/<topic>", methods=["POST"])
        def subscribe(topic):
            resp = self.subscribe(topic)
            resp.update({'identity': self.p2pd().identify()})
            current_app.logger.info("Done subscribe")
            return jsonify(resp)

        @libp2p.route("/messages", methods=["POST"])
        async def message():
            # {
            #   message: message,
            #   topic: topic
            # }
            current_app.logger.info("Before get json")
            payload = await request.get_json()
            current_app.logger.info("Messages post")
            return jsonify(self.send_message(payload))

        @libp2p.route("/identity", methods=["GET"])
        def identity():
            return jsonify(self.p2pd().identify())

        return libp2p
Exemplo n.º 9
0
def blueprint() -> Blueprint:
    blueprint = Blueprint("blueprint", __name__)

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

    return blueprint
Exemplo n.º 10
0
def blueprint() -> Blueprint:
    blueprint = Blueprint('blueprint', __name__)

    @blueprint.route('/')
    def index() -> str:
        return ''

    return blueprint
Exemplo n.º 11
0
    def run(self):
        """
        While we could use the standard decorators to register these routes, 
        using add_url_rule() allows us to create diffrent endpoint names
        programmatically and pass the classes self object to the routes
        """

        loop = asyncio.get_event_loop()

        http_blueprint = Blueprint(__name__, 'http')
        http_blueprint.before_request(self.check_if_naughty)
        #http_blueprint.after_request(self.make_normal)

        http_blueprint.add_url_rule('/<uuid:GUID>',
                                    'key_exchange',
                                    self.key_exchange,
                                    methods=['POST'])
        http_blueprint.add_url_rule('/<uuid:GUID>',
                                    'stage',
                                    self.stage,
                                    methods=['GET'])
        http_blueprint.add_url_rule('/<uuid:GUID>/jobs',
                                    'jobs',
                                    self.jobs,
                                    methods=['GET'])
        http_blueprint.add_url_rule('/<uuid:GUID>/jobs/<job_id>',
                                    'job_result',
                                    self.job_result,
                                    methods=['POST'])

        # Add a catch all route
        http_blueprint.add_url_rule('/',
                                    'unknown_path',
                                    self.unknown_path,
                                    defaults={'path': ''})
        http_blueprint.add_url_rule('/<path:path>',
                                    'unknown_path',
                                    self.unknown_path,
                                    methods=['GET', 'POST'])

        self.app = Quart(__name__)

        logging.getLogger('quart.app').setLevel(
            logging.DEBUG if state.args['--debug'] else logging.ERROR)
        logging.getLogger('quart.serving').setLevel(
            logging.DEBUG if state.args['--debug'] else logging.ERROR)

        #serving_handler.setFormatter('%(h)s %(p)s - - %(t)s statusline: "%(r)s" statuscode: %(s)s responselen: %(b)s protocol: %(H)s')
        #logging.getLogger('quart.app').removeHandler(default_handler)

        self.app.register_blueprint(http_blueprint)
        self.app.run(
            host=self['BindIP'],
            port=self['Port'],
            debug=False,
            use_reloader=False,
            #access_log_format=,
            loop=loop)
Exemplo n.º 12
0
async def test_root_endpoint_with_blueprint(app):
    blueprint = Blueprint('api', __name__, url_prefix='/api')
    api = restplus.Api(blueprint, version='1.0')
    app.register_blueprint(blueprint)

    async with app.test_request_context():
        url = url_for('api.root')
        assert url == '/api/'
        assert api.base_url == 'http://localhost/api/'
Exemplo n.º 13
0
    async def test_with_blueprint_absolute(self, app, mocker):
        bp = Blueprint('foo', __name__, url_prefix='/foo')
        bp.add_url_rule('/<foo>', 'foobar', view_func=lambda x: x)
        app.register_blueprint(bp)
        field = fields.Url(absolute=True)
        obj = mocker.Mock(foo=42)

        async with app.test_request_context('/foo/foo'):
            assert 'http://localhost/foo/42' == field.output('foo', obj)
Exemplo n.º 14
0
    def __init__(self, app, schema, **options):
        self.app = app
        warnings.warn('GraphQL Blueprint is now deprecated, please use GraphQLView directly')
        self.blueprint = Blueprint('graphql', __name__,
                                   template_folder='templates')

        app.add_url_rule('/graphql', view_func=AsyncGraphQLView.as_view('graphql', schema=schema, **options))

        self.app.register_blueprint(self.blueprint)
Exemplo n.º 15
0
    def run(self):
        if (self['Key'] == f'{self.certs_path}/artic2_private.key') and (
                self['Cert'] == f'{self.certs_path}/artic2_cert.pem'):
            if not os.path.exists(get_path_in_data_folder(
                    "artic2_private.key")) or not os.path.exists(
                        get_path_in_data_folder(
                            "artic2_cert.pem")) or self['RegenCert']:
                create_self_signed_cert()

        config = Config()
        config.ciphers = 'ALL'
        config.accesslog = os.path.join(get_path_in_artic2("logs"),
                                        "access.log")
        config.bind = f"{self['BindIP']}:{self['Port']}"
        config.certfile = os.path.expanduser(self['Cert'])
        config.keyfile = os.path.expanduser(self['Key'])
        config.include_server_header = False
        config.use_reloader = False
        config.debug = False
        """
        While we could use the standard decorators to register these routes, 
        using add_url_rule() allows us to create diffrent endpoint names
        programmatically and pass the classes self object to the routes
        """

        http_blueprint = Blueprint(__name__, 'https')
        http_blueprint.before_request(self.check_if_naughty)

        http_blueprint.add_url_rule('/<uuid:GUID>',
                                    'key_exchange',
                                    self.key_exchange,
                                    methods=['POST'])
        http_blueprint.add_url_rule('/<uuid:GUID>',
                                    'stage',
                                    self.stage,
                                    methods=['GET'])
        http_blueprint.add_url_rule('/<uuid:GUID>/jobs',
                                    'jobs',
                                    self.jobs,
                                    methods=['GET'])
        http_blueprint.add_url_rule('/<uuid:GUID>/jobs/<job_id>',
                                    'job_result',
                                    self.job_result,
                                    methods=['POST'])

        http_blueprint.add_url_rule('/',
                                    'unknown_path',
                                    self.unknown_path,
                                    defaults={'path': ''})
        http_blueprint.add_url_rule('/<path:path>',
                                    'unknown_path',
                                    self.unknown_path,
                                    methods=['GET', 'POST'])

        self.app = Quart(__name__)
        self.app.register_blueprint(http_blueprint)
        asyncio.run(serve(self.app, config))
Exemplo n.º 16
0
    async def test_with_blueprint_invalid_object(self, app):
        bp = Blueprint('foo', __name__, url_prefix='/foo')
        bp.add_url_rule('/<foo>', 'foobar', view_func=lambda x: x)
        app.register_blueprint(bp)
        field = fields.Url()

        async with app.test_request_context('/foo/foo'):
            with pytest.raises(fields.MarshallingError):
                field.output('foo', None)
Exemplo n.º 17
0
async def test_nesting_and_sibling() -> None:
    app = Quart(__name__)

    parent = Blueprint("parent", __name__, url_prefix="/parent")
    child = Blueprint("child", __name__, url_prefix="/child")

    @child.route("/")
    def index() -> ResponseReturnValue:
        return "index"

    parent.register_blueprint(child)
    app.register_blueprint(parent)
    app.register_blueprint(child, url_prefix="/sibling")

    test_client = app.test_client()
    response = await test_client.get("/parent/child/")
    assert response.status_code == 200
    response = await test_client.get("/sibling/")
    assert response.status_code == 200
Exemplo n.º 18
0
async def test_default_apidoc_on_root_with_blueprint(app, client):
    blueprint = Blueprint('api', __name__, url_prefix='/api')
    restplus.Api(blueprint, version='1.0')
    app.register_blueprint(blueprint)

    async with app.test_request_context():
        assert url_for('api.doc') == url_for('api.root')
        response = await client.get(url_for('api.doc'))
    assert response.status_code == 200
    assert response.content_type == 'text/html; charset=utf-8'
Exemplo n.º 19
0
 def test_url_for_with_blueprint(self, app):
     """Verify that url_for works when an Api object is mounted on a
     Blueprint.
     """
     api_bp = Blueprint('api', __name__)
     api = restplus.Api(api_bp)
     api.add_resource(HelloWorld, '/foo/<string:bar>')
     app.register_blueprint(api_bp)
     with app.test_request_context('/foo'):
         assert api.url_for(HelloWorld, bar='baz') == '/foo/baz'
Exemplo n.º 20
0
async def test_root_endpoint_with_blueprint_with_subdomain(app):
    app.url_map.host_matching = True
    app.config['SERVER_NAME'] = 'localhost'
    blueprint = Blueprint('api', __name__, subdomain='api', url_prefix='/api')
    api = restplus.Api(blueprint, version='1.0')
    app.register_blueprint(blueprint)

    async with app.test_request_context():
        url = url_for('api.root', _external=True)
        assert url == 'http://api.localhost/api/'
        assert api.base_url == 'http://api.localhost/api/'
Exemplo n.º 21
0
async def test_default_endpoint_with_blueprint(app):
    blueprint = Blueprint('api', __name__, url_prefix='/api')
    api = restplus.Api(blueprint)
    app.register_blueprint(blueprint)

    @api.route('/test/')
    class TestResource(restplus.Resource):
        pass

    async with app.test_request_context():
        assert url_for('api.test_resource') == '/api/test/'
async def test_root_endpoint_blueprint(app: Pint) -> None:
    blueprint = Blueprint('blueprint', __name__)

    @blueprint.route('/page/')
    async def route() -> ResponseReturnValue:
        return 'OK'

    app.register_blueprint(blueprint)
    async with app.test_request_context('GET', '/page/'):
        assert request.blueprint == 'blueprint'
        assert '/page/' == url_for('blueprint.route')
Exemplo n.º 23
0
async def test_url_for_blueprint_relative(app: Quart) -> None:
    blueprint = Blueprint("blueprint", __name__)

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

    app.register_blueprint(blueprint, url_prefix="/blue")

    async with app.test_request_context("/blue/"):
        assert url_for(".index") == "/blue/"
        assert url_for("index") == "/"
Exemplo n.º 24
0
async def test_blueprint_route() -> None:
    app = Quart(__name__)
    blueprint = Blueprint('blueprint', __name__)

    @blueprint.route('/page/')
    async def route() -> ResponseReturnValue:
        return 'OK'

    app.register_blueprint(blueprint)

    async with app.test_request_context('GET', '/page/'):
        assert request.blueprint == 'blueprint'
Exemplo n.º 25
0
async def test_blueprint_route() -> None:
    app = Quart(__name__)
    blueprint = Blueprint("blueprint", __name__)

    @blueprint.route("/page/")
    async def route() -> ResponseReturnValue:
        return "OK"

    app.register_blueprint(blueprint)

    async with app.test_request_context("/page/"):
        assert request.blueprint == "blueprint"
Exemplo n.º 26
0
async def test_url_for_blueprint_relative(app: Quart) -> None:
    blueprint = Blueprint('blueprint', __name__)

    @blueprint.route('/')
    def index() -> str:
        return ''

    app.register_blueprint(blueprint, url_prefix='/blue')

    async with app.test_request_context('/blue/'):
        assert url_for('.index') == '/blue/'
        assert url_for('index') == '/'
Exemplo n.º 27
0
async def test_nesting_url_prefixes(
    parent_init: Optional[str],
    child_init: Optional[str],
    parent_registration: Optional[str],
    child_registration: Optional[str],
) -> None:
    app = Quart(__name__)

    parent = Blueprint("parent", __name__, url_prefix=parent_init)
    child = Blueprint("child", __name__, url_prefix=child_init)

    @child.route("/")
    def index() -> ResponseReturnValue:
        return "index"

    parent.register_blueprint(child, url_prefix=child_registration)
    app.register_blueprint(parent, url_prefix=parent_registration)

    test_client = app.test_client()
    response = await test_client.get("/parent/child/")
    assert response.status_code == 200
Exemplo n.º 28
0
async def test_blueprint_url_prefix() -> None:
    app = Quart(__name__)
    blueprint = Blueprint("blueprint", __name__)
    prefix = Blueprint("prefix", __name__, url_prefix="/prefix")

    @app.route("/page/")
    @blueprint.route("/page/")
    @prefix.route("/page/")
    async def route() -> ResponseReturnValue:
        return "OK"

    app.register_blueprint(blueprint, url_prefix="/blueprint")
    app.register_blueprint(prefix)

    async with app.test_request_context("/page/"):
        assert request.blueprint is None

    async with app.test_request_context("/prefix/page/"):
        assert request.blueprint == "prefix"

    async with app.test_request_context("/blueprint/page/"):
        assert request.blueprint == "blueprint"
Exemplo n.º 29
0
async def test_default_endpoint_for_namespace_with_blueprint(app):
    blueprint = Blueprint('api', __name__, url_prefix='/api')
    api = restplus.Api(blueprint)
    ns = api.namespace('ns', 'Test namespace')

    @ns.route('/test/')
    class TestResource(restplus.Resource):
        pass

    app.register_blueprint(blueprint)

    async with app.test_request_context():
        assert url_for('api.ns_test_resource') == '/api/ns/test/'
Exemplo n.º 30
0
async def test_blueprint_url_prefix() -> None:
    app = Quart(__name__)
    blueprint = Blueprint('blueprint', __name__)
    prefix = Blueprint('prefix', __name__, url_prefix='/prefix')

    @app.route('/page/')
    @blueprint.route('/page/')
    @prefix.route('/page/')
    async def route() -> ResponseReturnValue:
        return 'OK'

    app.register_blueprint(blueprint, url_prefix='/blueprint')
    app.register_blueprint(prefix)

    async with app.test_request_context("/page/"):
        assert request.blueprint is None

    async with app.test_request_context("/prefix/page/"):
        assert request.blueprint == 'prefix'

    async with app.test_request_context("/blueprint/page/"):
        assert request.blueprint == 'blueprint'