Exemple #1
0
 def inner(*args, **kwargs):
     try:
         return func(*args, **kwargs)
     except TemplateError as exc:
         app.logger.error(u"Caught exception:\n{0}".format(exc.text))
         return render_template("error.mako", traceback=exc.text)
     except Exception:
         app.logger.exception(u"Caught exception:")
         return render_template("error.mako", traceback=format_exc())
Exemple #2
0
def index():
    if request.method == 'POST':
        uploaded_file = request.files['file']
        w = request.form.get('w')
        h = request.form.get('h')
        if not uploaded_file:
            return abort(400)

        if w and h:
            paste_file = PasteFile.create_file_after_crop(uploaded_file, w, h)
        else:
            paste_file = PasteFile.create_by_upload_file(uploaded_file)
        db.session.add(paste_file)
        db.session.commit()

        return jsonify({
            'url_d': paste_file.url_d,
            'url_i': paste_file.url_i,
            'url_s': paste_file.url_s,
            'url_p': paste_file.url_p,
            'filename': paste_file.filename,
            'size': paste_file.size_humanize,
            'time': str(paste_file.uploadtime),
            'type': paste_file.type,
            'quoteurl': paste_file.quoteurl
        })
    return render_template('index.html', **locals())
Exemple #3
0
def settings():
    status = process_settings() if request.method == "POST" else None
    update_sites()
    default = cache.bot.wiki.get_site()
    kwargs = {"status": status, "default_lang": default.lang,
              "default_project": default.project}
    return render_template("settings.mako", **kwargs)
Exemple #4
0
 def get(self):
     url = request.args.get('url', '')
     url_pattern = url.rsplit('/', 1)[0]
     keyboards = KEYBOARD_URL_MAPS['default']
     if url_pattern in KEYBOARD_URL_MAPS:
         keyboards += KEYBOARD_URL_MAPS[url_pattern]
     return render_template('widgets/keyboard.html', keyboards=keyboards)
Exemple #5
0
def index():
    notice = get_notice()
    update_sites()
    query = do_check()
    return render_template(
        "index.mako", notice=notice, query=query, result=query.result,
        turnitin_result=query.turnitin_result)
def render_page(template_name):
    """
    Render templates by template_name.
    """
    try:
        return render_template(template_name + '.html')
    except TopLevelLookupException:
        abort(404)
Exemple #7
0
 def get(self, slug):
     category = Category.objects.get_or_404(_slug=slug)
     posts = Post.objects.filter(
         category=category
     ).order_by("-recent_activity_time")
     return render_template('categories/list.html',
                            category=category.name,
                            posts=posts)
Exemple #8
0
def section(chapter, section):
    chapter = secure_filename(chapter)
    section = secure_filename(section)
    path = os.path.join(BOOK_DIR, chapter, section)
    with codecs.open(path, 'r', 'utf-8') as f:
        content = f.read()
    content = Markup(markdown(content))
    return render_template('page.html', **locals())
Exemple #9
0
def index():
    # not logged in, redirect
    # if 'logged_in' not in session:
    #     return redirect(url_for('login'))

    # process POST request
    if request.method == 'POST':
        pass
    return render_template('index.html', error=None)
Exemple #10
0
 def _deco(*args, **kwargs):
     template_name = template
     if template_name is None:
         template_name = request.endpoint.replace(".", "/") + ".html"
     ctx = f(*args, **kwargs)
     if ctx is None:
         ctx = {}
     elif not isinstance(ctx, dict):
         return ctx
     return render_template(template_name, **ctx)
def render_templates(template_name):
    """
    Render .html file to view.
    """
    if not template_name.endswith('.html'):
        template_name = '{}.html'.format(template_name)
    try:
        return render_template(template_name, name=template_name)
    except (TemplateError, TopLevelLookupException):
        abort(404)
Exemple #12
0
def verify_pin():
    pin = request.form["pin"]
    token = session["token"]
    redirect_url = current_app.al.get_redirect_url(token)
    try:
        current_app.al.create_account_step3(token, pin)
    except ALserviceNotAValidPin:
        return render_template(
            "save_account.mako", form_action="/verify_token", pin_error=True, language=session["language"]
        )
    return redirect(redirect_url)
Exemple #13
0
def data():
    # not logged in, redirect
    # if 'logged_in' not in session:
    #     return redirect(url_for('login'))

    # process POST request
    if request.method == 'POST':
        pass

    available_sources = [name for name in os.listdir('http_server/static/author_corpus/') if not name.startswith('.')]
    return render_template('data.html', error=None, sources=available_sources)
Exemple #14
0
def verify_token():
    if not change_language():
        token = request.form.get("token", session.get("token"))
        if not token:
            abort(400)

        session["token"] = token
        try:
            current_app.al.create_account_step2(token)
        except (ALserviceTokenError, ALserviceTicketError):
            return render_template(
                "token_was_sent.mako",
                form_action="/verify_token",
                email=session["email"],
                token_error=True,
                language=session["language"],
            )

    return render_template(
        "save_account.mako", form_action="/verify_token", pin_error=False, language=session["language"]
    )
Exemple #15
0
def api_json():
    if not request.args:
        return render_template("api.mako", help=True)

    format = request.args.get("format", "json")
    if format in ["json", "jsonfm"]:
        update_sites()
        try:
            result = handle_api_request()
        except Exception as exc:
            result = format_api_error("unhandled_exception", exc)
    else:
        errmsg = u"Unknown format: '{0}'".format(format)
        result = format_api_error("unknown_format", errmsg)

    if format == "jsonfm":
        return render_template("api.mako", help=False, result=result)
    resp = make_response(dumps(result))
    resp.mimetype = "application/json"
    resp.headers["Access-Control-Allow-Origin"] = "*"
    return resp
def render_correct_template(template_name):
    """
    Check and render correct template for given url.
    """
    try:
        return render_template(template_name + '.html')
    except TopLevelLookupException:
        LOG.debug('Template %s.html not found.', template_name)
        abort(404)
    except exceptions.html_error_template().render():
        LOG.debug('Template error in %s.html.', template_name)
        abort(500)
Exemple #17
0
 def handle_exception(e):
     log.exception('Exception during request')
     try:
         return render_template(current_app.config['STATUS_TEMPLATE'],
             status=DummyStatus(500, 'Internal Server Error', ''),
             traceback=traceback.format_exc() if app.debug else None,
         ), 500
     except KeyError:
         return InternalServerError()
     except TemplateError as e2:
         text = e2.text.strip()
         log.error('Exception during error template rendering\n' + text)
     return e
Exemple #18
0
    def post(self, id):
        context = self.get_context(id)
        form = context.get('form')

        if form.validate():
            comment = Comment()
            form.populate_obj(comment)

            post = context.get('post')
            post.comments.append(comment)
            post.save()

            return redirect(url_for('post.detail', id=id))
        return render_template('posts/detail.html', **context)
Exemple #19
0
def send_token():
    if not change_language():
        email = request.form.get("email", session.get("email"))
        ticket = session.get("ticket")
        if not email or not ticket:
            abort(400)

        session["email"] = email
        current_app.al.create_account_step1(email, ticket)

    return render_template(
        "token_was_sent.mako",
        form_action="/send_token",
        email=session["email"],
        token_error=False,
        language=session["language"],
    )
Exemple #20
0
def render_consent(language: str, requester_name: str, locked_attr: list, released_claims: dict, state: str,
                   months: list, select_attributes: bool) -> str:
    if not isinstance(locked_attr, list):
        locked_attr = [locked_attr]
    locked_claims = {k: released_claims.pop(k) for k in locked_attr if k in released_claims}

    return render_template(
        'consent.mako',
        consent_question=None,
        state=state,
        released_claims=released_claims,
        locked_claims=locked_claims,
        form_action='/set_language',
        language=language,
        requester_name=requester_name,
        months=months,
        select_attributes=select_attributes)
Exemple #21
0
def approve(ticket):
    template_params = dict(form_action="/approve/%s" % ticket, ticket=ticket, login_failed_message=False)

    if not change_language():
        session["ticket"] = ticket

        # user has approved linking
        if request.method == "POST":
            email = request.form["email"]
            pin = request.form["pin"]
            redirect_url = current_app.al.get_redirect_url(ticket)
            try:
                current_app.al.link_key(email, pin, ticket)
                return redirect(redirect_url)
            except ALserviceAuthenticationError:
                template_params["login_failed_message"] = True

    template_params["language"] = session["language"]
    return render_template("login.mako", **template_params)
Exemple #22
0
def preview(filehash):
    paste_file = PasteFile.get_by_filehash(filehash)

    filepath = get_file_path(filehash)
    if not paste_file:
        if not(os.path.exists(filepath) and (not os.path.islink(filepath))):
            return abort(404)

        linkfile = get_file_path(filehash.replace('.', '_'))
        symlink = None
        if os.path.exists(linkfile):
            with open(linkfile) as fp:
                symlink = fp.read().strip()

        paste_file = PasteFile.create_by_old_paste(filehash, symlink)
        db.session.add(paste_file)
        db.session.commit()

    return render_template('success.html', p=paste_file)
Exemple #23
0
    def post(self, id):
        if not current_user.is_authenticated():
            abort(403)

        context = self.get_context(id)
        form = context.get('form')

        if form.validate():
            comment = Comment()
            form.populate_obj(comment)
            comment.author = User.objects.get_or_404(id=current_user.id)
            comment.save()

            post = context.get('post')
            post.comments.append(comment)
            post.save()

            return redirect(url_for('post.detail', id=id))
        return render_template('posts/detail.html', **context)
Exemple #24
0
    def handle_http_exception(e):

        # Pass through non errors.
        if e.code < 400:
            return e

        if e.code >= 500:
            log.exception(str(e))
        else:
            log.warning(str(e))

        try:
            return render_template('/http_status.haml',
                status=e,
                traceback=traceback.format_exc() if app.debug else None,
            ), e.code
        except TemplateError as e2:
            text = e2.text.strip()
            print 'HERE', text
            log.error('Exception during error template rendering\n' + text)
        return e
def presence_start_end():
    """
    Renders presence_start_end template.
    """
    return render_template('presence_start_end.html')
Exemple #26
0
 def get(self, id):
     context = self.get_context(id)
     Post.objects(id=id).update_one(inc__views=1)
     return render_template('posts/detail.html', **context)
def mean_time_weekday():
    """
    Renders mean_time_weekday template.
    """
    return render_template('mean_time_weekday.html')
Exemple #28
0
def create_account():
    change_language()
    return render_template("create_account.mako", form_action="/create_account", language=session["language"])
Exemple #29
0
 def get(self):
     posts = Post.objects.all()
     return render_template('index.html', posts=posts)
Exemple #30
0
def api():
    return render_template("api.mako", help=True)