Example #1
1
def create_app(config=None, blueprints=None):
    """
    Create and initialise the application.
    """
    app = Flask(__name__)
    app.config.from_pyfile("%s/config/default.py" % app.root_path)
    app.url_map.converters["regex"] = RegexConverter

    app.add_template_filter(slugify)

    if blueprints is None:
        blueprints = DEFAULT_BLUEPRINTS

    configure_blueprints(app, blueprints)

    return app
def create_app(config_name):

    application = Flask(__name__,
                        static_folder='static/',
                        static_url_path=configs[config_name].ASSET_PATH)

    init_app(
        application,
        configs[config_name],
        bootstrap=bootstrap,
        data_api_client=data_api_client,
        login_manager=login_manager
    )

    application.permanent_session_lifetime = timedelta(hours=1)
    from .main import main as main_blueprint
    from .status import status as status_blueprint

    url_prefix = application.config['URL_PREFIX']
    application.register_blueprint(status_blueprint, url_prefix=url_prefix)
    application.register_blueprint(main_blueprint, url_prefix=url_prefix)
    login_manager.login_view = 'main.render_login'
    main_blueprint.config = application.config.copy()

    init_frontend_app(application, data_api_client, login_manager)

    application.add_template_filter(parse_document_upload_time)

    @application.context_processor
    def extra_template_variables():
        return {
            'generic_contact_email': application.config['GENERIC_CONTACT_EMAIL'],
        }

    return application
def create_app(config_name):

    application = Flask(__name__,
                        static_folder='static/',
                        static_url_path=configs[config_name].STATIC_URL_PATH)

    init_app(
        application,
        configs[config_name],
        bootstrap=bootstrap,
        data_api_client=data_api_client,
        feature_flags=feature_flags,
        login_manager=login_manager
    )
    # Should be incorporated into digitalmarketplace-utils as well
    csrf.init_app(application)

    application.permanent_session_lifetime = timedelta(hours=1)
    from .main import main as main_blueprint
    from .status import status as status_blueprint

    application.register_blueprint(status_blueprint, url_prefix='/admin')
    application.register_blueprint(main_blueprint, url_prefix='/admin')
    login_manager.login_view = 'main.render_login'
    main_blueprint.config = application.config.copy()

    @application.before_request
    def remove_trailing_slash():
        if request.path != '/' and request.path.endswith('/'):
            return redirect(request.path[:-1], code=301)

    application.add_template_filter(parse_document_upload_time)

    return application
Example #4
0
def app_factory(extra_config=None):
    """Builds the flask application"""
    app = Flask(__name__)

    # App defaults
    app.config.update(dict(
        DEBUG=True,
        CLEANCSS_EXTRA_ARGS=['--skip-rebase'],
        FLATPAGES_ROOT='blog',
        FLATPAGES_EXTENSION='.md',
        FLATPAGES_MARKDOWN_EXTENSIONS=['codehilite', JavierExtensions()],
        FLATPAGES_AUTO_RELOAD=True))
    # Extra config
    if extra_config:
        app.config.update(extra_config)

    # Blueprints
    app.register_blueprint(BLOG, url_prefix='/blog')
    app.register_blueprint(INDIVIDUAL)
    app.register_blueprint(FEEDS)

    # Other configuration
    app.context_processor(template_settings)
    app.add_template_filter(l10n_date)
    register_assets(app)
    register_pages(app)
    return app
Example #5
0
def create_app(app_mode='DEBUG'):
    """ Create application, register blueprints, etc """
    if app_mode == '':
        app_mode = os.environ.get('APP_MODE', 'DEBUG')
    # create an application
    app = Flask(__name__)
    app.config['SECRET_KEY'] = b'\x88~\x17h\xdc;,\x9f\x1do\x98\xcd\xaf|\x1c\x19\xec\xcf\xb1\x12\xd4\x8b\xcdQ'
    # set logging
    configure_logging(app_mode, app)
    if app_mode == 'DEBUG':
        # debugging in VSCode works only if following 2 lines are commented out
        #app.debug = True
        #app.config['DEBUG'] = True
        app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
    # register blueprints
    app.register_blueprint(public_ui)
    app.register_blueprint(member_ui)
    app.register_blueprint(customer_ui)
    # register jinja exts
    app.add_template_filter(f=points, name='points')
    # configure uploads
    app.config['UPLOAD_FOLDER'] = os.path.join(BASE_DIR, 'uploads')
    # app started
    logging.info('Application started in %s mode', app_mode)
    return app
Example #6
0
def create_app():
    app = Flask(__name__, static_folder="../static", static_url_path="/static")

    from api import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api')

    app.register_blueprint(web, url_prefix='')
    app.debug = True
    app.add_template_filter(human_date)

    return app
def create_app(config_name):
    application = Flask(__name__,
                        static_folder='static/',
                        static_url_path=configs[config_name].STATIC_URL_PATH)

    init_app(
        application,
        configs[config_name],
        data_api_client=data_api_client,
        feature_flags=feature_flags,
        login_manager=login_manager,
    )

    from .main import main as main_blueprint
    from .status import status as status_blueprint

    application.register_blueprint(status_blueprint,
                                   url_prefix='/suppliers')
    application.register_blueprint(main_blueprint,
                                   url_prefix='/suppliers')
    login_manager.login_message_category = "must_login"
    main_blueprint.config = application.config.copy()

    csrf.init_app(application)

    @csrf.error_handler
    def csrf_handler(reason):
        if 'user_id' not in session:
            application.logger.info(
                u'csrf.session_expired: Redirecting user to log in page'
            )

            return application.login_manager.unauthorized()

        application.logger.info(
            u'csrf.invalid_token: Aborting request, user_id: {user_id}',
            extra={'user_id': session['user_id']})

        abort(400, reason)

    @application.before_request
    def remove_trailing_slash():
        if request.path.endswith('/'):
            return redirect(request.path[:-1], code=301)

    @application.before_request
    def refresh_session():
        session.permanent = True
        session.modified = True

    application.add_template_filter(question_references)
    application.add_template_filter(parse_document_upload_time)

    return application
Example #8
0
def create_app(config):
    app = Flask(__name__)
    app.config.from_object(configs.get(config))

    register_extensions(app)
    # 用于创建测试数据
    Migrate(app, db)
    register_blueprints(app)
    # 注册自定义过滤器
    app.add_template_filter(get_jobdelta)

    return app
def create_app(config_name):
    asset_path = os.environ.get('ASSET_PATH', configs[config_name].ASSET_PATH)
    application = Flask(__name__,
                        static_folder='static/',
                        static_url_path=asset_path)

    init_app(
        application,
        configs[config_name],
        data_api_client=data_api_client,
        login_manager=login_manager,
    )

    from .main import main as main_blueprint
    from .status import status as status_blueprint

    url_prefix = application.config['URL_PREFIX']
    application.register_blueprint(status_blueprint,
                                   url_prefix=url_prefix)
    application.register_blueprint(main_blueprint,
                                   url_prefix=url_prefix)
    login_manager.login_message_category = "must_login"
    main_blueprint.config = application.config.copy()

    application.add_template_filter(question_references)
    application.add_template_filter(parse_document_upload_time)

    init_frontend_app(application, data_api_client, login_manager)

    @application.context_processor
    def extra_template_variables():
        return {
            'marketplace_home': urlparse.urljoin('/', application.config['BASE_PREFIX']),
            'generic_contact_email': application.config['GENERIC_CONTACT_EMAIL'],
        }

    def component_filter(x, thing, *args, **kwargs):
        from jinja2 import Markup  # , escape
        from flask import current_app

        COMPONENTS = 'components'
        EXTENSION = '.html'

        t = current_app.jinja_env.get_template(
            COMPONENTS + '/' + thing + EXTENSION)
        return Markup(t.render(x=x, **kwargs))

    application.jinja_env.filters['as'] = component_filter
    application.jinja_env.globals.update(render_component=render_component)

    return application
Example #10
0
def create_app(method):
    my_app = Flask('test_filter')

    filters = make_filters(FILTERS, method)
    for name, function in filters.items():
        my_app.add_template_filter(function, name)

    @my_app.route('/my_hex/<int:number>', endpoint='my_hex')
    @my_app.route('/my_bin/<int:number>', endpoint='my_bin')
    @my_app.route('/my_oct/<int:number>', endpoint='my_oct')
    def use_filter(number):
        filter_ = request.url_rule.endpoint
        template = '{{ filter_ }} {{ number|%s }}' % filter_
        pytest.set_trace()
        return render_template_string(template, **locals())
    return my_app
Example #11
0
def create_app(config_name):
    application = Flask(
        __name__,
        static_folder='static/',
        static_url_path=configs[config_name].STATIC_URL_PATH
    )

    application.config['NOTIFY_ENVIRONMENT'] = config_name
    application.config.from_object(configs[config_name])

    init_app(application)
    csrf.init_app(application)

    @csrf.error_handler
    def csrf_handler(reason):
        if 'user_id' not in session:
            application.logger.info(
                u'csrf.session_expired: Redirecting user to log in page'
            )

            return application.login_manager.unauthorized()

        application.logger.info(
            u'csrf.invalid_token: Aborting request, user_id: {user_id}',
            extra={'user_id': session['user_id']})

        abort(400, reason)

    login_manager.init_app(application)
    admin_api_client.init_app(application)
    proxy_fix.init_app(application)

    from .main import main as main_blueprint
    application.permanent_session_lifetime = timedelta(hours=1)
    application.register_blueprint(main_blueprint, url_prefix='/admin')
    login_manager.login_view = 'main.render_login'

    main_blueprint.config = application.config.copy()

    @application.before_request
    def remove_trailing_slash():
        if request.path != '/' and request.path.endswith('/'):
            return redirect(request.path[:-1], code=301)

    application.add_template_filter(datetimeformat)

    return application
Example #12
0
class App(object):
    def __init__(self):
        self._indices = {}
        templateFolder = os.path.join(
            os.path.dirname(os.path.abspath(__file__)), 'templates')
        staticFolder = os.path.join(
            os.path.dirname(os.path.abspath(__file__)), 'static')
        self._app = Flask('pyaci Query App',
                          static_folder=staticFolder,
                          template_folder=templateFolder)
        self._app.add_template_test(isDn, 'Dn')
        self._app.add_template_filter(getParentDn, 'parentDn')

    def addIndex(self, index):
        # TODO: Handle duplicate index.
        self._indices[index.name] = index
        self._app.add_url_rule(
            '/{}/dn/<path:dn>'.format(index.name),
            view_func=DnView.as_view('dn_view_{}'.format(index.name),
                                     index, self),
            methods=['GET']
        )
        self._app.add_url_rule(
            '/{}/class/<className>'.format(index.name),
            view_func=ClassView.as_view('class_view_{}'.format(index.name),
                                        index, self),
            methods=['GET']
        )

        if index.name == 'audit':
            self._app.add_url_rule(
                '/{}/affected/<path:dn>'.format(index.name),
                view_func=AuditView.as_view(
                    'affected_view_{}'.format(index.name),
                    index, self),
                methods=['GET']
            )

    def indices(self):
        return self._indices

    def run(self, debug=False):
        self._app.debug = debug
        self._app.run(host='0.0.0.0')
Example #13
0
def create_app_by_config(config=None, profile=False):
    app = Flask(__name__)
    # 初始化环境配置
    app.config.from_object("config.default")
    if config:
        try:
            app.config.from_object(config)
        except:
            raise ValueError("[%s] config is not exists" % config)

    from qsapp.views.qsmain_view import qsmain
    from qsapp.views.wechat_view import wechat
    app.register_blueprint(qsmain)
    app.register_blueprint(wechat)

    # 增加过滤器
    for value in template_filters.__dict__.values():
        if callable(value):
            app.add_template_filter(value)
    return app
Example #14
0
    def _crea_app(self, config=None):
        app = Flask(__name__, template_folder="plantillas" )
        app.psdash = self
        app.config.from_envvar('PSDASH_CONFIG', silent=True)

        if config and isinstance(config, dict):
            app.config.update(config)

        self._cargar_direccciones_remotas_permitidas(app)

        # If the secret key is not read from the config just set it to something.
        if not app.secret_key:
            app.secret_key = 'whatisthissourcery'
        app.add_template_filter(fromtimestamp)

        from controlador_web import webapp
        prefix = app.config.get('PSDASH_URL_PREFIX')
        if prefix:
            prefix = '/' + prefix.strip('/')
        webapp.url_prefix = prefix
        app.register_blueprint(webapp)

        return app
Example #15
0
    def _create_app(self, config=None):
        app = Flask(__name__)
        app.psdash = self
        app.config.from_envvar('PSDASH_CONFIG', silent=True)

        if config and isinstance(config, dict):
            app.config.update(config)

        self._load_allowed_remote_addresses(app)

        # If the secret key is not read from the config just set it to something.
        if not app.secret_key:
            app.secret_key = 'whatisthissourcery'
        app.add_template_filter(fromtimestamp)

        from psdash.web import webapp
        prefix = app.config.get('PSDASH_URL_PREFIX')
        if prefix:
            prefix = '/' + prefix.strip('/')
        webapp.url_prefix = prefix
        app.register_blueprint(webapp)

        return app
Example #16
0
# Blueprints
from .tf2.views import tf2 as tf2_blueprint
from .users.views import users as users_blueprint
from .mods.views import mods as mods_blueprint

# Admin
from .users.models import User
from .mods.models import ModAuthor
from .admin.views import admin

admin.init_app(app)

# TF2 Schema
from .tf2.models import TF2Item, TF2EquipRegion, TF2BodyGroup

app.register_blueprint(users_blueprint)
app.register_blueprint(mods_blueprint)
app.register_blueprint(tf2_blueprint)

# Assets
from assets import assets

# Jinja2 Filters
from filters import format_thousands, pluralize, datetime_to_datestring
app.add_template_filter(format_thousands)
app.add_template_filter(pluralize)
app.add_template_filter(datetime_to_datestring)

# Load current app version into globals
from functions import current_version
app.config['VERSION'] = current_version()
Example #17
0
File: manage.py Project: qxbug/zsky

def make_cache_key(*args, **kwargs):
    path = request.path
    args = str(hash(frozenset(request.args.items())))
    return (path + args).encode('utf-8')

def filelist_filter(info_hash):
    try:
        return json.loads(Search_Filelist.query.filter_by(info_hash=info_hash).first().file_list)
    except:
        return [{
       'path':Search_Hash.query.filter_by(info_hash=info_hash).first().name, 
       'length':Search_Hash.query.filter_by(info_hash=info_hash).first().length
       }]
app.add_template_filter(filelist_filter,'filelist')


def todate_filter(s):
    return datetime.datetime.fromtimestamp(int(s)).strftime('%Y-%m-%d')
app.add_template_filter(todate_filter,'todate')


def tothunder_filter(magnet):
    return base64.b64encode('AA'+magnet+'ZZ')
app.add_template_filter(tothunder_filter,'tothunder')

def sphinx_conn():
    conn = pymysql.connect(host=DB_HOST, port=DB_PORT_SPHINX, user=DB_USER, password=DB_PASS, db=DB_NAME_SPHINX,
                           charset=DB_CHARSET, cursorclass=pymysql.cursors.DictCursor)
    curr = conn.cursor()
Example #18
0
#!/usr/bin/env python

import json

import argparse
from flask import Flask, make_response, render_template

import app_config
from render_utils import make_context, smarty_filter, urlencode_filter
import static

from gentrification import make_ca_context

app = Flask(__name__)

app.add_template_filter(smarty_filter, name='smarty')
app.add_template_filter(urlencode_filter, name='urlencode')

# Filters
def format_currency(value):
    value = int(value)
    return "${:,}".format(value)

def format_comma(value):
    value = int(value)
    return "{:,}".format(value)

app.jinja_env.filters['format_currency'] = format_currency
app.jinja_env.filters['format_comma'] = format_comma

# Example application views
# -*- coding: utf-8 -*-
__author__ = 'venking'

from flask import Flask
from web import loginctrl
from module.util import fromtimestamp

app = Flask(__name__)
app.register_blueprint(loginctrl,url_prefix='/login')

app.add_template_filter(fromtimestamp)
app.secret_key = 'zoupan19940907'

# @app.route('/')
# def index():
#     return 'Index Page!'
#
#
# @app.route('/hello')
# def hello_world():
#     return 'Hello World!'
#
#
# @app.route('/user/<username>')
# def show_user_profile(username):
#     # show the user profile for that user
#     flash('你好,%s'%(username))
#     return 'User %s' % username
#
#
# @app.route('/post/<int:post_id>')
Example #20
0
app.add_url_rule('/atlases', 'get atlases', get_atlases)
app.add_url_rule('/atlas', 'post atlas', post_atlas, methods=['POST'])
app.add_url_rule('/atlas-hints/<id>', 'post atlas hints', post_atlas_hints, methods=['GET', 'POST'])
app.add_url_rule('/atlas/<id>', 'get atlas', get_atlas)
app.add_url_rule('/map/<id>', 'get map', get_map) 
app.add_url_rule('/maps', 'get maps', get_maps)
app.add_url_rule('/atlases-list', 'get atlases list', get_atlases_list)
app.add_url_rule('/maps-list', 'get maps list', get_maps_list)
app.add_url_rule('/check-map-status/<id>', 'get map status', check_map_status, methods=['GET']) 
app.add_url_rule('/tile/<path:path>', 'tile', tile)

app.add_url_rule('/tile/map/<id>/<path:path>', 'tilemap', tile_by_id)
app.add_url_rule('/tile/atlas/<id>/<path:path>', 'tileatlas', tile_by_id)
 
app.add_url_rule('/map-sandwich', 'map-sandwich', map_sandwich)
app.add_url_rule('/map-sandwich/map/<id>', 'map-sandwich-map', map_sandwich)
app.add_url_rule('/map-sandwich/atlas/<id>', 'map-sandwich-atlas', map_sandwich) 

app.add_url_rule('/faq', 'faq', faq) 
app.add_url_rule('/faq-public', 'faq-public', faq_public)
app.add_url_rule('/docs', 'docs', docs)

app.error_handler_spec[None][404] = page_not_found

app.add_template_filter(sumiter)
app.add_template_filter(datetimeformat)

if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=8080)
Example #21
0
import os

from boto.s3.key import Key
from boto.s3.connection import S3Connection
from flask import Flask, request, render_template
from pbkdf2 import crypt

import forms
import filters
import models
import settings


app = Flask(__name__)
app.config.update(SECRET_KEY=settings.FLASK_SECRET_KEY)
app.add_template_filter(filters.nl2br)


@app.route('/', methods=['GET', 'POST'])
def create_page():
    """ Main view to present the user with a form to create a signup page. """
    form = forms.PageForm(request.form)
    error = None

    if request.method == 'POST' and form.validate():

        # if password incorrect or not entered, show an error
        if not valid_password(form.password.data):
            error = "Must enter correct password."
            return render_template('main.html', form=form, error=error)
Example #22
0
def create_app(config=None):
    """ config should be a python file """
    from pathlib import Path

    from flask import (Flask,
            current_app,
            g,
            session,
            url_for,
            render_template)

    from flask_sqlalchemy import SQLAlchemy
    from flask_security import (Security, SQLAlchemyUserDatastore)

    from flask_wtf.csrf import CsrfProtect

    from flask_assets import (Environment, Bundle)

    from .app_setup import (init_db, setup_dirs)
    from .core import (db, load_blueprints, setup_logger)
    from .lib.template_filters import (
        fmt_datetime,
        none_as_str,
        next_page_url,
        prev_page_url,
        get_page_url,
        get_images)

    from .models.user import (User, Role, user_datastore)

    from .Admin import (index, series, images, texts, contact)
    from .Public import (index, contact, texts)
    from .Security import user

    app = Flask(__name__.split('.')[0], instance_relative_config=True)

    app.config.from_object('config')
    app.config.from_pyfile('config.py')

    if config is not None:
        app.config.from_pyfile(config)
        setup_logger(app)
        app.logger.info('Started with config from: {}'.format(config))
    else:
        setup_logger(app)
        app.logger.info('Started App')

    # Flask.sqlalchemy
    db.init_app(app)

    load_blueprints(app)

    # make sure db tables and required directories exist
    before_first_request_funcs = [setup_dirs(app),
                                  init_db(app)]

    #Security
    csrf = CsrfProtect()
    csrf.init_app(app)
    security = Security()
    security.init_app(app, user_datastore, register_blueprint=False)

    # Assets
    assets = Environment(app=app)
    assets.from_yaml('assets.yml')

    # template filters
    app.add_template_filter(fmt_datetime)
    app.add_template_filter(none_as_str)
    app.add_template_filter(next_page_url)
    app.add_template_filter(prev_page_url)
    app.add_template_filter(get_page_url)
    app.add_template_filter(get_images)

    return app
Example #23
0
def create_app():
    from config import configs

    application = Flask(__name__)

    application.config.from_object(configs[os.environ["NOTIFY_ENVIRONMENT"]])

    init_app(application)
    statsd_client.init_app(application)
    logging.init_app(application, statsd_client)
    init_csrf(application)
    request_id.init_app(application)

    service_api_client.init_app(application)
    user_api_client.init_app(application)
    api_key_api_client.init_app(application)
    job_api_client.init_app(application)
    notification_api_client.init_app(application)
    status_api_client.init_app(application)
    invite_api_client.init_app(application)
    template_statistics_client.init_app(application)
    events_api_client.init_app(application)
    provider_client.init_app(application)
    organisations_client.init_app(application)

    login_manager.init_app(application)
    login_manager.login_view = "main.sign_in"
    login_manager.login_message_category = "default"
    login_manager.session_protection = None

    from app.main import main as main_blueprint

    application.register_blueprint(main_blueprint)

    from .status import status as status_blueprint

    application.register_blueprint(status_blueprint)

    proxy_fix.init_app(application)

    application.session_interface = ItsdangerousSessionInterface()

    application.add_template_filter(format_datetime)
    application.add_template_filter(format_datetime_24h)
    application.add_template_filter(format_datetime_normal)
    application.add_template_filter(format_datetime_short)
    application.add_template_filter(format_time)
    application.add_template_filter(syntax_highlight_json)
    application.add_template_filter(valid_phone_number)
    application.add_template_filter(linkable_name)
    application.add_template_filter(format_date)
    application.add_template_filter(format_date_normal)
    application.add_template_filter(format_date_short)
    application.add_template_filter(format_datetime_relative)
    application.add_template_filter(format_delta)
    application.add_template_filter(format_notification_status)
    application.add_template_filter(format_notification_status_as_time)
    application.add_template_filter(format_notification_status_as_field_status)
    application.add_template_filter(format_notification_status_as_url)

    application.after_request(useful_headers_after_request)
    application.after_request(save_service_after_request)
    application.before_request(load_service_before_request)

    @application.context_processor
    def _attach_current_service():
        return {"current_service": current_service}

    register_errorhandlers(application)

    setup_event_handlers()

    return application
Example #24
0
@app.route('/index')
def index():
    """docstring for index"""
    data = {
        'name': 'ai',
        'age': 18,
        'my_dic': {'city': 'Beijing'},
        'my_list': [1, 2, 3, 4, 5],
        'my_int': 0,
    }
    # return render_template('index.html', name='ai', age=18)
    # data前面的**表示按键-值对解析字典
    return render_template('index.html', **data)


# 自定义过滤器方法一
def list_split2(li):
    """自定义过滤器方法一 list_split2"""
    return li[::2]


# 注册过滤器
app.add_template_filter(list_split2, 'lis2')


# 自定义过滤器方法二
@app.template_filter('lis3')
def list_split3(li):
    """自定义过滤器方法一 list_split2"""
    return li[::3]
def create_app(config={}):
    app = Flask(__name__, instance_relative_config=True)
    app.config.update(DEFAULT_CONFIG)
    app.config.from_pyfile('settings.py', silent=True)
    app.config.update(config)

    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        return getattr(g, 'language', 'en')

    assets_env.init_app(app)
    db.init_app(app)

    app.register_blueprint(admin)
    app.register_blueprint(auth)
    app.register_blueprint(meetings)

    app.add_template_filter(activity_map)
    app.add_template_filter(countries)
    app.add_template_filter(country_in)
    app.add_template_filter(region_in)
    app.add_template_filter(crop)
    app.add_template_filter(nl2br)
    app.add_template_filter(convert_to_dict, name='dict')
    app.add_template_filter(no_image_cache)
    app.add_template_filter(pluralize)
    app.add_template_filter(slugify)
    app.add_template_filter(sort_by_tuple_element)
    app.add_template_filter(clean_html)
    app.add_template_global(active)
    app.add_template_global(date_processor)
    app.add_template_global(inject_static_file)
    app.add_template_global(inject_badge_context)
    app.add_template_global(has_perm)
    app.add_template_global(Logo, name='get_logo')

    @app.context_processor
    def inject_context():
        return {
            'CustomField': {
                'TEXT': CustomField.TEXT,
                'IMAGE': CustomField.IMAGE,
                'EMAIL': CustomField.EMAIL,
                'CHECKBOX': CustomField.CHECKBOX,
                'SELECT': CustomField.SELECT,
                'COUNTRY': CustomField.COUNTRY,
                'LANGUAGE': CustomField.LANGUAGE,
                'CATEGORY': CustomField.CATEGORY,
                'EVENT': CustomField.EVENT,
            },
            'Participant': {
                'PARTICIPANT': Participant.PARTICIPANT,
                'MEDIA': Participant.MEDIA,
                'DEFAULT': Participant.DEFAULT,
                'DEFAULT_MEDIA': Participant.DEFAULT_MEDIA,
            },
        }

    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'
    login_manager.login_message_category = 'warning'

    mail.init_app(app)
    redis_store.init_app(app, strict=True)

    if app.config.get('SENTRY_DSN'):
        sentry.init_app(app)

    _configure_uploads(app)
    _configure_logging(app)

    app.config['REPRESENTING_TEMPLATES'] = (
        path('meetings/participant/representing'))

    _translations = app.config['TRANSLATIONS']
    if _DEFAULT_LANG not in _translations:
        _translations = [_DEFAULT_LANG] + _translations
    app.config['TRANSLATIONS'] = _translations

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(user_id)

    @app.route('/')
    def index():
        return redirect(url_for('meetings.home'))

    @app.errorhandler(413)
    def file_too_large(error):
        mb = 1024 * 1024
        max_size = app.config.get('UPLOAD_SIZE', mb) / mb
        return render_template('_file_too_large.html',
                               max_size=max_size,
                               url=request.url), 413

    return app
Example #26
0
app = Flask(__name__)
app.debug = app_config.DEBUG

try:
    file_handler = logging.FileHandler('%s/public_app.log' % app_config.SERVER_LOG_PATH)
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)
except IOError:
    pass

app.logger.setLevel(logging.INFO)

app.register_blueprint(static.static, url_prefix='/%s' % app_config.PROJECT_SLUG)

app.add_template_filter(smarty_filter, name='smarty')
app.add_template_filter(urlencode_filter, name='urlencode')
app.add_template_filter(format_commas_filter, name='format_commas')

# Example of rendering index.html with public_app 
@app.route('/%s/' % app_config.PROJECT_SLUG, methods=['GET'])
def index():
    """
    Example view rendering a simple page.
    """
    context = make_context(asset_depth=1)

    context['users'] = SITE_USERS

    return make_response(render_template('admin/index.html', **context))
Example #27
0
from mongokit import Connection
import steam

from models import Profile, Job, Match, User
from filters import unix_strftime, prettyprint
app = Flask(__name__)

app.config.from_pyfile("settings.cfg")
connection = Connection(app.config['MONGODB_HOST'],
                        app.config['MONGODB_PORT'])

cache = Cache(app)
oid = OpenID(app)

connection.register([Profile, Job, Match, User])
app.add_template_filter(unix_strftime)
app.add_template_filter(prettyprint)

# Setup steamodd
steam.api.key.set(app.config['STEAM_API_KEY'])
steam.api.socket_timeout.set(10)

# Helpers
@cache.cached(timeout=60*60, key_prefix="league_passes")
def get_league_passes():
    try:
        return [x for x in steam.items.schema(570, "en_US") if x.type == "League Pass"]
    except steam.api.APIError:
        return []

App Template for static publishing.
"""

import app_config
import json
import oauth
import static

from flask import Flask, make_response, render_template
from render_utils import make_context, smarty_filter, urlencode_filter
from werkzeug.debug import DebuggedApplication

app = Flask(__name__)
app.debug = app_config.DEBUG

app.add_template_filter(smarty_filter, name="smarty")
app.add_template_filter(urlencode_filter, name="urlencode")


@app.route("/")
@oauth.oauth_required
def index():
    """
    Example view demonstrating rendering a simple HTML page.
    """
    context = make_context()

    with open("data/featured.json") as f:
        context["featured"] = json.load(f)

    return make_response(render_template("index.html", **context))
Example #29
0
# Setup steamodd
steam.api.key.set(app.config['STEAM_API_KEY'])
steam.api.socket_timeout.set(5)

# Setup debugtoolbar if we're in debug mode.
if app.debug:
    from flask.ext.debugtoolbar import DebugToolbarExtension
    toolbar = DebugToolbarExtension(app)


# Set up jinja2 filters.
from app.filters import escape_every_character,\
    timestamp_to_datestring,\
    datetime_to_datestring,\
    seconds_to_time
app.add_template_filter(escape_every_character)
app.add_template_filter(timestamp_to_datestring)
app.add_template_filter(datetime_to_datestring)
app.add_template_filter(seconds_to_time)


# Load current app version into globals
from helpers import current_version
app.config['VERSION'] = current_version()

# Load views
import views

# Load blueprints
from app.users.views import mod as users_module
app.register_blueprint(users_module)
Example #30
0
from kagami.config import Config
from kagami.models import KagamiStatus
from kagami.i18n import i18n


def get_api(access_token: str, access_secret: str):
    tw_auth = tweepy.OAuthHandler(current_app.config['CK'], current_app.config['CS'])
    tw_auth.set_access_token(access_token, access_secret)
    return tweepy.API(tw_auth)


app = Flask(__name__)
app.config.from_object(Config)
app.config['STRINGS'] = i18n()
import kagami.handler
import kagami.auth
import kagami.status
import kagami.user
import kagami.user_config
import kagami.direct_message
import kagami.cookie

app.add_template_filter(nl2br)
app.jinja_env.globals.update(handler=kagami.handler)
app.jinja_env.globals.update(int=int, str=str)
app.jinja_env.globals.update(session=session)
app.jinja_env.globals.update(KagamiStatus=KagamiStatus)
Bootstrap(app)
if app.config['ENABLE_HTTPS']:
    SSLify(app)