Пример #1
0
    async def openapi(self, request):
        # noinspection PyTypeChecker
        self.schema_generator = APISpecSchemaGenerator(
            APISpec(
                title="Example API",
                version="1.0",
                openapi_version="3.0.0",
                info={"description": "ASGI Agent"},
                plugins=[MarshmallowPlugin()],
            ))  # type: ignore

        # add opneapi models based on Marshammallow
        for name, schema in self.schema_models.items():
            self.schema_generator.spec.components.schema(name, schema=schema)

        # create spec file for display via apistar
        schema = yaml.dump(
            self.schema_generator.get_schema(routes=self.routes),
            default_flow_style=False,
        )

        # TODO: fix (Deactivated due to: ValueError: call stack is not deep enough)
        # async with AIOFile('static/schema.yaml', 'w+') as afp:
        #     await afp.write(schema)  # BUG: ValueError: call stack is not deep enough

        return HTMLResponse(
            apistar.docs(
                schema,
                schema_url="/static/schema.yaml",
                theme="swaggerui",
                static_url="/static/",
            ))
Пример #2
0
def test_docs():
    schema = {
        "openapi": "3.0.0",
        "info": {
            "title": "",
            "version": ""
        },
        "paths": {}
    }
    index_html = apistar.docs(schema, static_url="/static/")
    assert "<title>API Star</title>" in index_html
    assert 'href="/static/css/base.css"' in index_html
Пример #3
0
def test_docs_with_static_url_func():
    schema = {
        "openapi": "3.0.0",
        "info": {
            "title": "",
            "version": ""
        },
        "paths": {}
    }
    index_html = apistar.docs(schema, static_url=lambda x: "/" + x)
    assert "<title>API Star</title>" in index_html
    assert 'href="/css/base.css"' in index_html
Пример #4
0
def docs(path, format, encoding, output_dir, theme, serve, verbose):
    options = {
        "schema": {"path": path, "format": format, "encoding": encoding},
        "docs": {"output_dir": output_dir, "theme": theme},
    }
    config = _load_config(options, verbose=verbose)

    path = config["schema"]["path"]
    format = config["schema"]["format"]
    encoding = config["schema"]["encoding"]
    output_dir = config["docs"]["output_dir"]
    theme = config["docs"]["theme"]

    if output_dir is None:
        output_dir = "build"
    if theme is None:
        theme = "apistar"

    schema_filename = os.path.basename(path)
    schema_url = "/" + schema_filename
    with open(path, "rb") as schema_file:
        content = schema_file.read()

    try:
        index_html = apistar.docs(
            content, format=format, encoding=encoding, schema_url=schema_url, theme=theme
        )
    except (typesystem.ParseError, typesystem.ValidationError) as exc:
        if isinstance(exc, typesystem.ParseError):
            summary = {
                "json": "Invalid JSON.",
                "yaml": "Invalid YAML.",
                None: "Parse error.",
            }[encoding]
        else:
            summary = {
                "config": "Invalid APIStar config.",
                "jsonschema": "Invalid JSONSchema document.",
                "openapi": "Invalid OpenAPI schema.",
                "swagger": "Invalid Swagger schema.",
                None: "Invalid schema.",
            }[format]
        _echo_error(exc, content, summary=summary, verbose=verbose)
        sys.exit(1)

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # Write 'index.html' to the docs.
    output_path = os.path.join(output_dir, "index.html")
    if verbose:
        click.echo(output_path)
    output_file = open(output_path, "w")
    output_file.write(index_html)
    output_file.close()

    # Write schema file to the docs.
    schema_path = os.path.join(output_dir, schema_filename)
    if verbose:
        click.echo(schema_path)
    shutil.copy2(path, schema_path)

    # Write static files to the docs.
    package_dir = os.path.dirname(apistar.__file__)
    static_dir = os.path.join(package_dir, "themes", theme, "static")
    _copy_tree(static_dir, output_dir, verbose=verbose)

    # All done.
    if serve:
        os.chdir(output_dir)
        addr = ("", 8000)
        handler = http.server.SimpleHTTPRequestHandler
        socketserver.TCPServer.allow_reuse_address = True
        with socketserver.TCPServer(addr, handler) as httpd:
            msg = 'Documentation available at "http://127.0.0.1:8000/" (Ctrl+C to quit)'
            click.echo(click.style("✓ ", fg="green") + msg)
            httpd.serve_forever()
    else:
        msg = 'Documentation built at "%s".'
        click.echo(click.style("✓ ", fg="green") + (msg % output_path))
Пример #5
0
def docs(path, format, encoding, output_dir, theme, serve, verbose):
    options = {
        'schema': {
            'path': path,
            'format': format,
            'encoding': encoding,
        },
        'docs': {
            'output_dir': output_dir,
            'theme': theme,
        }
    }
    config = _load_config(options, verbose=verbose)

    path = config['schema']['path']
    format = config['schema']['format']
    encoding = config['schema']['encoding']
    output_dir = config['docs']['output_dir']
    theme = config['docs']['theme']

    if output_dir is None:
        output_dir = 'build'
    if theme is None:
        theme = 'apistar'

    schema_filename = os.path.basename(path)
    schema_url = '/' + schema_filename
    with open(path, 'rb') as schema_file:
        content = schema_file.read()

    try:
        index_html = apistar.docs(content,
                                  format=format,
                                  encoding=encoding,
                                  schema_url=schema_url)
    except (ParseError, ValidationError) as exc:
        _echo_error(exc, content, verbose=verbose)
        sys.exit(1)

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # Write 'index.html' to the docs.
    output_path = os.path.join(output_dir, 'index.html')
    if verbose:
        click.echo(output_path)
    output_file = open(output_path, 'w')
    output_file.write(index_html)
    output_file.close()

    # Write schema file to the docs.
    schema_path = os.path.join(output_dir, schema_filename)
    if verbose:
        click.echo(schema_path)
    shutil.copy2(path, schema_path)

    # Write static files to the docs.
    package_dir = os.path.dirname(apistar.__file__)
    static_dir = os.path.join(package_dir, 'themes', theme, 'static')
    _copy_tree(static_dir, output_dir, verbose=verbose)

    # All done.
    if serve:
        os.chdir(output_dir)
        addr = ("", 8000)
        handler = http.server.SimpleHTTPRequestHandler
        socketserver.TCPServer.allow_reuse_address = True
        with socketserver.TCPServer(addr, handler) as httpd:
            msg = 'Documentation available at "http://127.0.0.1:8000/" (Ctrl+C to quit)'
            click.echo(click.style('✓ ', fg='green') + msg)
            httpd.serve_forever()
    else:
        msg = 'Documentation built at "%s".'
        click.echo(click.style('✓ ', fg='green') + (msg % output_path))