Example #1
0
    def setUp(self):
        bp = Blueprint(
            'bp',
            __name__,
            template_folder=['templates/bp', 'another_templates/another_bp'])

        @bp.route('/render_bp_from_templates')
        def render_bp_from_templates():
            return render_template('bp.html', result="succeeds")

        @bp.route('/render_bp_from_another_templates')
        def render_bp_from_another_templates():
            return render_template('another_bp.html', result="succeeds")

        app = Flask(__name__,
                    template_folder=['templates', 'another_templates'])
        MakoTemplates(app)

        @app.route('/render_from_templates')
        def render_from_templates():
            return render_template('template_file.html', result="succeeds")

        @app.route('/render_from_another_templates')
        def render_from_another_templates():
            return render_template('another_template_file.html',
                                   result="succeeds")

        app.register_blueprint(bp)
        self.app = app
        self.client = app.test_client()
Example #2
0
    def __init__(self, bot):
        self.bot = bot

        self.cfg = PluginConfig(self)
        self.db = FileBackend(self.cfg.get('main_db'))

        mtt = MessageRetargeter(bot)
        self.msg = mtt.msg

        web = Flask(__name__, template_folder=tmpl_dir)
        mako = MakoTemplates()
        mako.init_app(web)

        # Add routes here
        web.add_url_rule('/edit_web/<args>', 'edit_web', self.edit_web, methods=['GET', 'POST'])

        _thread.start_new_thread(web.run, (), {'host': '0.0.0.0'})
Example #3
0
 def test_renderer(self, **kwargs):
     app = Flask(__name__)
     app.template_folder = os.path.join(self.root, "templates")
     app.config.update(MAKO_CACHE_DIR=os.path.join(self.root, "cache"),
                       MAKO_CACHE_SIZE=10)
     app.config.update(kwargs)
     with app.test_request_context():
         yield app, MakoTemplates(app)
Example #4
0
def bootstrap_server():
    app = Flask("camrail")
    config = Config()
    app.config.from_object(config)
    app.template_folder = config.template_folder
    mako_templates = MakoTemplates(app)
    globals()["app"] = app
    globals()["mako_templates"] = mako_templates
Example #5
0
    def create_lookup(app):
        lookup = Base.create_lookup(app)
        lookup.default_filters = ['unicode_safe']
        
        get_template = lookup.get_template
        def new_get_template(name):
            g._mako_template_name = name
            return get_template(name)
        lookup.get_template = new_get_template
        
        lookup.template_args['preprocessor'] = preprocessor

        return lookup
Example #6
0
        def setUp(self):
            app = Flask(__name__)
            app.debug = True
            babel = Babel(app)
            mako = MakoTemplates(app)
            self.app = app
            self.mako = mako
            self.babel = babel

            @app.route('/')
            def babel_page():
                return render_template('babel_template.html')

            @babel.localeselector
            def get_locale():
                return self.locale
Example #7
0
def create_app():
    app = Flask(__name__)

    # import blueprint
    from controller.index import index_blueprint

    # reg blueprint
    app.register_blueprint(index_blueprint)

    config = load_config()
    app.config.from_object(config)

    from flask.ext.mako import MakoTemplates
    MakoTemplates(app)

    return app
Example #8
0
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        app.config['MAKO_DIR'] = MAKO_DIR
        mako = MakoTemplates(app)
        self.app = app
        self.mako = mako
        cur_dir = os.path.dirname(os.path.realpath(__file__))
        self.content_path = join(cur_dir, 'content')
        self.output_path = join(cur_dir, 'output')
        self.output_tags_path = join(self.output_path, 'tags')

        @app.route('/regen')
        def regen():
            client = DummyDropboxClient()
            DropboxSync(client, self.content_path, self.output_path,
                        self.output_tags_path).gen_pages()
            return 'OK'
Example #9
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('app.cfg')

    MakoTemplates(app)

    for blueprint_qualname in blueprints:
        blueprint = import_string(blueprint_qualname)
        app.register_blueprint(blueprint)

    @app.before_request
    def before_request():
        g.debug = True

    @app.teardown_appcontext
    def teardown_db(exception):
        db = getattr(g, '_database', None)
        if db is not None:
            db.close()

    return app
Example #10
0
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        mako = MakoTemplates(app)
        self.app = app
        self.mako = mako

        @app.before_request
        def setup_context():
            g.test_g = "test_g"

        @app.route('/context')
        def context():
            return render_template_string(u"${ g.test_g }")

        @app.route('/templatefile')
        def template_file():
            return render_template('template_file.html', result="succeeds")

        @app.route('/def_file')
        def def_file():
            return render_template_def('def_file.html',
                                       'test_def',
                                       result="This")
Example #11
0
File: ext.py Project: thanhnd5/fork
# -*- coding: utf-8 -*-
"""
    ext
    ~~~

    Good place for pluggable extensions.

"""

from flask.ext.debugtoolbar import DebugToolbarExtension
from flask.ext.login import LoginManager
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.assets import Environment
from flask.ext.mako import MakoTemplates

db = SQLAlchemy()
assets = Environment()
login_manager = LoginManager()

# Almost any modern Flask extension has special init_app()
# method for deferred app binding. But there are a couple of
# popular extensions that no nothing about such use case.

toolbar = lambda app: DebugToolbarExtension(app)  # has no init_app()

mako = lambda app: MakoTemplates(app)
class MustInheritFromStatdatabase(Exception):
    pass

if __name__ == "__main__":
    import ssl

    app.config.from_pyfile("settings.cfg")
    LOGGER = logging.getLogger("alservice")
    hdlr = logging.FileHandler(app.config["LOG_FILE"])
    base_formatter = logging.Formatter("[%(asctime)-19.19s] [%(levelname)-5.5s]: %(message)s")
    hdlr.setLevel(app.config["LOG_LEVEL"])
    hdlr.setFormatter(base_formatter)
    LOGGER.addHandler(hdlr)
    LOGGER.setLevel(logging.DEBUG)
    mako = MakoTemplates()
    mako.init_app(app)
    app._mako_lookup = TemplateLookup(directories=["templates"],
                                      input_encoding='utf-8', output_encoding='utf-8',
                                      imports=["from flask.ext.babel import gettext as _"])
    context = None
    if app.config['SSL']:
        context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        context.load_cert_chain(app.config["SERVER_CERT"], app.config["SERVER_KEY"])
    global keys
    global stat_service
    global base
    keys = []
    for key in app.config["JWT_PUB_KEY"]:
        _bkey = rsa_load(key)
        pub_key = RSAKey().load_key(_bkey)
    pass


if __name__ == "__main__":
    import ssl

    app.config.from_pyfile("settings.cfg")
    LOGGER = logging.getLogger("alservice")
    hdlr = logging.FileHandler(app.config["LOG_FILE"])
    base_formatter = logging.Formatter(
        "[%(asctime)-19.19s] [%(levelname)-5.5s]: %(message)s")
    hdlr.setLevel(app.config["LOG_LEVEL"])
    hdlr.setFormatter(base_formatter)
    LOGGER.addHandler(hdlr)
    LOGGER.setLevel(logging.DEBUG)
    mako = MakoTemplates()
    mako.init_app(app)
    app._mako_lookup = TemplateLookup(
        directories=["templates"],
        input_encoding='utf-8',
        output_encoding='utf-8',
        imports=["from flask.ext.babel import gettext as _"])
    context = None
    if app.config['SSL']:
        context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        context.load_cert_chain(app.config["SERVER_CERT"],
                                app.config["SERVER_KEY"])
    global keys
    global stat_service
    global base
    keys = []
Example #14
0
import logging
import itertools

from flask import Flask, request, session, g, redirect, url_for, abort, flash
from flask.ext.mako import MakoTemplates, render_template

from evaluate import AnnotationInterface
from config import data_path, sqldict_path

logger = logging.getLogger(__name__)

app = Flask(__name__)
app.template_folder = "templates"
app.secret_key = '[l=xPsQ\x88\xc4\x19\r\xdf\x06\xb2\xa6\xfa$\x114\x97?\xc3\xab\x9f\xe2'
app.debug = True
mako = MakoTemplates(app)

ai = AnnotationInterface(data_path, sqldict_path)


def get_user_stats(username):
    """For given user, find number of annotated and skipped listings.

    :param username: searched user
    :return: two dictionaries {'done': count, 'skipped': count}
    """

    return ai.get_stats(username)


@app.route('/login', methods=['GET', 'POST'])
Example #15
0
import tempfile
import urlparse
import ConfigParser

import MySQLdb,MySQLdb.cursors

from functools import wraps

from flask import Flask,request,make_response,send_file,Response
from flask.ext.mako import MakoTemplates,render_template
import mako.exceptions

app = Flask(__name__)
app.config['MAKO_TRANSLATE_EXCEPTIONS'] = False

makotmpl = MakoTemplates(app)

cfg = ConfigParser.ConfigParser()
cfg.read(['db.cfg'])

class FilterSet(object):
    def __init__(self, report, mode='html'):
        self.mode = mode
        if 'filters' not in report:
            self.filters = {}
        else:
            self.filters = report['filters']

    def run(self, column, s, *args, **kw):
        return getattr(self, self.filters.get(column,'noop'))(s, *args, **kw)
Example #16
0
import flask
from flask_fas_openid import FAS
from flask.ext.mako import MakoTemplates

from fedoratagger.lib import create_session

# Create the application.
APP = flask.Flask(__name__)
# set up FAS
APP.config.from_object('fedoratagger.default_config')
if 'FEDORATAGGER_CONFIG' in os.environ:  # pragma: no cover
    APP.config.from_envvar('FEDORATAGGER_CONFIG')
APP.config['FAS_OPENID_CHECK_CERT'] = False
FAS = FAS(APP)
mako = MakoTemplates(APP)
SESSION = create_session(APP.config['DB_URL'])

from fedoratagger.api import API
from fedoratagger.frontend import FRONTEND

APP.register_blueprint(API)
APP.register_blueprint(FRONTEND)
APP.wsgi_app = make_tw2_middleware(
    APP.wsgi_app,
    res_prefix=APP.config['RES_PREFIX'],
)


# pylint: disable=W0613
@APP.teardown_request
Example #17
0
def register_mako(app):
    MakoTemplates(app)
Example #18
0
# -*- coding: utf-8 -*-
"""Flask app initialization."""
from flask import Flask
from flask.ext.mako import MakoTemplates  # pylint: disable=no-name-in-module, import-error

app = Flask(__name__)  # pylint: disable=invalid-name
mako = MakoTemplates(app)  # pylint: disable=invalid-name
Example #19
0
from flask.ext.mako import MakoTemplates, render_template
from flask_sqlalchemy import SQLAlchemy

mako = MakoTemplates()
db = SQLAlchemy()
Example #20
0
import json

from flask import render_template, redirect, url_for, request
from flask.ext.login import login_required
from flask.ext.mako import MakoTemplates
from flask.ext.mako import render_template as render_mako

from bradmin import app

mako = MakoTemplates(app)

@app.route("/mesh")
@login_required
def mesh():
    return render_mako('mesh.html')

# -*- coding: utf-8 -*-
"""
Defines views.
"""

import calendar
from flask import redirect, url_for
from flask import Flask
from flask.ext.mako import MakoTemplates, render_template, exceptions
app = Flask(__name__)  # pylint: disable-msg=C0103
mako = MakoTemplates(app)  # pylint: disable-msg=C0103
from presence_analyzer.main import app
from presence_analyzer.utils import jsonify, get_data, mean, group_by_weekday
from presence_analyzer.utils import return_id_start_end, get_data_from_xml

import logging
log = logging.getLogger(__name__)  # pylint: disable-msg=C0103

pages_list = [
    'presence_weekday',
    'mean_time_weekday',
    'presence_start_end'
]


@app.route('/')
def mainpage():
    """
    Redirects to front page.
    """
    return redirect(url_for('page_to_render', page_name='presence_weekday'))