def optimade_api_version():
    """Print OPTIMADE API version supported in currently installed optimade package as input for shell array"""
    try:
        from optimade import __api_version__
    except ImportError:
        exit("optimade MUST be installed to run 'api-version'")

    versions = [
        __api_version__.split('-')[0].split('+')[0].split('.')[0],
        '.'.join(__api_version__.split('-')[0].split('+')[0].split('.')[:2]),
        '.'.join(__api_version__.split('-')[0].split('+')[0].split('.')[:3]),
    ]
    print(' '.join(versions))
Ejemplo n.º 2
0
async def landing(request: Request):
    """Show a human-readable landing page when the base URL is accessed."""

    meta = meta_values(request.url, 1, 1, more_data_available=False)
    major_version = __api_version__.split(".")[0]
    versioned_url = f"{get_base_url(request.url)}/v{major_version}/"

    context = {
        "request": request,
        "request_url": request.url,
        "api_version": __api_version__,
        "implementation": meta.implementation,
        "versioned_url": versioned_url,
        "provider": meta.provider,
        "index_base_url": CONFIG.index_base_url,
        "endpoints": list(ENTRY_COLLECTIONS.keys()) + ["info"],
    }

    return TEMPLATES.TemplateResponse("landing_page.html", context)
Ejemplo n.º 3
0
                          exc_handlers.http_exception_handler)
app.add_exception_handler(RequestValidationError,
                          exc_handlers.request_validation_exception_handler)
app.add_exception_handler(ValidationError,
                          exc_handlers.validation_exception_handler)
app.add_exception_handler(VisitError,
                          exc_handlers.grammar_not_implemented_handler)
app.add_exception_handler(Exception, exc_handlers.general_exception_handler)

# Create the following prefixes:
#   /optimade
#   /optimade/vMajor (but only if Major >= 1)
#   /optimade/vMajor.Minor
#   /optimade/vMajor.Minor.Patch
valid_prefixes = ["/optimade"]
version = [int(_) for _ in __api_version__.split(".")]
while version:
    if version[0] or len(version) >= 2:
        valid_prefixes.append("/optimade/v{}".format(".".join(
            [str(_) for _ in version])))
    version.pop(-1)

for prefix in valid_prefixes:
    app.include_router(info.router, prefix=prefix)
    app.include_router(links.router, prefix=prefix)
    app.include_router(references.router, prefix=prefix)
    app.include_router(structures.router, prefix=prefix)


def update_schema(app):
    """Update OpenAPI schema in file 'local_openapi.json'"""
Ejemplo n.º 4
0
def render_landing_page(url: str) -> HTMLResponse:
    """Render and cache the landing page.

    This function uses the template file `./static/landing_page.html`, adapted
    from the original Jinja template. Instead of Jinja, some basic string
    replacement is used to fill out the fields from the server configuration.

    !!! warning "Careful"
        The removal of Jinja means that the fields are no longer validated as
        web safe before inclusion in the template.

    """
    meta = meta_values(url, 1, 1, more_data_available=False)
    major_version = __api_version__.split(".")[0]
    versioned_url = f"{get_base_url(url)}/v{major_version}/"

    template_dir = Path(__file__).parent.joinpath("static").resolve()

    html = (template_dir / "landing_page.html").read_text()

    # Build a dictionary that maps the old Jinja keys to the new simplified replacements
    replacements = {
        "api_version": __api_version__,
    }

    if meta.provider:
        replacements.update({
            "provider.name":
            meta.provider.name,
            "provider.prefix":
            meta.provider.prefix,
            "provider.description":
            meta.provider.description,
            "provider.homepage":
            str(meta.provider.homepage) or "",
        })

    if meta.implementation:
        replacements.update({
            "implementation.name":
            meta.implementation.name or "",
            "implementation.version":
            meta.implementation.version or "",
            "implementation.source_url":
            str(meta.implementation.source_url or ""),
        })

    for replacement in replacements:
        html = html.replace(f"{{{{ {replacement} }}}}",
                            replacements[replacement])

    # Build the list of endpoints. The template already opens and closes the `<ul>` tag.
    endpoints_list = [
        f'<li><a href="{versioned_url}{endp}">{versioned_url}{endp}</a></li>'
        for endp in list(ENTRY_COLLECTIONS.keys()) + ["info"]
    ]
    html = html.replace("{% ENDPOINTS %}", "\n".join(endpoints_list))

    # If the index base URL has been configured, also list it
    index_base_url_html = ""
    if CONFIG.index_base_url:
        index_base_url_html = f"""<h3>Index base URL:</h3>
<p><a href={CONFIG.index_base_url}>{CONFIG.index_base_url}</a></p>
"""
    html = html.replace("{% INDEX_BASE_URL %}", index_base_url_html)

    return HTMLResponse(html)