Esempio n. 1
0
def static_html(name):
    if name in aliases: redirect(aliases[name])
    linkheaders = ["</style.css>; rel=preload; as=style"]
    keys = remove_identical(FormsDict.decode(request.query))

    adminmode = request.cookies.get("adminmode") == "true" and auth.check(
        request)

    clock = Clock()
    clock.start()

    LOCAL_CONTEXT = {
        "adminmode": adminmode,
        "apikey": request.cookies.get("apikey") if adminmode else None,
        "_urikeys": keys,  #temporary!
    }
    lc = LOCAL_CONTEXT
    lc["filterkeys"], lc["limitkeys"], lc["delimitkeys"], lc["amountkeys"], lc[
        "specialkeys"] = uri_to_internal(keys)

    template = jinja_environment.get_template(name + '.jinja')
    try:
        res = template.render(**LOCAL_CONTEXT)
    except ValueError as e:
        abort(404, "Entity does not exist")

    if settings.get_settings("DEV_MODE"): jinja_environment.cache.clear()

    log("Generated page {name} in {time:.5f}s".format(name=name,
                                                      time=clock.stop()),
        module="debug_performance")
    return clean_html(res)
Esempio n. 2
0
def static_html(name):
    linkheaders = ["</style.css>; rel=preload; as=style"]
    keys = remove_identical(FormsDict.decode(request.query))

    pyhp_file = os.path.exists(pthjoin(WEBFOLDER, "pyhp", name + ".pyhp"))
    html_file = os.path.exists(pthjoin(WEBFOLDER, name + ".html"))
    jinja_file = os.path.exists(pthjoin(WEBFOLDER, "jinja", name + ".jinja"))
    pyhp_pref = settings.get_settings("USE_PYHP")
    jinja_pref = settings.get_settings("USE_JINJA")

    adminmode = request.cookies.get(
        "adminmode") == "true" and database.checkAPIkey(
            request.cookies.get("apikey")) is not False

    clock = Clock()
    clock.start()

    # if a jinja file exists, use this
    if (jinja_file and jinja_pref) or (jinja_file and not html_file
                                       and not pyhp_file):
        LOCAL_CONTEXT = {
            "adminmode": adminmode,
            "apikey": request.cookies.get("apikey") if adminmode else None,
            "_urikeys": keys,  #temporary!
        }
        LOCAL_CONTEXT["filterkeys"], LOCAL_CONTEXT["limitkeys"], LOCAL_CONTEXT[
            "delimitkeys"], LOCAL_CONTEXT["amountkeys"] = uri_to_internal(keys)

        template = jinjaenv.get_template(name + '.jinja')

        res = template.render(**LOCAL_CONTEXT)
        log("Generated page {name} in {time:.5f}s (Jinja)".format(
            name=name, time=clock.stop()),
            module="debug")
        return res

    # if a pyhp file exists, use this
    elif (pyhp_file and pyhp_pref) or (pyhp_file and not html_file):

        #things we expose to the pyhp pages
        environ = {
            "adminmode": adminmode,
            "apikey": request.cookies.get("apikey") if adminmode else None,
            # maloja
            "db": database,
            "htmlmodules": htmlmodules,
            "htmlgenerators": htmlgenerators,
            "malojatime": malojatime,
            "utilities": utilities,
            "urihandler": urihandler,
            "settings": settings.get_settings,
            # external
            "urllib": urllib
        }
        # request
        environ["filterkeys"], environ["limitkeys"], environ[
            "delimitkeys"], environ["amountkeys"] = uri_to_internal(keys)
        environ["_urikeys"] = keys  #temporary!

        #response.set_header("Content-Type","application/xhtml+xml")
        res = pyhpfile(pthjoin(WEBFOLDER, "pyhp", name + ".pyhp"), environ)
        log("Generated page {name} in {time:.5f}s (PYHP)".format(
            name=name, time=clock.stop()),
            module="debug")
        return res

    # if not, use the old way
    else:

        with open(pthjoin(WEBFOLDER, name + ".html")) as htmlfile:
            html = htmlfile.read()

        # apply global substitutions
        with open(pthjoin(WEBFOLDER, "common/footer.html")) as footerfile:
            footerhtml = footerfile.read()
        with open(pthjoin(WEBFOLDER, "common/header.html")) as headerfile:
            headerhtml = headerfile.read()
        html = html.replace("</body>", footerhtml + "</body>").replace(
            "</head>", headerhtml + "</head>")

        # If a python file exists, it provides the replacement dict for the html file
        if os.path.exists(pthjoin(WEBFOLDER, name + ".py")):
            #txt_keys = SourceFileLoader(name,"web/" + name + ".py").load_module().replacedict(keys,DATABASE_PORT)
            try:
                module = importlib.import_module(".web." + name,
                                                 package="maloja")
                txt_keys, resources = module.instructions(keys)
            except Exception as e:
                log("Error in website generation: " + str(sys.exc_info()),
                    module="error")
                raise

            # add headers for server push
            for resource in resources:
                if all(ord(c) < 128 for c in resource["file"]):
                    # we can only put ascii stuff in the http header
                    linkheaders.append("<" + resource["file"] +
                                       ">; rel=preload; as=" +
                                       resource["type"])

            # apply key substitutions
            for k in txt_keys:
                if isinstance(txt_keys[k], list):
                    # if list, we replace each occurence with the next item
                    for element in txt_keys[k]:
                        html = html.replace(k, element, 1)
                else:
                    html = html.replace(k, txt_keys[k])

        response.set_header("Link", ",".join(linkheaders))
        log("Generated page {name} in {time:.5f}s (Python+HTML)".format(
            name=name, time=clock.stop()),
            module="debug")
        return html