Ejemplo n.º 1
0
def index():
    """トップページ
    テンプレートを使用してページを表示します
    """
    greeting_list = load_data()
    template = env.get_template('index.html')
    return template.render(greeting_list=greeting_list)
Ejemplo n.º 2
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)
Ejemplo n.º 3
0
def customerror(error):
	errorcode = error.status_code
	errordesc = error.status
	traceback = error.traceback
	traceback = traceback.strip() if traceback is not None else "No Traceback"
	adminmode = request.cookies.get("adminmode") == "true" and auth.check(request)

	template = jinja_environment.get_template('error.jinja')
	res = template.render(errorcode=errorcode,errordesc=errordesc,traceback=traceback,adminmode=adminmode)
	return res
Ejemplo n.º 4
0
    def index():
        db.cursor.execute(
            "select url, description from bookmarks order by count desc")
        bookmarks = db.cursor.fetchall()

        bookmarks = [(("/redirect?url=" + url, desc) if desc else
                      ("/redirect?url=" + url, url))
                     for (url, desc) in bookmarks]

        return template.render(bookmarks=bookmarks)
Ejemplo n.º 5
0
def index():
    with open('ind.template', 'r') as f:
        template = SimpleTemplate('\n'.join(f.readlines()))
    with open('allresults_new.json', 'r') as f:
        data = ''.join(f.readlines())
    with open('text.html', 'r') as f:
        text = ''.join(f.readlines())
    with open('graphing.html', 'r') as f:
        config = ''.join(f.readlines())
    return template.render(text=text, data=data, config=config)
Ejemplo n.º 6
0
def login():
    error = None
    if request.method == 'POST':
        try:
            do_login(request.form['username'],
                     request.form['password'])
        except ValueError:
            error = "Invalid Login"
        else:
            return redirect(app.url('show_entries'))
    template = jinja2_env.get_template('login.html')
    return template.render('login.html', error=error)
Ejemplo n.º 7
0
def register():
    form = RegistrationForm(request.POST)
    userExists = False
    if request.method == 'POST' and form.validate():
        connection = Connection()
        db = connection.test_database
        users = db.users
        userExists = users.find_one({'email' : str(form.email.data)})
        if not userExists:
            user = {'_id':users.count(),
                    'email' : str(form.email.data),
                    'password' : str(form.password.data)}
            users.insert(user)
        else:
            form.email.errors = {"User exists 2"}
            
    template = env.get_template('index.html')
    return template.render(form=form)
Ejemplo n.º 8
0
def register():
    form = RegistrationForm(request.POST)
    userExists = False
    if request.method == 'POST' and form.validate():
        connection = Connection()
        db = connection.test_database
        users = db.users
        userExists = users.find_one({'email': str(form.email.data)})
        if not userExists:
            user = {
                '_id': users.count(),
                'email': str(form.email.data),
                'password': str(form.password.data)
            }
            users.insert(user)
        else:
            form.email.errors = {"User exists 2"}

    template = env.get_template('index.html')
    return template.render(form=form)
Ejemplo n.º 9
0
def pyhp(path):
    # filter path name (no leading /, no ..),
    # make sure it's not /static/, /session/, /pyhp.py, etc.
    #   (maybe put all pages in /pages/ ?
    if path == '/':
        path = '/index.pyhp'
    print(f"TEST Attempting to load path: '{path}'")

    ## get template file
    template = env.get_template(path)

    ## load session (using cookie hash)

    ## databass?

    ## extract cookies, forms, etc. from request?

    ## save session data

    ## return page or error
    #return "ha ha butts: " + path + " " + str(dict(request.query))
    return template.render(request=request, session={})
Ejemplo n.º 10
0
def homepage():
    template = env.get_template("homepage.html")
    context = {}
    return template.render(context)
Ejemplo n.º 11
0
def login_success():
    template = env.get_template("login_success.html")
    context = {
        'redirect_url': "{}/stats".format(SITE_DOMAIN)
    }
    return template.render(context)
Ejemplo n.º 12
0
            "payment",
            ]

        IGNORE_BODY_KEYWORDS = [
            "unsubscribe",
            ]

        print datetime.datetime.now()
        context = calculate_email_stats(
            USERNAME,
            ACCESS_TOKEN,
            DAYS,
            ALIASES=ALIASES,
            IGNORE_EMAILS=IGNORE_EMAILS,
            IGNORE_SUBJECT_KEYWORDS=IGNORE_SUBJECT_KEYWORDS,
            IGNORE_BODY_KEYWORDS=IGNORE_BODY_KEYWORDS,
            MIN_THREAD_LENGTH=2,
            )

        if SAVE is True:
            with open(FILENAME, "w") as f:
                pickle.dump(context, f)

    print datetime.datetime.now()
    # context.update(locals())

    return template.render(context)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8080)
Ejemplo n.º 13
0
def customerror(error):
	code = int(str(error).split(",")[0][1:])

	template = jinjaenv.get_template('error.jinja')
	res = template.render(errorcode=code)
	return res
Ejemplo n.º 14
0
def show_entries(db):
    entries = get_all_entries(db)
    jinja2_env.get_te
    template = jinja2_env.get_template('show_entries.html')
    return template.render( entries=entries)
Ejemplo n.º 15
0
def log_in_again():
    template = env.get_template("log_in_again.html")
    context = {}
    return template.render(context)
Ejemplo n.º 16
0
def error404(error):
    with open('./views/fourohfour.tpl','r') as fp:
        data = fp.read()
        template = SimpleTemplate(data)
        return template.render(error=error,title="ruh roh!")
Ejemplo n.º 17
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
Ejemplo n.º 18
0
def error404(error):
    with open('./views/fourohfour.tpl', 'r') as fp:
        data = fp.read()
        template = SimpleTemplate(data)
        return template.render(error=error, title="ruh roh!")