當前位置: 首頁>>代碼示例>>Python>>正文


Python Flask.add_template_global方法代碼示例

本文整理匯總了Python中flask.Flask.add_template_global方法的典型用法代碼示例。如果您正苦於以下問題:Python Flask.add_template_global方法的具體用法?Python Flask.add_template_global怎麽用?Python Flask.add_template_global使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在flask.Flask的用法示例。


在下文中一共展示了Flask.add_template_global方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: create_app

# 需要導入模塊: from flask import Flask [as 別名]
# 或者: from flask.Flask import add_template_global [as 別名]
def create_app(init=False):
    app = Flask(__name__, static_url_path="/elegon/static", template_folder="templates")
    app.config.from_object("elegon.config")
    app.secret_key = "c534d51a57638e8a8a51c36d4a4128b89f8beb22"

    for ext in (db, openid2):
        ext.init_app(app)

    for bp in blueprints:
        import_name = "%s.ui.%s:bp" % (__package__, bp)
        app.register_blueprint(import_string(import_name))

    for fl in (max, min, paginator_kwargs, enumerate):
        app.add_template_global(fl)

    with app.app_context():
        db.create_all()

    @app.before_request
    def init_global_vars():
        user_dict = json.loads(request.cookies.get(app.config["OPENID2_PROFILE_COOKIE_NAME"], "{}"))
        g.user = user_dict and User.get_or_create(user_dict["username"], user_dict["email"]) or None
        g.start = request.args.get("start", type=int, default=0)
        g.limit = request.args.get("limit", type=int, default=20)

    init_logging()

    if init:
        init_scheduler()
        start_scheduler()
        signal.signal(signal.SIGTERM, stop_scheduler)
        signal.signal(signal.SIGHUP, stop_scheduler)

    return app
開發者ID:tonicbupt,項目名稱:elegon,代碼行數:36,代碼來源:app.py

示例2: create_app

# 需要導入模塊: from flask import Flask [as 別名]
# 或者: from flask.Flask import add_template_global [as 別名]
def create_app():
    app = Flask(__name__, static_url_path='/huhuran/static')
    app.config.from_object('huhuran.config')
    app.config.setdefault('SQLALCHEMY_TRACK_MODIFICATIONS', True)
    app.secret_key = app.config['SECRET_KEY']

    logging.basicConfig(format='%(levelname)s:%(asctime)s:%(message)s',
                        level=logging.INFO)

    for ext in (db, ):
        ext.init_app(app)

    for bp in blueprints:
        import_name = '%s.views.%s:bp' % (__package__, bp)
        app.register_blueprint(import_string(import_name))

    for fl in (max, min):
        app.add_template_global(fl)

    @app.before_request
    def init_global_vars():
        g.user = 'sso' in session and get_user(sso.get('me').data) or None
        g.start = request.args.get('start', type=int, default=0)
        g.limit = request.args.get('limit', type=int, default=20)

    return app
開發者ID:tonicbupt,項目名稱:huhuran,代碼行數:28,代碼來源:app.py

示例3: create_app

# 需要導入模塊: from flask import Flask [as 別名]
# 或者: from flask.Flask import add_template_global [as 別名]
def create_app():
    app = Flask(__name__, static_url_path='/argonath/static')
    app.config.from_object('argonath.config')
    app.secret_key = 'wolegeca'

    logging.basicConfig(format='%(levelname)s:%(asctime)s:%(message)s',
                        level=logging.INFO)

    for ext in (db, openid2):
        ext.init_app(app)

    for bp in blueprints:
        import_name = '%s.views.%s:bp' % (__package__, bp)
        app.register_blueprint(import_string(import_name))

    for fl in (max, min, paginator_kwargs):
        app.add_template_global(fl)

    @app.before_request
    def init_global_vars():
        user_dict = json.loads(request.cookies.get(app.config['OPENID2_PROFILE_COOKIE_NAME'], '{}'))
        g.user = user_dict and User.get_or_create(user_dict['username'], user_dict['email']) or None
        g.start = request.args.get('start', type=int, default=0)
        g.limit = request.args.get('limit', type=int, default=20)

    return app
開發者ID:ninjadq,項目名稱:argonath,代碼行數:28,代碼來源:app.py

示例4: create_app

# 需要導入模塊: from flask import Flask [as 別名]
# 或者: from flask.Flask import add_template_global [as 別名]
def create_app():
    app = Flask(__name__, static_url_path='/neptulon/static')
    app.config.from_object('neptulon.config')
    app.secret_key = app.config['SECRET_KEY']

    logging.basicConfig(format='%(levelname)s:%(asctime)s:%(message)s', level=logging.INFO)

    db.init_app(app)
    mail.init_app(app)
    oauth.init_app(app)

    for bp in blueprints:
        import_name = '%s.views.%s:bp' % (__package__, bp)
        app.register_blueprint(import_string(import_name))

    for fl in (max, min, paginator_kwargs):
        app.add_template_global(fl)

    @app.before_request
    def init_global_vars():
        g.user = None
        if 'id' in session:
            g.user = User.get(session['id'])
        g.redir = request.args.get('redirect', '')
        g.start = request.args.get('start', type=int, default=0)
        g.limit = request.args.get('limit', type=int, default=20)

    return app
開發者ID:CMGS,項目名稱:neptulon,代碼行數:30,代碼來源:app.py

示例5: create_app

# 需要導入模塊: from flask import Flask [as 別名]
# 或者: from flask.Flask import add_template_global [as 別名]
def create_app():
    app = Flask(__name__, static_url_path='/argonath/static')
    app.config.from_object('argonath.config')
    app.config.setdefault('SQLALCHEMY_TRACK_MODIFICATIONS', True)
    app.secret_key = 'wolegeca'

    logging.basicConfig(format='%(levelname)s:%(asctime)s:%(message)s',
                        level=logging.INFO)

    for ext in (db, ):
        ext.init_app(app)

    for bp in blueprints:
        import_name = '%s.views.%s:bp' % (__package__, bp)
        app.register_blueprint(import_string(import_name))

    for fl in (max, min, paginator_kwargs):
        app.add_template_global(fl)

    @app.before_request
    def init_global_vars():
        g.user = 'id' in session and User.get(session['id']) or None
        g.start = request.args.get('start', type=int, default=0)
        g.limit = request.args.get('limit', type=int, default=20)

    return app
開發者ID:CMGS,項目名稱:argonath,代碼行數:28,代碼來源:app.py

示例6: app_factory

# 需要導入模塊: from flask import Flask [as 別名]
# 或者: from flask.Flask import add_template_global [as 別名]
def app_factory(**kwargs):
    app = Flask(__name__)
    app.config.from_object(config_combined)
    db.init_app(app)

    DebugToolbarExtension(app)

    app.add_template_global(string_isinstance, name='string_isinstance')

    login_manager = LoginManager(app)

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

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

    @app.route('/login/', methods=['GET', 'POST'])
    def login():
        form = LoginForm(request.form)
        if form.validate_on_submit():
            if (form.username.data == app.config['ADMIN_USERNAME'] and
                form.password.data == app.config['ADMIN_PASSWORD']):
                user = User()
                login_user(user)
                return redirect(url_for('index'))
            else:
                form.username.errors.append('Invalid Username...')
                form.password.errors.append('...or Password')
        return render_template('login.html', form=form)

    @app.route('/logout/')
    def logout():
        logout_user()
        return redirect(url_for('login'))

    @app.route('/content/')
    @login_required
    def content():
        return render_template('content.html')

    @app.errorhandler(404)
    def err404(e):
        return render_template('404.html'), 404

    @app.errorhandler(500)
    def err500(e):
        return render_template('500.html'), 500

    return app
開發者ID:plumdog,項目名稱:flask_boilerplate,代碼行數:54,代碼來源:__init__.py

示例7: create_app

# 需要導入模塊: from flask import Flask [as 別名]
# 或者: from flask.Flask import add_template_global [as 別名]
def create_app(config_name='development', p_db=db, p_bcrypt=bcrypt, p_login_manager=login_manager):
    new_app = Flask(__name__)
    config_app(config_name, new_app)

    p_db.init_app(new_app)
    p_bcrypt.init_app(new_app)
    p_login_manager.init_app(new_app)
    p_login_manager.login_view = 'register'
    db.init_app(new_app)
    init_models_module(db, p_bcrypt, new_app)

    # Add translator utilities.
    new_app.add_template_global(translator.translate)

    return new_app
開發者ID:bnookala,項目名稱:gig,代碼行數:17,代碼來源:__init__.py

示例8: create_app

# 需要導入模塊: from flask import Flask [as 別名]
# 或者: from flask.Flask import add_template_global [as 別名]
def create_app(config_file=None):
    app = Flask(__name__)
    app = change_jinja_templates(app)
    if config_file:
        app.config.from_pyfile(config_file)
    else:
        app.config.from_envvar("CLA_PUBLIC_CONFIG")

    if app.config.get("SENTRY_DSN"):
        app.sentry = Sentry(app, dsn=app.config.get("SENTRY_DSN"), logging=True, level=logging.ERROR)

    app.babel = Babel(app)
    app.babel.localeselector(get_locale)

    app.cache = Cache(app)

    app.mail = Mail(app)

    for extension in app.config["EXTENSIONS"]:
        extension.init_app(app)

    app.session_interface = CheckerSessionInterface()
    app.json_encoder = CustomJSONEncoder

    register_error_handlers(app)

    app.add_template_global(honeypot.FIELD_NAME, name="honeypot_field_name")

    app.register_blueprint(base)
    app.register_blueprint(geocoder)
    app.register_blueprint(contact)
    app.register_blueprint(scope)
    if not app.config.get("CONTACT_ONLY"):
        app.register_blueprint(checker)

    logging.config.dictConfig(app.config["LOGGING"])
    # quiet markdown module
    logging.getLogger("MARKDOWN").setLevel(logging.WARNING)

    if app.debug:
        from werkzeug.debug import DebuggedApplication

        app.wsgi_app = DebuggedApplication(app.wsgi_app, True)

    return app
開發者ID:ministryofjustice,項目名稱:cla_public,代碼行數:47,代碼來源:app.py

示例9: create_app

# 需要導入模塊: from flask import Flask [as 別名]
# 或者: from flask.Flask import add_template_global [as 別名]
def create_app(config_file=None, config_object=None):
    """
    Application bootstrapper.
    """
    app = Flask(__name__, static_folder='public')
    app.config.from_object('eveauth.settings.BaseConfig')
    app.environment = os.getenv('eveauth_ENV', 'dev')

    if config_file:
        file_ext = os.path.splitext(config_file)[1]
        if file_ext == '.yml':
            with open(config_file) as f:
                config_yaml = yaml.load(f)
                app.config.update(**config_yaml)
        elif file_ext == '.py':
            app.config.from_pyfile(config_file)
        else:
            raise Exception('Unsupported config file format: {}, expecting Yaml or Python'.format(file_ext))

    if config_object:
        app.config.update(**config_object)

    if app.environment != 'test':
        csrf.init_app(app)

    from eveauth.api import api_manager
    api_manager.init_app(app)

    from eveauth.models import db, migrate, ma
    db.init_app(app)
    migrate.init_app(app, db)
    ma.init_app(app)

    from eveauth.controllers import MetaView
    MetaView.register(app)

    from eveauth.services import sso_service
    sso_service.init_app(app)

    app.add_template_global(app.config, 'config')

    return app
開發者ID:orbitroom,項目名稱:EveAuth,代碼行數:44,代碼來源:app.py

示例10: create_app

# 需要導入模塊: from flask import Flask [as 別名]
# 或者: from flask.Flask import add_template_global [as 別名]
def create_app():
    app = Flask('Ainur', static_url_path='/static')
    app.config.from_object('config')
    app.secret_key = app.config['SECRET']

    db.init_app(app)
    db.app = app
    db.create_all()
    rds.init_app(app)

    for bp in blueprints:
        import_name = '%s.%s:bp' % (__package__, bp)
        app.register_blueprint(import_string(import_name))

    for fl in (max, min, paginator_kwargs, login_url):
        app.add_template_global(fl)

    @app.before_request
    def init_global_vars():
        g.page = request.args.get('page', type=int, default=0)
        g.start = request.args.get('start', type=int, default=g.page * 20)
        g.limit = request.args.get('limit', type=int, default=20)

        if request.path == '/user/login_from_openid/' or request.path.startswith('/ajax'):
            return

        if 'uid' not in session:
            abort(401)
        g.user = User.get_by_uid(session['uid'])

    @app.errorhandler(403)
    @app.errorhandler(401)
    def error_handler(e):
        return render_template('errors/%s.html' % e.code), e.code

    return app
開發者ID:tonicbupt,項目名稱:ainur,代碼行數:38,代碼來源:app.py

示例11: create_app

# 需要導入模塊: from flask import Flask [as 別名]
# 或者: from flask.Flask import add_template_global [as 別名]
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    bootstrap.init_app(app)
    moment.init_app(app)
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'
    db.init_app(app)
    from .main import main
    from .auth import auth
    from .manager import manager
    app.register_blueprint(main)
    app.register_blueprint(auth)
    app.register_blueprint(manager)
    configure_uploads(app, photos)
    patch_request_class(app)
    from .models import Message, User, Post, Praise, Comment, Collection
    app.add_template_global(Message, 'Message')
    app.add_template_global(User, 'User')
    app.add_template_global(Post, 'Post')
    app.add_template_global(Comment, 'Comment')
    return app
開發者ID:LiangXunfly,項目名稱:microblog_flask,代碼行數:25,代碼來源:__init__.py

示例12: Category

# 需要導入模塊: from flask import Flask [as 別名]
# 或者: from flask.Flask import add_template_global [as 別名]
    if request.method == 'POST':
        newCategory = Category(
            name=request.form['name'], user_id=login_session['user_id'])
        session.add(newCategory)
        flash('New Category %s Successfully Created' % newCategory.name)
        session.commit()
        return redirect(url_for('showCatalog'))
    else:
        return render_template('newCategory.html')


def get_category(item):
    category = session.query(Category).filter_by(id=item.category_id).one()
    return category

app.add_template_global(get_category, name='get_category')


def is_logged_in():
    return 'username' in login_session

app.add_template_global(is_logged_in, name='is_logged_in')


def get_count(q):
    count_q = q.statement.with_only_columns([func.count()]).order_by(None)
    count = q.session.execute(count_q).scalar()
    return count


# Show a category
開發者ID:ggilley,項目名稱:fullstack-nanodegree-vm,代碼行數:33,代碼來源:application.py

示例13: jsonify

# 需要導入模塊: from flask import Flask [as 別名]
# 或者: from flask.Flask import add_template_global [as 別名]
def jsonify(*args, **kwargs):
    response = flask_jsonify(*args, **kwargs)
    if not response.data.endswith(b'\n'):
        response.data += b'\n'
    return response

# Prevent WSGI from correcting the casing of the Location header
BaseResponse.autocorrect_location_header = False

# Find the correct template folder when running from a different location
tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')

app = Flask(__name__, template_folder=tmpl_dir)
app.debug = bool(os.environ.get('DEBUG'))

app.add_template_global('HTTPBIN_TRACKING' in os.environ, name='tracking_enabled')

app.config['SWAGGER'] = {
    'title': 'httpbin.org',
    'uiversion': 3
}

template = {
  "swagger": "2.0",
  "info": {
    "title": "httpbin.org",
    "description": (
        "A simple HTTP Request & Response Service."
        "<br/> <br/> <b>Run locally: </b> <code>$ docker run -p 80:80 kennethreitz/httpbin</code>"
    ),
    "contact": {
開發者ID:Lucretiel,項目名稱:httpbin,代碼行數:33,代碼來源:core.py

示例14: fix_name

# 需要導入模塊: from flask import Flask [as 別名]
# 或者: from flask.Flask import add_template_global [as 別名]
from flask import Flask, render_template, url_for, jsonify
import json

def fix_name(name):
    return name.replace(" ","_")

data = json.load(open('report.json'))
app = Flask(__name__)
app.add_template_global(fix_name)

@app.route("/")
def report():
    total_demand = data['demand']['Total Demand']
    disaggregation_results = data['disaggregate']
    reportdata = {k:v for k,v in data['demand'].iteritems() if k not in ["Demand Data", "Total Demand"]}
    return render_template("index.html", total_demand=total_demand, demand=reportdata, disaggregation_results=disaggregation_results, zones=data['zones'])

@app.route("/demanddata")
def demanddata():
    return jsonify({'data': [{'date': k,'value': v} for k,v in data['demand']['Demand Data'].iteritems()]})

@app.route("/zonedata/<key>/<zone>")
def zonedata(key, zone):
    """
    key: "Min Daily Avg Demand" from report.demand_report
    zone: zone name like "DOSA"
    """
    key = key.replace("_"," ")
    ret = {}
    for ts, dd in data['demand'][key]['Data'][zone].iteritems():
        ret[ts] = [{'date': k, 'value': v} for k,v in dd.iteritems()]
開發者ID:SoftwareDefinedBuildings,項目名稱:openbas,代碼行數:33,代碼來源:app.py

示例15: static_url

# 需要導入模塊: from flask import Flask [as 別名]
# 或者: from flask.Flask import add_template_global [as 別名]
@app.template_global()
def static_url(**values):
    """Return a static url with an mtime query string for cache busting."""
    filename = values.get('filename', None)
    if not filename:
        return url_for('static', **values)

    file_path = os.path.join(app.static_folder, filename)
    if os.path.exists(file_path):
        values['mtime'] = int(os.stat(file_path).st_mtime)

    return url_for('static', **values)


app.add_template_global(datetime.date.today, 'today')
CACHED_URL_FOR = functools.lru_cache(2048)(flask.url_for)


@app.template_global()
def url_for(endpoint, **values):
    """A wrapper around flask.url_for that uses a cache."""
    _inject_filters(endpoint, values)
    return CACHED_URL_FOR(endpoint, **values)


@app.template_global()
def url_for_current(**kwargs):
    """URL for current page with updated request args."""
    if not kwargs:
        return url_for(request.endpoint, **request.view_args)
開發者ID:adamgibbins,項目名稱:fava,代碼行數:32,代碼來源:application.py


注:本文中的flask.Flask.add_template_global方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。