Example #1
0
def test_bp_static(app):
    current_file = inspect.getfile(inspect.currentframe())
    with open(current_file, "rb") as file:
        current_file_contents = file.read()

    blueprint = Blueprint("test_static")

    blueprint.static("/testing.file", current_file)

    app.blueprint(blueprint)

    request, response = app.test_client.get("/testing.file")
    assert response.status == 200
    assert response.body == current_file_contents
Example #2
0
def test_bp_static():
    current_file = inspect.getfile(inspect.currentframe())
    with open(current_file, 'rb') as file:
        current_file_contents = file.read()

    app = Sanic('test_static')
    blueprint = Blueprint('test_static')

    blueprint.static('/testing.file', current_file)

    app.blueprint(blueprint)

    request, response = sanic_endpoint_test(app, uri='/testing.file')
    assert response.status == 200
    assert response.body == current_file_contents
def test_bp_static():
    current_file = inspect.getfile(inspect.currentframe())
    with open(current_file, 'rb') as file:
        current_file_contents = file.read()

    app = Sanic('test_static')
    blueprint = Blueprint('test_static')

    blueprint.static('/testing.file', current_file)

    app.blueprint(blueprint)

    request, response = app.test_client.get('/testing.file')
    assert response.status == 200
    assert response.body == current_file_contents
Example #4
0
def test_static_content_range_back(app, file_name, static_file_directory):
    app.static(
        '/testing.file', get_file_path(static_file_directory, file_name),
        use_content_range=True)

    bp = Blueprint('test_bp_static', url_prefix='/bp')
    bp.static('/testing.file', get_file_path(static_file_directory, file_name),
              use_content_range=True)
    app.blueprint(bp)

    headers = {
        'Range': 'bytes=-12'
    }
    uri = app.url_for('static')
    assert uri == '/testing.file'
    assert uri == app.url_for('static', name='static')
    assert uri == app.url_for('static', name='static', filename='any')

    request, response = app.test_client.get(uri, headers=headers)
    assert response.status == 200
    assert 'Content-Length' in response.headers
    assert 'Content-Range' in response.headers
    static_content = bytes(get_file_content(
        static_file_directory, file_name))[-12:]
    assert int(response.headers[
               'Content-Length']) == len(static_content)
    assert response.body == static_content

    # blueprint
    uri = app.url_for('static', name='test_bp_static.static')
    assert uri == '/bp/testing.file'
    assert uri == app.url_for('static', name='test_bp_static.static',
                              filename='any')
    assert uri == app.url_for('test_bp_static.static')
    assert uri == app.url_for('test_bp_static.static', name='any')
    assert uri == app.url_for('test_bp_static.static', filename='any')
    assert uri == app.url_for('test_bp_static.static', name='any',
                              filename='any')

    request, response = app.test_client.get(uri, headers=headers)
    assert response.status == 200
    assert 'Content-Length' in response.headers
    assert 'Content-Range' in response.headers
    static_content = bytes(get_file_content(
        static_file_directory, file_name))[-12:]
    assert int(response.headers[
               'Content-Length']) == len(static_content)
    assert response.body == static_content
Example #5
0
def test_static_content_range_error(app, file_name, static_file_directory):
    app.static(
        "/testing.file",
        get_file_path(static_file_directory, file_name),
        use_content_range=True,
    )

    bp = Blueprint("test_bp_static", url_prefix="/bp")
    bp.static(
        "/testing.file",
        get_file_path(static_file_directory, file_name),
        use_content_range=True,
    )
    app.blueprint(bp)

    headers = {"Range": "bytes=1-0"}
    uri = app.url_for("static")
    assert uri == "/testing.file"
    assert uri == app.url_for("static", name="static")
    assert uri == app.url_for("static", name="static", filename="any")

    request, response = app.test_client.get(uri, headers=headers)
    assert response.status == 416
    assert "Content-Length" in response.headers
    assert "Content-Range" in response.headers
    assert response.headers["Content-Range"] == "bytes */%s" % (len(
        get_file_content(static_file_directory, file_name)), )

    # blueprint
    uri = app.url_for("static", name="test_bp_static.static")
    assert uri == "/bp/testing.file"
    assert uri == app.url_for("static",
                              name="test_bp_static.static",
                              filename="any")
    assert uri == app.url_for("test_bp_static.static")
    assert uri == app.url_for("test_bp_static.static", name="any")
    assert uri == app.url_for("test_bp_static.static", filename="any")
    assert uri == app.url_for("test_bp_static.static",
                              name="any",
                              filename="any")

    request, response = app.test_client.get(uri, headers=headers)
    assert response.status == 416
    assert "Content-Length" in response.headers
    assert "Content-Range" in response.headers
    assert response.headers["Content-Range"] == "bytes */%s" % (len(
        get_file_content(static_file_directory, file_name)), )
def test_static_content_range_empty(file_name, static_file_directory):
    app = Sanic('test_static')
    app.static('/testing.file',
               get_file_path(static_file_directory, file_name),
               use_content_range=True)

    bp = Blueprint('test_bp_static', url_prefix='/bp')
    bp.static('/testing.file',
              get_file_path(static_file_directory, file_name),
              use_content_range=True)
    app.blueprint(bp)

    uri = app.url_for('static')
    assert uri == '/testing.file'
    assert uri == app.url_for('static', name='static')
    assert uri == app.url_for('static', name='static', filename='any')

    request, response = app.test_client.get(uri)
    assert response.status == 200
    assert 'Content-Length' in response.headers
    assert 'Content-Range' not in response.headers
    assert int(response.headers['Content-Length']) == len(
        get_file_content(static_file_directory, file_name))
    assert response.body == bytes(
        get_file_content(static_file_directory, file_name))

    # blueprint
    uri = app.url_for('static', name='test_bp_static.static')
    assert uri == '/bp/testing.file'
    assert uri == app.url_for('static',
                              name='test_bp_static.static',
                              filename='any')
    assert uri == app.url_for('test_bp_static.static')
    assert uri == app.url_for('test_bp_static.static', name='any')
    assert uri == app.url_for('test_bp_static.static', filename='any')
    assert uri == app.url_for('test_bp_static.static',
                              name='any',
                              filename='any')

    request, response = app.test_client.get(uri)
    assert response.status == 200
    assert 'Content-Length' in response.headers
    assert 'Content-Range' not in response.headers
    assert int(response.headers['Content-Length']) == len(
        get_file_content(static_file_directory, file_name))
    assert response.body == bytes(
        get_file_content(static_file_directory, file_name))
Example #7
0
def test_bp_static_content_type(app, file_name):
    # This is done here, since no other test loads a file here
    current_file = inspect.getfile(inspect.currentframe())
    current_directory = os.path.dirname(os.path.abspath(current_file))
    static_directory = os.path.join(current_directory, 'static')

    blueprint = Blueprint('test_static')
    blueprint.static('/testing.file',
                     get_file_path(static_directory, file_name),
                     content_type='text/html; charset=utf-8')

    app.blueprint(blueprint)

    request, response = app.test_client.get('/testing.file')
    assert response.status == 200
    assert response.body == get_file_content(static_directory, file_name)
    assert response.headers['Content-Type'] == 'text/html; charset=utf-8'
def test_static_content_range_error(file_name, static_file_directory):
    app = Sanic('test_static')
    app.static('/testing.file',
               get_file_path(static_file_directory, file_name),
               use_content_range=True)

    bp = Blueprint('test_bp_static', url_prefix='/bp')
    bp.static('/testing.file',
              get_file_path(static_file_directory, file_name),
              use_content_range=True)
    app.blueprint(bp)

    headers = {'Range': 'bytes=1-0'}
    uri = app.url_for('static')
    assert uri == '/testing.file'
    assert uri == app.url_for('static', name='static')
    assert uri == app.url_for('static', name='static', filename='any')

    request, response = app.test_client.get(uri, headers=headers)
    assert response.status == 416
    assert 'Content-Length' in response.headers
    assert 'Content-Range' in response.headers
    assert response.headers['Content-Range'] == "bytes */%s" % (len(
        get_file_content(static_file_directory, file_name)), )

    # blueprint
    uri = app.url_for('static', name='test_bp_static.static')
    assert uri == '/bp/testing.file'
    assert uri == app.url_for('static',
                              name='test_bp_static.static',
                              filename='any')
    assert uri == app.url_for('test_bp_static.static')
    assert uri == app.url_for('test_bp_static.static', name='any')
    assert uri == app.url_for('test_bp_static.static', filename='any')
    assert uri == app.url_for('test_bp_static.static',
                              name='any',
                              filename='any')

    request, response = app.test_client.get(uri, headers=headers)
    assert response.status == 416
    assert 'Content-Length' in response.headers
    assert 'Content-Range' in response.headers
    assert response.headers['Content-Range'] == "bytes */%s" % (len(
        get_file_content(static_file_directory, file_name)), )
Example #9
0
def test_bp_static_content_type(app, file_name):
    # This is done here, since no other test loads a file here
    current_file = inspect.getfile(inspect.currentframe())
    current_directory = os.path.dirname(os.path.abspath(current_file))
    static_directory = os.path.join(current_directory, "static")

    blueprint = Blueprint("test_static")
    blueprint.static(
        "/testing.file",
        get_file_path(static_directory, file_name),
        content_type="text/html; charset=utf-8",
    )

    app.blueprint(blueprint)

    request, response = app.test_client.get("/testing.file")
    assert response.status == 200
    assert response.body == get_file_content(static_directory, file_name)
    assert response.headers["Content-Type"] == "text/html; charset=utf-8"
Example #10
0
def test_static_head_request(file_name, static_file_directory):
    app = Sanic("base")
    app.static(
        "/testing.file",
        get_file_path(static_file_directory, file_name),
        use_content_range=True,
    )

    bp = Blueprint("test_bp_static", url_prefix="/bp")
    bp.static(
        "/testing.file",
        get_file_path(static_file_directory, file_name),
        use_content_range=True,
    )
    app.blueprint(bp)

    uri = app.url_for("static")
    assert uri == "/testing.file"
    assert uri == app.url_for("static", name="static")
    assert uri == app.url_for("static", name="static", filename="any")

    request, response = app.test_client.head(uri)
    assert response.status == 200
    assert "Accept-Ranges" in response.headers
    assert "Content-Length" in response.headers
    assert int(response.headers["Content-Length"]) == len(
        get_file_content(static_file_directory, file_name)
    )

    # blueprint
    uri = app.url_for("static", name="test_bp_static.static")
    assert uri == "/bp/testing.file"
    assert uri == app.url_for(
        "static", name="test_bp_static.static", filename="any"
    )

    request, response = app.test_client.head(uri)
    assert response.status == 200
    assert "Accept-Ranges" in response.headers
    assert "Content-Length" in response.headers
    assert int(response.headers["Content-Length"]) == len(
        get_file_content(static_file_directory, file_name)
    )
Example #11
0
def test_static_blueprint_name(app: Sanic, static_file_directory, file_name):
    current_file = inspect.getfile(inspect.currentframe())
    with open(current_file, 'rb') as file:
        current_file_contents = file.read()

    bp = Blueprint(name="static", url_prefix="/static", strict_slashes=False)

    bp.static("/test.file/",
              get_file_path(static_file_directory, file_name),
              name="static.testing",
              strict_slashes=True)

    app.blueprint(bp)

    uri = app.url_for('static', name='static.testing')
    assert uri == "/static/test.file"

    _, response = app.test_client.get("/static/test.file")
    assert response.status == 404

    _, response = app.test_client.get("/static/test.file/")
    assert response.status == 200
Example #12
0
def test_static_blueprint_name(app: Sanic, static_file_directory, file_name):
    current_file = inspect.getfile(inspect.currentframe())
    with open(current_file, "rb") as file:
        current_file_contents = file.read()

    bp = Blueprint(name="static", url_prefix="/static", strict_slashes=False)

    bp.static(
        "/test.file/",
        get_file_path(static_file_directory, file_name),
        name="static.testing",
        strict_slashes=True,
    )

    app.blueprint(bp)

    uri = app.url_for("static", name="static.testing")
    assert uri == "/static/test.file"

    _, response = app.test_client.get("/static/test.file")
    assert response.status == 404

    _, response = app.test_client.get("/static/test.file/")
    assert response.status == 200
Example #13
0
def blueprint_factory():
    oas3_blueprint = Blueprint("openapi", url_prefix="/swagger")

    dir_path = dirname(dirname(realpath(__file__)))
    dir_path = abspath(dir_path + "/ui")

    oas3_blueprint.static("/", dir_path + "/index.html", strict_slashes=True)
    oas3_blueprint.static("/", dir_path)

    # Redirect "/swagger" to "/swagger/"
    @oas3_blueprint.route("", strict_slashes=True)
    def index(request):
        return redirect("{}/".format(oas3_blueprint.url_prefix))

    @oas3_blueprint.route("/swagger.json")
    @doc_route(exclude=True)
    def spec(request):
        return json(specification.build().serialize())

    @oas3_blueprint.route("/swagger-config")
    def config(request):
        return json(getattr(request.app.config, "SWAGGER_UI_CONFIGURATION",
                            {}))

    @oas3_blueprint.listener("before_server_start")
    def build_spec(app, loop):
        # --------------------------------------------------------------- #
        # Globals
        # --------------------------------------------------------------- #
        specification.describe(
            getattr(app.config, "API_TITLE", "API"),
            getattr(app.config, "API_VERSION", "1.0.0"),
            getattr(app.config, "API_DESCRIPTION", None),
            getattr(app.config, "API_TERMS_OF_SERVICE", None),
        )

        specification.license(
            getattr(app.config, "API_LICENSE_NAME", None),
            getattr(app.config, "API_LICENSE_URL", None),
        )

        specification.contact(
            getattr(app.config, "API_CONTACT_NAME", None),
            getattr(app.config, "API_CONTACT_URL", None),
            getattr(app.config, "API_CONTACT_EMAIL", None),
        )

        for scheme in getattr(app.config, "API_SCHEMES", ["http"]):
            host = getattr(app.config, "API_HOST", None)
            basePath = getattr(app.config, "API_BASEPATH", "")
            if host is None or basePath is None:
                continue

            specification.url(f"{scheme}://{host}/{basePath}")

        # --------------------------------------------------------------- #
        # Blueprints
        # --------------------------------------------------------------- #
        for _blueprint in app.blueprints.values():
            if not hasattr(_blueprint, "routes"):
                continue

            for _route in _blueprint.routes:
                if hasattr(_route.handler, "view_class"):
                    # class based view
                    for http_method in _route.methods:
                        _handler = getattr(_route.handler.view_class,
                                           http_method.lower(), None)
                        if _handler:
                            operation = operations[_route.handler]
                            if not operation.tags:
                                operation.tag(_blueprint.name)
                else:
                    operation = operations[_route.handler]
                    # operation.blueprint = _blueprint
                    # is this necc ?
                    if not operation.tags:
                        operation.tag(_blueprint.name)

        uri_filter = get_uri_filter(app)

        # --------------------------------------------------------------- #
        # Operations
        # --------------------------------------------------------------- #
        for _uri, _route in app.router.routes_all.items():

            # Ignore routes under swagger blueprint
            if _route.uri.startswith(oas3_blueprint.url_prefix):
                continue

            # Apply the URI filter
            if uri_filter(_uri):
                continue

            # route.name will be None when using class based view
            if _route.name and "static" in _route.name:
                continue

            # --------------------------------------------------------------- #
            # Methods
            # --------------------------------------------------------------- #

            handler_type = type(_route.handler)

            if handler_type is CompositionView:
                view = _route.handler
                method_handlers = view.handlers.items()
            else:
                method_handlers = zip(_route.methods, repeat(_route.handler))

            uri = _uri if _uri == "/" else _uri.rstrip("/")

            for segment in _route.parameters:
                uri = re.sub("<" + segment.name + ".*?>",
                             "{" + segment.name + "}", uri)

            for method, _handler in method_handlers:

                if method == "OPTIONS":
                    continue

                operation = operations[_handler]

                if not hasattr(operation, "operationId"):
                    operation.operationId = "%s_%s" % (method.lower(),
                                                       _route.name)

                for _parameter in _route.parameters:
                    operation.parameter(_parameter.name, _parameter.cast,
                                        "path")

                specification.operation(uri, method, operation)

    return oas3_blueprint
Example #14
0
import os

from sanic.blueprints import Blueprint

dir_path = os.path.dirname(os.path.realpath(__file__))
dir_path = os.path.abspath(dir_path + "/ui")

blueprint = Blueprint("swagger", url_prefix="swagger")

blueprint.static("/", dir_path + "/index.html")
blueprint.static("/", dir_path)
Example #15
0
def blueprint_factory():
    swagger_blueprint = Blueprint("swagger", url_prefix="/swagger")

    dir_path = dirname(dirname(realpath(__file__)))
    dir_path = abspath(dir_path + "/ui")

    swagger_blueprint.static("/",
                             dir_path + "/index.html",
                             strict_slashes=True)
    swagger_blueprint.static("/", dir_path)

    # Redirect "/swagger" to "/swagger/"
    @swagger_blueprint.route("", strict_slashes=True)
    def index(request):
        return redirect("{}/".format(swagger_blueprint.url_prefix))

    @swagger_blueprint.route("/swagger.json")
    def spec(request):

        if SANIC_VERSION >= SANIC_21_3_0:
            return json(swagger_blueprint.ctx._spec.as_dict)
        else:
            return json(swagger_blueprint._spec.as_dict)

    @swagger_blueprint.route("/swagger-config")
    def config(request):
        return json(getattr(request.app.config, "SWAGGER_UI_CONFIGURATION",
                            {}))

    @swagger_blueprint.listener("after_server_start")
    def build_spec(app, loop):
        # --------------------------------------------------------------- #
        # Blueprint Tags
        # --------------------------------------------------------------- #

        for blueprint_name, handler in get_blueprinted_routes(app):
            route_spec = route_specs[handler]
            route_spec.blueprint = blueprint_name
            if not route_spec.tags:
                route_spec.tags.append(blueprint_name)

        paths = {}

        for (uri, route_name, route_parameters,
             method_handlers) in get_all_routes(app,
                                                swagger_blueprint.url_prefix):

            # --------------------------------------------------------------- #
            # Methods
            # --------------------------------------------------------------- #

            methods = {}
            for _method, _handler in method_handlers:

                route_spec = route_specs.get(_handler) or RouteSpec()

                if route_spec.exclude:
                    continue

                api_consumes_content_types = getattr(
                    app.config, "API_CONSUMES_CONTENT_TYPES",
                    ["application/json"])
                consumes_content_types = route_spec.consumes_content_type or api_consumes_content_types

                api_produces_content_types = getattr(
                    app.config, "API_PRODUCES_CONTENT_TYPES",
                    ["application/json"])
                produces_content_types = route_spec.produces_content_type or api_produces_content_types

                # Parameters - Path & Query String
                route_parameters = []
                for parameter in route_parameters:
                    route_parameters.append({
                        **serialize_schema(parameter.cast),
                        "required":
                        True,
                        "in":
                        "path",
                        "name":
                        parameter.name,
                    })

                for consumer in route_spec.consumes:
                    spec = serialize_schema(consumer.field)
                    if "properties" in spec:
                        for name, prop_spec in spec["properties"].items():
                            route_param = {
                                **prop_spec,
                                "required": consumer.required,
                                "in": consumer.location,
                                "name": name,
                            }
                    else:
                        route_param = {
                            **spec,
                            "required":
                            consumer.required,
                            "in":
                            consumer.location,
                            "name":
                            consumer.field.name
                            if not isinstance(consumer.field, type)
                            and hasattr(consumer.field, "name") else "body",
                        }

                    if "$ref" in route_param:
                        route_param["schema"] = {"$ref": route_param["$ref"]}
                        del route_param["$ref"]

                    if route_param["in"] == "path":
                        route_param["required"] = True
                        for i, parameter in enumerate(route_parameters):
                            if parameter["name"] == route_param["name"]:
                                route_parameters.pop(i)
                                break

                    route_parameters.append(route_param)

                responses = {}

                for (status_code, routefield) in route_spec.response:
                    responses["{}".format(status_code)] = {
                        "schema": serialize_schema(routefield.field),
                        "description": routefield.description,
                    }

                if route_spec.produces:
                    responses["200"] = {
                        "schema": serialize_schema(route_spec.produces.field),
                        "description": route_spec.produces.description,
                    }
                elif not responses:
                    responses["200"] = {"description": "OK"}

                y = YamlStyleParametersParser(inspect.getdoc(_handler))
                autodoc_endpoint = y.to_openAPI_2()

                # if the user has manualy added a description or summary via
                # the decorator, then use theirs

                if route_spec.summary:
                    autodoc_endpoint["summary"] = route_spec.summary

                if route_spec.description:
                    autodoc_endpoint["description"] = route_spec.description

                endpoint = remove_nulls({
                    "operationId": route_spec.operation or route_name,
                    "summary": route_spec.summary,
                    "description": route_spec.description,
                    "consumes": consumes_content_types,
                    "produces": produces_content_types,
                    "tags": route_spec.tags or None,
                    "parameters": route_parameters,
                    "responses": responses,
                })

                # otherwise, update with anything parsed from the
                # docstrings yaml
                endpoint.update(autodoc_endpoint)

                methods[_method.lower()] = endpoint

            if methods:
                paths[uri] = methods

        # --------------------------------------------------------------- #
        # Definitions
        # --------------------------------------------------------------- #

        _spec = Swagger2Spec(app=app)

        _spec.add_definitions(
            definitions={
                obj.object_name: definition
                for obj, definition in definitions.values()
            })

        # --------------------------------------------------------------- #
        # Tags
        # --------------------------------------------------------------- #

        tags = set()
        for route_spec in route_specs.values():
            if route_spec.blueprint != "swagger":
                tags.update(route_spec.tags)

        _spec.add_tags(tags=[{"name": name} for name in tags])

        _spec.add_paths(paths)

        if SANIC_VERSION >= SANIC_21_3_0:
            swagger_blueprint.ctx._spec = _spec
        else:
            swagger_blueprint._spec = _spec

    return swagger_blueprint
Example #16
0
def test_static_file(app, static_file_directory, file_name):
    app.static("/testing.file", get_file_path(static_file_directory,
                                              file_name))
    app.static(
        "/testing2.file",
        get_file_path(static_file_directory, file_name),
        name="testing_file",
    )

    uri = app.url_for("static")
    uri2 = app.url_for("static", filename="any")
    uri3 = app.url_for("static", name="static", filename="any")

    assert uri == "/testing.file"
    assert uri == uri2
    assert uri2 == uri3

    request, response = app.test_client.get(uri)
    assert response.status == 200
    assert response.body == get_file_content(static_file_directory, file_name)

    bp = Blueprint("test_bp_static", url_prefix="/bp")

    bp.static("/testing.file", get_file_path(static_file_directory, file_name))
    bp.static(
        "/testing2.file",
        get_file_path(static_file_directory, file_name),
        name="testing_file",
    )

    app.blueprint(bp)

    uri = app.url_for("static", name="test_bp_static.static")
    uri2 = app.url_for("static", name="test_bp_static.static", filename="any")
    uri3 = app.url_for("test_bp_static.static")
    uri4 = app.url_for("test_bp_static.static", name="any")
    uri5 = app.url_for("test_bp_static.static", filename="any")
    uri6 = app.url_for("test_bp_static.static", name="any", filename="any")

    assert uri == "/bp/testing.file"
    assert uri == uri2
    assert uri2 == uri3
    assert uri3 == uri4
    assert uri4 == uri5
    assert uri5 == uri6

    request, response = app.test_client.get(uri)
    assert response.status == 200
    assert response.body == get_file_content(static_file_directory, file_name)

    # test for other parameters
    uri = app.url_for("static", _external=True, _server="http://localhost")
    assert uri == "http://localhost/testing.file"

    uri = app.url_for(
        "static",
        name="test_bp_static.static",
        _external=True,
        _server="http://localhost",
    )
    assert uri == "http://localhost/bp/testing.file"

    # test for defined name
    uri = app.url_for("static", name="testing_file")
    assert uri == "/testing2.file"

    request, response = app.test_client.get(uri)
    assert response.status == 200
    assert response.body == get_file_content(static_file_directory, file_name)

    uri = app.url_for("static", name="test_bp_static.testing_file")
    assert uri == "/bp/testing2.file"
    assert uri == app.url_for("static",
                              name="test_bp_static.testing_file",
                              filename="any")

    request, response = app.test_client.get(uri)
    assert response.status == 200
    assert response.body == get_file_content(static_file_directory, file_name)
Example #17
0
from itertools import repeat
import os

from sanic.blueprints import Blueprint
from sanic.response import json
from sanic.views import CompositionView

from .doc import route_specs, RouteSpec, serialize_schema, definitions


blueprint = Blueprint('swagger', url_prefix='swagger')

dir_path = os.path.dirname(os.path.realpath(__file__))
dir_path = os.path.abspath(dir_path + '/ui')

blueprint.static('/', dir_path + '/index.html')
blueprint.static('/', dir_path)


_spec = {}


# Removes all null values from a dictionary
def remove_nulls(dictionary, deep=True):
    return {
        k: remove_nulls(v, deep) if deep and type(v) is dict else v
        for k, v in dictionary.items()
        if v is not None
    }

Example #18
0
from .doc import route_specs, RouteSpec, serialize_schema, definitions

blueprint = Blueprint('swagger', url_prefix='swagger')

dir_path = os.path.dirname(os.path.realpath(__file__))
dir_path = os.path.abspath(dir_path + '/ui')


# Redirect "/swagger" to "/swagger/"
@blueprint.route('', strict_slashes=True)
def index(request):
    return redirect("{}/".format(blueprint.url_prefix))


blueprint.static('/', dir_path + '/index.html', strict_slashes=True)
blueprint.static('/', dir_path)

_spec = {}


# Removes all null values from a dictionary
def remove_nulls(dictionary, deep=True):
    return {
        k: remove_nulls(v, deep) if deep and type(v) is dict else v
        for k, v in dictionary.items() if v is not None
    }


@blueprint.listener('before_server_start')
def build_spec(app, loop):
Example #19
0
def test_static_file(app, static_file_directory, file_name):
    app.static(
        '/testing.file', get_file_path(static_file_directory, file_name))
    app.static(
        '/testing2.file', get_file_path(static_file_directory, file_name),
        name='testing_file')

    uri = app.url_for('static')
    uri2 = app.url_for('static', filename='any')
    uri3 = app.url_for('static', name='static', filename='any')

    assert uri == '/testing.file'
    assert uri == uri2
    assert uri2 == uri3

    request, response = app.test_client.get(uri)
    assert response.status == 200
    assert response.body == get_file_content(static_file_directory, file_name)

    bp = Blueprint('test_bp_static', url_prefix='/bp')

    bp.static('/testing.file', get_file_path(static_file_directory, file_name))
    bp.static('/testing2.file',
              get_file_path(static_file_directory, file_name),
              name='testing_file')

    app.blueprint(bp)

    uri = app.url_for('static', name='test_bp_static.static')
    uri2 = app.url_for('static', name='test_bp_static.static', filename='any')
    uri3 = app.url_for('test_bp_static.static')
    uri4 = app.url_for('test_bp_static.static', name='any')
    uri5 = app.url_for('test_bp_static.static', filename='any')
    uri6 = app.url_for('test_bp_static.static', name='any', filename='any')

    assert uri == '/bp/testing.file'
    assert uri == uri2
    assert uri2 == uri3
    assert uri3 == uri4
    assert uri4 == uri5
    assert uri5 == uri6

    request, response = app.test_client.get(uri)
    assert response.status == 200
    assert response.body == get_file_content(static_file_directory, file_name)

    # test for other parameters
    uri = app.url_for('static', _external=True, _server='http://localhost')
    assert uri == 'http://localhost/testing.file'

    uri = app.url_for('static', name='test_bp_static.static',
                      _external=True, _server='http://localhost')
    assert uri == 'http://localhost/bp/testing.file'

    # test for defined name
    uri = app.url_for('static', name='testing_file')
    assert uri == '/testing2.file'

    request, response = app.test_client.get(uri)
    assert response.status == 200
    assert response.body == get_file_content(static_file_directory, file_name)

    uri = app.url_for('static', name='test_bp_static.testing_file')
    assert uri == '/bp/testing2.file'
    assert uri == app.url_for('static', name='test_bp_static.testing_file',
                              filename='any')

    request, response = app.test_client.get(uri)
    assert response.status == 200
    assert response.body == get_file_content(static_file_directory, file_name)
Example #20
0
# Serves the file /home/ubuntu/test.png when the URL /the_best.png is requested
app.static('/the_best.png', '/home/ubuntu/test.png', name='best_png')

# you can use url_for to build the static file url
# you can ignore name and filename parameters if you don`t define it
app.url_for('static', name='best_png') == '/the_best.png'
app.url_for('sttaic', name='best_png', filename='any') == '/the_best.png'

# you need define the name for other static files
app.static('/another/png', '/home/ubuntu/another.png', name='another')
app.url_for('static', name='another') == '/another.png'
app.url_for('static', name='another', filename='any') == '/another.png'

# also, you can use static for blueprint
bp = Blueprint('bp', url_prefix='/bp')
bp.static('/static', './static')

# servers the file directly
bp.static('/the_best.png', '/home/ubuntu/test.png', name='best_png')
app.blueprints(bp)

app.url_for('static', name='bp.static',
            filename='file.txt') == '/bp/static/file.txt'
app.url_for('static', name='bp.best_png') == '/bp/test_Best.png'

# Virtual Host
app.static('/example_static', './example_static', host='www.example.com')

# Streaming Large File
app.static('/large_video.mp4',
           '/home/ubuntu/large_video.mp4',
Example #21
0
def test_static_file(static_file_directory, file_name):
    app = Sanic("qq")
    app.static(
        "/testing.file", get_file_path(static_file_directory, file_name)
    )
    app.static(
        "/testing2.file",
        get_file_path(static_file_directory, file_name),
        name="testing_file",
    )

    app.router.finalize()

    uri = app.url_for("static")
    uri2 = app.url_for("static", filename="any")
    uri3 = app.url_for("static", name="static", filename="any")

    assert uri == "/testing.file"
    assert uri == uri2
    assert uri2 == uri3

    app.router.reset()

    request, response = app.test_client.get(uri)
    assert response.status == 200
    assert response.body == get_file_content(static_file_directory, file_name)

    app.router.reset()

    bp = Blueprint("test_bp_static", url_prefix="/bp")

    bp.static("/testing.file", get_file_path(static_file_directory, file_name))
    bp.static(
        "/testing2.file",
        get_file_path(static_file_directory, file_name),
        name="testing_file",
    )

    app.blueprint(bp)

    uris = [
        app.url_for("static", name="test_bp_static.static"),
        app.url_for("static", name="test_bp_static.static", filename="any"),
        app.url_for("test_bp_static.static"),
        app.url_for("test_bp_static.static", filename="any"),
    ]

    assert all(uri == "/bp/testing.file" for uri in uris)

    request, response = app.test_client.get(uri)
    assert response.status == 200
    assert response.body == get_file_content(static_file_directory, file_name)

    # test for other parameters
    uri = app.url_for("static", _external=True, _server="http://localhost")
    assert uri == "http://localhost/testing.file"

    uri = app.url_for(
        "static",
        name="test_bp_static.static",
        _external=True,
        _server="http://localhost",
    )
    assert uri == "http://localhost/bp/testing.file"

    # test for defined name
    uri = app.url_for("static", name="testing_file")
    assert uri == "/testing2.file"

    request, response = app.test_client.get(uri)
    assert response.status == 200
    assert response.body == get_file_content(static_file_directory, file_name)

    uri = app.url_for("static", name="test_bp_static.testing_file")
    assert uri == "/bp/testing2.file"
    assert uri == app.url_for(
        "static", name="test_bp_static.testing_file", filename="any"
    )

    request, response = app.test_client.get(uri)
    assert response.status == 200
    assert response.body == get_file_content(static_file_directory, file_name)
Example #22
0
def blueprint_factory():
    oas3_blueprint = Blueprint("openapi", url_prefix="/api")

    dir_path = dirname(dirname(realpath(__file__)))
    dir_path = abspath(dir_path + "/ui")

    oas3_blueprint.static("/", dir_path + "/index.html", strict_slashes=True)
    oas3_blueprint.static("/", dir_path)

    # Redirect "/swagger" to "/swagger/"
    @oas3_blueprint.route("", strict_slashes=True)
    def index(request):
        return redirect("{}/".format(oas3_blueprint.url_prefix))

    @oas3_blueprint.route("/swagger.json")
    def spec(request):
        return json(specification.build().serialize())

    @oas3_blueprint.route("/swagger-config")
    def config(request):
        return json(
            getattr(
                request.app.config,
                "SWAGGER_UI_CONFIGURATION",
                DEFAULT_SWAGGER_UI_CONFIG,
            ))

    @oas3_blueprint.listener("before_server_start")
    def build_spec(app, loop):
        # --------------------------------------------------------------- #
        # Blueprint Tags
        # --------------------------------------------------------------- #

        for blueprint_name, handler in get_blueprinted_routes(app):
            operation = operations[handler]
            if not operation.tags:
                operation.tag(blueprint_name)

        # --------------------------------------------------------------- #
        # Operations
        # --------------------------------------------------------------- #
        for uri, route_name, route_parameters, method_handlers in get_all_routes(
                app, oas3_blueprint.url_prefix):

            # --------------------------------------------------------------- #
            # Methods
            # --------------------------------------------------------------- #

            uri = uri if uri == "/" else uri.rstrip("/")

            for method, _handler in method_handlers:

                if method == "OPTIONS":
                    continue

                operation = operations[_handler]

                # operation ID must be unique, and it isnt currently used for
                # anything in UI, so dont add something meaningless
                # if not hasattr(operation, "operationId"):
                #     operation.operationId = "%s_%s" % (method.lower(), route.name)

                for _parameter in route_parameters:
                    operation.parameter(_parameter.name, _parameter.cast,
                                        "path")

                specification.operation(uri, method, operation)

        add_static_info_to_spec_from_config(app, specification)

    return oas3_blueprint
Example #23
0
from .doc import route as doc_route
from .doc import route_specs, serialize_schema

swagger_blueprint = Blueprint("swagger", url_prefix="/swagger")

dir_path = os.path.dirname(os.path.realpath(__file__))
dir_path = os.path.abspath(dir_path + "/ui")


# Redirect "/swagger" to "/swagger/"
@swagger_blueprint.route("", strict_slashes=True)
def index(request):
    return redirect("{}/".format(swagger_blueprint.url_prefix))


swagger_blueprint.static("/", dir_path + "/index.html", strict_slashes=True)
swagger_blueprint.static("/", dir_path)

_spec = {}


# Removes all null values from a dictionary
def remove_nulls(dictionary, deep=True):
    return {
        k: remove_nulls(v, deep) if deep and type(v) is dict else v
        for k, v in dictionary.items() if v is not None
    }


@swagger_blueprint.listener("before_server_start")
def build_spec(app, loop):
Example #24
0
async def index(request):
    event_loop = get_event_loop()
    file = await event_loop.run_in_executor(None, open, './README.md')
    markdowner = Markdown()
    data = await event_loop.run_in_executor(None, file.read)
    return response.html(markdowner.convert(data))


@app.get('/sample')
async def sample(request):
    data = await http_request_from_third_party(request)
    return response.text(data)


@app.get('/samples')
async def samples(request):
    data = await bulk_http_requests_from_third_party(request, [1, 2])
    return response.text(data)


@app.get('/docs')
def handle_request(request):
    return response.redirect('/docs/index.html')


docs_blueprint = Blueprint('docs', url_prefix='/docs')
docs_blueprint.static('/', './docs')

app.blueprint(docs_blueprint)
app.blueprint(health_blueprint)