Ejemplo n.º 1
0
def test_render_markdown_for():
    with app.app_context():
        from flask import Blueprint
        mod = Blueprint('testme', __name__)
        result = utils.render_markdown_for('test_script.md', mod)
        assert "no file found" in result
        result = utils.render_markdown_for('takeabeltof.md', mod)
        assert "no file found" not in result
        assert "<h1>Takeabeltof</h1>" in result
Ejemplo n.º 2
0
def contact():
    setExits()
    g.name = 'Contact Us'
    from app import app
    from takeabeltof.mailer import send_message
    rendered_html = render_markdown_for(__file__, mod, 'contact.md')
    show_form = True
    context = {}
    if request.form:
        if request.form['name'] and request.form['email'] and request.form[
                'comment']:
            context['name'] = request.form['name']
            context['email'] = request.form['email']
            context['comment'] = request.form['comment']
            context['date'] = local_datetime_now().isoformat(sep=" ")
            print(context)
            send_message(
                None,
                subject="Comment from {}".format(app.config['SITE_NAME']),
                html_template="home/email/contact_email.html",
                context=context,
                reply_to=request.form['email'],
            )

            show_form = False
        else:
            context = request.form
            flash('You left some stuff out.')

    return render_template('contact.html',
                           rendered_html=rendered_html,
                           show_form=show_form,
                           context=context)
Ejemplo n.º 3
0
def about():
    setExits()
    g.title = "About"

    rendered_html = render_markdown_for('about.md', mod)

    return render_template('markdown.html', rendered_html=rendered_html)
Ejemplo n.º 4
0
def about():
    setExits()
    g.title = "About Jumstats"

    rendered_html = render_markdown_for(__file__, mod, 'about.md')

    return render_template('markdown.html', rendered_html=rendered_html)
Ejemplo n.º 5
0
def home():
    setExits()
    g.suppress_page_header = True
    rendered_html = render_markdown_for('index.md', mod)

    return render_template(
        'markdown.html',
        rendered_html=rendered_html,
    )
Ejemplo n.º 6
0
Archivo: news.py Proyecto: wleddy/news
def display():
    setExits()
    #import pdb; pdb.set_trace()
    rendered_html = render_markdown_for(__file__,mod,'news/news.md')
    
    recs = Article(g.db).select()
    
    return render_template('news/news.html',
        rendered_html=rendered_html, recs = recs,
        )    
Ejemplo n.º 7
0
def render_home_page_to_cache(force=False):
    """If Home page HTML is not in pref table, render the HTML for the home page and save it to prefs table.
    Always return the rendered html
    
    if force == True, ignore the expiration date and always render the html fresh
    
    """
    #get the time cache expiration TTL
    try:
        from app import app
        cache_exp_minutes = app.config['JUMP_DATA_CACHE_TTL']
    except:
        cache_exp_minutes = 20

    page_name = "cache_home_page"
    cache = Pref(g.db).select_one(where='name = "{}"'.format(page_name, ))
    # see if the page is in cache
    if cache and cache.expires >= datetime_as_string(
            local_datetime_now()) and force == False:
        # deliver from cache
        content = cache.value
    else:
        #otherwise render a new page and save it to cache
        rendered_html = render_markdown_for(__file__, mod, 'index.md')
        report_data = get_report_data()
        summary_data = jump.make_data_dict()
        hourly_data = hourlies(1)
        hourly_graph_html = hourly_graph.hourly_graph(hourly_data)

        content = render_template(
            'index_body.html',
            rendered_html=rendered_html,
            data=summary_data,
            report_data=report_data,
            hourly_data=hourly_data,
            hourly_graph_html=hourly_graph_html,
        )

        if not cache:
            cache = Pref(g.db).new()

        cache.name = page_name
        cache.value = content
        expires = local_datetime_now() + timedelta(
            seconds=60 * cache_exp_minutes)  # cache TTL
        cache.expires = datetime_as_string(expires)
        Pref(g.db).save(cache)

        try:
            g.db.commit()
        except:
            g.db.rollback()
            #satify without saving to cache

    return content
Ejemplo n.º 8
0
def docs(filename=None):
    setExits()
    g.title = "Docs"
    from app import get_app_config
    app_config = get_app_config()

    #import pdb;pdb.set_trace()

    file_exists = False
    if not filename:
        filename = "README.md"
    else:
        filename = filename.strip('/')

    # first try to get it as a (possibly) valid path
    temp_path = os.path.join(os.path.dirname(os.path.abspath(__name__)),
                             filename)
    if not os.path.isfile(temp_path):
        # try the default doc dir
        temp_path = os.path.join(os.path.dirname(os.path.abspath(__name__)),
                                 'docs', filename)

    if not os.path.isfile(temp_path) and 'DOC_DIRECTORY_LIST' in app_config:
        for path in app_config['DOC_DIRECTORY_LIST']:
            temp_path = os.path.join(
                os.path.dirname(os.path.abspath(__name__)), path.strip('/'),
                filename)
            if os.path.isfile(temp_path):
                break

    filename = temp_path
    file_exists = os.path.isfile(filename)

    if file_exists:
        rendered_html = render_markdown_for(filename, mod)
        return render_template('markdown.html', rendered_html=rendered_html)
    else:
        #file not found
        abort(404)
Ejemplo n.º 9
0
def register():
    """Allow people to sign up thier own accounts on the web site"""
    setExits()
    g.title = "Account Registration"
    g.editURL = url_for('.register')
    g.listURL = '/'  # incase user cancels
    user = User(g.db)
    rec = user.new()

    from takeabeltof.mailer import send_message
    from app import app

    is_admin = False
    user_roles = None
    roles = None
    no_delete = True
    success = True
    help = render_markdown_for("user/new_account_help.md", mod)

    if 'confirm' in request.args:
        #Try to find the user record that requested registration
        rec = user.select_one(where='access_token = "{}"'.format(
            request.args.get('confirm', '')).strip())
        if rec and rec.access_token_expires > time():
            if rec.active == 1:
                success = "active"
            else:
                success = "waiting"

            #inform the admin
            to = [(app.config['MAIL_DEFAULT_SENDER'],
                   app.config['MAIL_DEFAULT_ADDR'])]
            confirmURL = "{}://{}{}?activate={}".format(
                app.config['HOST_PROTOCOL'], app.config['HOST_NAME'],
                url_for('.activate'), rec.access_token)
            deleteURL = "{}://{}{}?delete={}".format(
                app.config['HOST_PROTOCOL'], app.config['HOST_NAME'],
                url_for('.delete'), rec.access_token)
            context = {
                'rec': rec,
                'confirmURL': confirmURL,
                'deleteURL': deleteURL
            }
            subject = 'Activate Account Request from - {}'.format(
                app.config['SITE_NAME'])
            html_template = 'user/email/admin_activate_acct.html'
            text_template = None
            send_message(to,
                         context=context,
                         subject=subject,
                         html_template=html_template,
                         text_template=text_template)

            return render_template('user/registration_success.html',
                                   success=success)
        else:
            flash("That registration request has expired")
            return redirect('/')

    if not request.form:
        pass
    else:
        if validForm(rec):
            #update the record
            user.update(rec, request.form)
            rec.active = 0  # Self registered accounts are inactive by default
            set_password_from_form(rec)
            set_username_from_form(rec)
            rec.access_token = get_access_token()
            rec.access_token_expires = time() + (3600 * 48)

            try:
                user.save(rec)

                #Send confirmation email to user
                full_name = '{} {}'.format(rec.first_name,
                                           rec.last_name).strip()
                to = [(full_name, rec.email)]
                context = {'rec': rec, 'confirmation_code': rec.access_token}
                subject = 'Signup Success'
                html_template = 'user/email/registration_confirm.html'
                text_template = 'user/email/registration_confirm.txt'
                send_message(to,
                             context=context,
                             subject=subject,
                             html_template=html_template,
                             text_template=text_template)

                #inform the admin
                to = [(app.config['MAIL_DEFAULT_SENDER'],
                       app.config['MAIL_DEFAULT_ADDR'])]
                deleteURL = "{}://{}{}?delete={}".format(
                    app.config['HOST_PROTOCOL'], app.config['HOST_NAME'],
                    url_for('.delete'), rec.access_token)
                context = {
                    'rec':
                    rec,
                    'deleteURL':
                    deleteURL,
                    'registration_exp':
                    datetime.fromtimestamp(
                        rec.access_token_expires).strftime('%Y-%m-%d %H:%M:%S')
                }
                subject = 'Unconfirmed Account Request from - {}'.format(
                    app.config['SITE_NAME'])
                html_template = 'user/email/admin_activate_acct.html'
                text_template = None
                send_message(to,
                             context=context,
                             subject=subject,
                             html_template=html_template,
                             text_template=text_template)

                g.db.commit()

            except Exception as e:
                g.db.rollback()
                mes = "An error occured while new user was attempting to register"
                printException(mes, "error", e)
                # Send email to the administrator
                to = [(app.config['MAIL_DEFAULT_SENDER'],
                       app.config['MAIL_DEFAULT_ADDR'])]
                context = {'mes': mes, 'rec': rec, 'e': str(e)}
                body = "Signup Error\n{{context.mes}}\n{{context.e}}\nrec:\n{{context.rec}}"
                send_message(to, context=context, body=body, subject=mes)
                success = False

            return render_template('user/registration_success.html',
                                   success=success)
        else:
            #validation failed
            user.update(rec, request.form)

    return render_template('user/user_edit.html',
                           rec=rec,
                           no_delete=no_delete,
                           is_admin=is_admin,
                           user_roles=user_roles,
                           roles=roles,
                           help=help)
Ejemplo n.º 10
0
def docs_data():
    setExits()
    g.title = "Data Dictionary"

    rendered_html = render_markdown_for(__file__, mod, '/doc_data.md')
    return render_template('markdown.html', rendered_html=rendered_html)
Ejemplo n.º 11
0
def docs_home():
    setExits()
    g.title = "Documentation List"

    rendered_html = render_markdown_for(__file__, mod, '/doc_home.md')
    return render_template('markdown.html', rendered_html=rendered_html)
Ejemplo n.º 12
0
def contact():
    setExits()
    g.title = 'Contact Us'
    from app import app
    from takeabeltof.mailer import send_message
    rendered_html = render_markdown_for('contact.md', mod)

    show_form = True
    context = {}
    success = True
    passed_quiz = False
    mes = "No errors yet..."
    if request.form:
        #import pdb;pdb.set_trace()
        quiz_answer = request.form.get('quiz_answer', "A")
        if quiz_answer.upper() == "C":
            passed_quiz = True
        else:
            flash("You did not answer the quiz correctly.")
        if request.form['email'] and request.form['comment'] and passed_quiz:
            context.update({'date': datetime_as_string()})
            for key, value in request.form.items():
                context.update({key: value})

            # get best contact email
            to = []
            # See if the contact info is in Prefs
            try:
                from users.views.pref import get_contact_email
                contact_to = get_contact_email()
                if contact_to:
                    to.append(contact_to)
            except Exception as e:
                printException(
                    "Need to update home.contact to find contacts in prefs.",
                    "error", e)

            try:
                admin_to = None
                if not to:
                    to = [
                        (
                            app.config['CONTACT_NAME'],
                            app.config['CONTACT_EMAIL_ADDR'],
                        ),
                    ]
                if app.config['CC_ADMIN_ON_CONTACT']:
                    admin_to = (
                        app.config['MAIL_DEFAULT_SENDER'],
                        app.config['MAIL_DEFAULT_ADDR'],
                    )

                if admin_to:
                    to.append(admin_to, )

            except KeyError as e:
                mes = "Could not get email addresses."
                mes = printException(mes, "error", e)
                if to:
                    #we have at least a to address, so continue
                    pass
                else:
                    success = False

            if success:
                # Ok so far... Try to send
                success, mes = send_message(
                    to,
                    subject="Contact from {}".format(app.config['SITE_NAME']),
                    html_template="home/email/contact_email.html",
                    context=context,
                    reply_to=request.form['email'],
                )

            show_form = False
        else:
            context = request.form
            flash('You left some stuff out.')

    if success:
        return render_template('contact.html',
                               rendered_html=rendered_html,
                               show_form=show_form,
                               context=context,
                               passed_quiz=passed_quiz)

    handle_request_error(mes, request, 500)
    flash(mes)
    return render_template('500.html'), 500