def test_theme_include_static(self): app = Flask(__name__) app.config['THEME_PATHS'] = [join(TESTS, 'morethemes')] setup_themes(app, app_identifier='testing') with app.test_request_context('/'): data = render_template('static_parent.html').strip() url = static_file_url('plain', 'style.css') assert data == 'Application, Plain, %s' % url
def test_template_exists(self): app = Flask(__name__) app.config['THEME_PATHS'] = [join(TESTS, 'morethemes')] setup_themes(app, app_identifier='testing') with app.test_request_context('/'): assert template_exists('hello.html') assert template_exists('_themes/cool/hello.html') assert not template_exists('_themes/plain/hello.html')
def test_theme_static(self): app = Flask(__name__) app.config['THEME_PATHS'] = [join(TESTS, 'morethemes')] setup_themes(app, app_identifier='testing') with app.test_request_context('/'): coolurl = static_file_url('cool', 'style.css') cooldata = render_theme_template('cool', 'static.html').strip() assert cooldata == 'Cool Blue v2, %s' % coolurl
def test_render_theme_template(self): app = Flask(__name__) app.config['THEME_PATHS'] = [join(TESTS, 'morethemes')] setup_themes(app, app_identifier='testing') with app.test_request_context('/'): coolsrc = render_theme_template('cool', 'hello.html').strip() plainsrc = render_theme_template('plain', 'hello.html').strip() assert coolsrc == 'Hello from Cool Blue v2.' assert plainsrc == 'Hello from the application'
def test_static_file_url(self): app = Flask(__name__) app.config['THEME_PATHS'] = [join(TESTS, 'morethemes')] setup_themes(app, app_identifier='testing') with app.test_request_context('/'): url = static_file_url('cool', 'style.css') genurl = url_for('_themes.static', themeid='cool', filename='style.css') assert url == genurl
def test_active_theme(self): app = Flask(__name__) app.config['THEME_PATHS'] = [join(TESTS, 'morethemes')] setup_themes(app, app_identifier='testing') with app.test_request_context('/'): appdata = render_template('active.html').strip() cooldata = render_theme_template('cool', 'active.html').strip() plaindata = render_theme_template('plain', 'active.html').strip() assert appdata == 'Application, Active theme: none' assert cooldata == 'Cool Blue v2, Active theme: cool' assert plaindata == 'Application, Active theme: plain'
def test_setup_themes(self): app = Flask(__name__) app.config['THEME_PATHS'] = [join(TESTS, 'morethemes')] setup_themes(app, app_identifier='testing') assert hasattr(app, 'theme_manager') if USING_BLUEPRINTS: assert '_themes' in app.blueprints else: assert '_themes' in app.modules assert 'theme' in app.jinja_env.globals assert 'theme_static' in app.jinja_env.globals
def test_theme_static_outside(self): app = Flask(__name__) app.config['THEME_PATHS'] = [join(TESTS, 'morethemes')] setup_themes(app, app_identifier='testing') with app.test_request_context('/'): try: render_template('static.html') except RuntimeError: pass else: raise AssertionError("Rendering static.html should have " "caused a RuntimeError")
def configure_extensions(app): mail.init_app(app) db.init_app(app) oid.init_app(app) cache.init_app(app) setup_themes(app) # more complicated setups configure_identity(app) configure_i18n(app)
def test_loader(self): app = Flask(__name__) app.config['THEME_PATHS'] = [join(TESTS, 'morethemes')] setup_themes(app, app_identifier='testing') with app.test_request_context('/'): if USING_BLUEPRINTS: src = themes_blueprint.jinja_loader.get_source( app.jinja_env, '_themes/cool/hello.html' ) else: src = themes_mod.jinja_loader.get_source( app.jinja_env, 'cool/hello.html' ) assert src[0].strip() == 'Hello from Cool Blue v2.'
def __init(): """Dummy unique init method. """ # get secret key. _secret_key = c.app.secret_key if hasattr(c, 'app') is True else None # get identifier _identifier = c.app.identifier if hasattr(c, 'app') is True else None # ... global app if app is None\ and _secret_key is not None\ and _identifier is not None: # get/set app app = Flask(__name__) app.secret_key = _secret_key # set themes path - currently hard coded for `easy to use` reason app.config['THEME_PATHS'] = ['themes'] # init themes setup_themes(app, app_identifier=_identifier)
def test_get_helpers(self): app = Flask(__name__) app.config['THEME_PATHS'] = [join(TESTS, 'morethemes')] setup_themes(app, app_identifier='testing') with app.test_request_context('/'): cool = app.theme_manager.themes['cool'] plain = app.theme_manager.themes['plain'] assert get_theme('cool') is cool assert get_theme('plain') is plain tl = get_themes_list() assert tl[0] is cool assert tl[1] is plain try: get_theme('notthis') except KeyError: pass else: raise AssertionError("Getting a nonexistent theme should " "raised KeyError")
# App Info __VERSION__ = '0.2' __AUTHOR__ = 'Faris Chebib' from flask import Flask from flaskext.themes import setup_themes #import synapse.views from synapse.views.admin import admin from synapse.views.frontend import frontend app = Flask(__name__) setup_themes(app) app.register_module(admin, url_prefix="") app.register_module(frontend, url_prefix="") from synapse.settings import SECRET_KEY, UPLOAD_FOLDER from synapse.settings import RECAPTCHA_PUBLIC_KEY, RECAPTCHA_PRIVATE_KEY from werkzeug import SharedDataMiddleware app.secret_key = SECRET_KEY app.add_url_rule('/uploads/<filename>', 'uploaded_file', build_only=True) app.wsgi_app = SharedDataMiddleware(app.wsgi_app, { '/uploads': UPLOAD_FOLDER, }) app.config.update( RECAPTCHA_PUBLIC_KEY = RECAPTCHA_PUBLIC_KEY, RECAPTCHA_PRIVATE_KEY = RECAPTCHA_PRIVATE_KEY ) from flaskext.babel import Babel
def configure_extensions(app): # configure extensions db.init_app(app) mail.init_app(app) cache.init_app(app) setup_themes(app)
def configure_extensions(app): #SQLAlchemy 装载 这个app的config并且初始数据库 db.init_app(app) setup_themes(app)
from datetime import datetime, timedelta import os import re from flask import abort, Flask, make_response, Markup, render_template from flaskext.themes import render_theme_template, setup_themes from filetree import FileTree import pytz app = Flask(__name__) app.config.from_envvar("HOURLYIMAGE_SETTINGS") setup_themes(app, app_identifier="hourlyimage") @app.route("/") def index(): """ Display available years and current day's images. """ ft = FileTree(app.config["TIMEZONE"], app.config["OFFSET_HOURS"]) path = app.config["IMAGE_LOCATION_DIR"] tree = ft.generate_tree(path) utc_time = pytz.utc.localize(datetime.utcnow()) tz_time = utc_time.astimezone(app.config["TIMEZONE"]) - \ timedelta(hours=app.config["OFFSET_HOURS"]) year = str(tz_time.year) month = "0%s" % tz_time.month if tz_time.month < 10 else str(tz_time.month) day = "0%s" % tz_time.day if tz_time.day < 10 else str(tz_time.day) current_day_images = None
elif limit == 86400: return 'one day ago' elif 86400 < limit < 259200: return '%d days ago' % (limit//86400) else: struct_t = time.localtime(t) return 'at %s' % time.strftime('%a %b %d %H:%M:%S', struct_t) Markdown(app) gravatar = Gravatar(app, size=100, rating='g', default='retro', force_default=False, force_lower=False) db = SQLAlchemy(app) from elpis import models from elpis.frontend.view import frontend app.register_module(frontend) from elpis.admin.view import login_required, admin as admin_view app.register_module(admin_view, url_prefix='/admin') admin_mod = Admin(app, models, db.session, theme='auth', view_decorator=login_required, exclude_pks=True) themes.setup_themes(app) app.register_module(admin_mod, url_prefix='/admin')
def create_app_ext(flask_config_file=None, flask_config_dict=None, moin_config_class=None, warn_default=True, **kwargs ): """ Factory for moin wsgi apps :param flask_config_file: a flask config file name (may have a MOINCFG class), if not given, a config pointed to by MOINCFG env var will be loaded (if possible). :param flask_config_dict: a dict used to update flask config (applied after flask_config_file was loaded [if given]) :param moin_config_class: if you give this, it'll be instantiated as app.cfg, otherwise it'll use MOINCFG from flask config. If that also is not there, it'll use the DefaultConfig built into MoinMoin. :param warn_default: emit a warning if moin falls back to its builtin default config (maybe user forgot to specify MOINCFG?) :param kwargs: if you give additional keyword args, the keys/values will get patched into the moin configuration class (before its instance is created) """ clock = Clock() clock.start('create_app total') app = Flask('MoinMoin') clock.start('create_app load config') if flask_config_file: app.config.from_pyfile(flask_config_file) else: if not app.config.from_envvar('MOINCFG', silent=True): # no MOINCFG env variable set, try stuff in cwd: from os import path flask_config_file = path.abspath('wikiconfig_local.py') if not path.exists(flask_config_file): flask_config_file = path.abspath('wikiconfig.py') if not path.exists(flask_config_file): flask_config_file = None if flask_config_file: app.config.from_pyfile(flask_config_file) if flask_config_dict: app.config.update(flask_config_dict) Config = moin_config_class if not Config: Config = app.config.get('MOINCFG') if not Config: if warn_default: logging.warning("using builtin default configuration") from MoinMoin.config.default import DefaultConfig as Config for key, value in kwargs.iteritems(): setattr(Config, key, value) if Config.secrets is None: # reuse the secret configured for flask (which is required for sessions) Config.secrets = app.config.get('SECRET_KEY') app.cfg = Config() clock.stop('create_app load config') clock.start('create_app register') # register converters from werkzeug.routing import PathConverter app.url_map.converters['itemname'] = PathConverter # register modules, before/after request functions from MoinMoin.apps.frontend import frontend frontend.before_request(before_wiki) frontend.teardown_request(teardown_wiki) app.register_blueprint(frontend) from MoinMoin.apps.admin import admin admin.before_request(before_wiki) admin.teardown_request(teardown_wiki) app.register_blueprint(admin, url_prefix='/+admin') from MoinMoin.apps.feed import feed feed.before_request(before_wiki) feed.teardown_request(teardown_wiki) app.register_blueprint(feed, url_prefix='/+feed') from MoinMoin.apps.misc import misc misc.before_request(before_wiki) misc.teardown_request(teardown_wiki) app.register_blueprint(misc, url_prefix='/+misc') from MoinMoin.apps.serve import serve app.register_blueprint(serve, url_prefix='/+serve') clock.stop('create_app register') clock.start('create_app flask-cache') cache = Cache() cache.init_app(app) app.cache = cache clock.stop('create_app flask-cache') # init storage clock.start('create_app init backends') init_backends(app) clock.stop('create_app init backends') clock.start('create_app flask-babel') i18n_init(app) clock.stop('create_app flask-babel') # configure templates clock.start('create_app flask-themes') setup_themes(app) if app.cfg.template_dirs: app.jinja_env.loader = ChoiceLoader([ FileSystemLoader(app.cfg.template_dirs), app.jinja_env.loader, ]) app.register_error_handler(403, themed_error) clock.stop('create_app flask-themes') clock.stop('create_app total') del clock return app
# some default settings, that can be overwritten AUTHOR='anonymous' THEME='default' PER_PAGE=5 POSTSLUG='blog/%title%' PAGESLUG='%title%' DATETIME='%d. %B %Y' # setup all the modules we need gen = Flask(__name__) gen.config.from_object(__name__) gen.config.from_pyfile('blogen.cfg') setup_themes(gen, app_identifier='blogen', theme_url_prefix='/theme') cli = Manager(gen) static = Freezer(gen) # Here is some code I had to include to make things work # unfortunately subclassing flask-flatpages was not enough, # so I copied and adjusted it. the original source is: # https://github.com/SimonSapin/Flask-FlatPages def pygmented_markdown(text): try: import pygments except ImportError: extensions = [] else:
from datetime import datetime, timedelta import os import re from flask import abort, Flask, make_response, Markup, render_template from flaskext.themes import render_theme_template, setup_themes from filetree import FileTree import pytz app = Flask(__name__) app.config.from_envvar("HOURLYIMAGE_SETTINGS") setup_themes(app, app_identifier="hourlyimage") @app.route("/") def index(): """ Display available years and current day's images. """ ft = FileTree(app.config["TIMEZONE"], app.config["OFFSET_HOURS"]) path = app.config["IMAGE_LOCATION_DIR"] tree = ft.generate_tree(path) utc_time = pytz.utc.localize(datetime.utcnow()) tz_time = utc_time.astimezone(app.config["TIMEZONE"]) - \ timedelta(hours=app.config["OFFSET_HOURS"]) year = str(tz_time.year) month = "0%s" % tz_time.month if tz_time.month < 10 else str(tz_time.month) day = "0%s" % tz_time.day if tz_time.day < 10 else str(tz_time.day)
from flask import Flask, render_template from flaskext.debugtoolbar import DebugToolbarExtension from flaskext.silk import Silk from flaskext.themes import setup_themes, packaged_themes_loader ###################### App Start ####################### app = Flask(__name__) app.config.from_object(setting) # debug tool toolbar = DebugToolbarExtension(app) # themes # packaged_themes_loader(app) setup_themes(app, app_identifier="flask-ims") # slik silk = Silk(app) # add modules from view import test from view import account from view import admin from view import general from view import todo from view import photo from view import wiki from view import feed app.register_module(test.mod)
from flask import (Flask, url_for, redirect, session, Markup, abort) from flaskext.themes import (setup_themes, render_theme_template, get_themes_list) from operator import attrgetter # default settings DEFAULT_THEME = 'calmblue' SECRET_KEY = 'not really secret' # application app = Flask(__name__) app.config.from_object(__name__) setup_themes(app, app_identifier='themesandbox') # data class Post(object): def __init__(self, data): self.slug = data['slug'] self.body = data['body'] self.title = data['title'] self.created = data['created'] @property def content(self): return Markup('\n\n'.join( '<p>%s</p>' % line for line in self.body.splitlines()
], else_ = cls.last_name) def instance_loader(app): base_app_path = os.path.split(app.root_path)[0] themes_dir = os.path.join(base_app_path, 'themes') if os.path.isdir(themes_dir): return load_themes_from(themes_dir) else: return () user_datastore = SQLAlchemyUserDatastore(db, User, Role) security = Security(app, user_datastore) init_extensions(app) configurator = Configurator(app) setup_themes(app, app_identifier="hootenflaten", loaders=[instance_loader, packaged_themes_loader, theme_paths_loader]) import base.view_helpers import base.views import base.models from time import mktime app.jinja_env.filters['mktime'] = mktime
def create_app_ext(flask_config_file=None, flask_config_dict=None, moin_config_class=None, warn_default=True, **kwargs): """ Factory for moin wsgi apps @param flask_config_file: a flask config file name (may have a MOINCFG class), if not given, a config pointed to by MOINCFG env var will be loaded (if possible). @param flask_config_dict: a dict used to update flask config (applied after flask_config_file was loaded [if given]) @param moin_config_class: if you give this, it'll be instantiated as app.cfg, otherwise it'll use MOINCFG from flask config. If that also is not there, it'll use the DefaultConfig built into MoinMoin. @oaram warn_default: emit a warning if moin falls back to its builtin default config (maybe user forgot to specify MOINCFG?) @param **kwargs: if you give additional key/values here, they'll get patched into the moin configuration class (before it instance is created) """ clock = Clock() clock.start('create_app total') app = Flask('MoinMoin') clock.start('create_app load config') if flask_config_file: app.config.from_pyfile(flask_config_file) else: app.config.from_envvar('MOINCFG', silent=True) if flask_config_dict: app.config.update(flask_config_dict) Config = moin_config_class if not Config: Config = app.config.get('MOINCFG') if not Config: if warn_default: logging.warning("using builtin default configuration") from MoinMoin.config.default import DefaultConfig as Config for key, value in kwargs.iteritems(): setattr(Config, key, value) if Config.secrets is None: # reuse the secret configured for flask (which is required for sessions) Config.secrets = app.config.get('SECRET_KEY') app.cfg = Config() clock.stop('create_app load config') clock.start('create_app register') # register converters from werkzeug.routing import PathConverter app.url_map.converters['itemname'] = PathConverter # register modules, before/after request functions from MoinMoin.apps.frontend import frontend frontend.before_request(before_wiki) frontend.after_request(after_wiki) app.register_module(frontend) from MoinMoin.apps.admin import admin admin.before_request(before_wiki) admin.after_request(after_wiki) app.register_module(admin, url_prefix='/+admin') from MoinMoin.apps.feed import feed feed.before_request(before_wiki) feed.after_request(after_wiki) app.register_module(feed, url_prefix='/+feed') from MoinMoin.apps.misc import misc misc.before_request(before_wiki) misc.after_request(after_wiki) app.register_module(misc, url_prefix='/+misc') from MoinMoin.apps.serve import serve app.register_module(serve, url_prefix='/+serve') clock.stop('create_app register') clock.start('create_app flask-cache') cache = Cache() cache.init_app(app) app.cache = cache clock.stop('create_app flask-cache') # init storage clock.start('create_app init backends') app.unprotected_storage, app.storage = init_backends(app) clock.stop('create_app init backends') clock.start('create_app index rebuild') if app.cfg.index_rebuild: app.unprotected_storage.index_rebuild() # XXX run this from a script clock.stop('create_app index rebuild') clock.start('create_app load/save xml') import_export_xml(app) clock.stop('create_app load/save xml') clock.start('create_app flask-babel') i18n_init(app) clock.stop('create_app flask-babel') # configure templates clock.start('create_app flask-themes') setup_themes(app) if app.cfg.template_dirs: app.jinja_env.loader = ChoiceLoader([ FileSystemLoader(app.cfg.template_dirs), app.jinja_env.loader, ]) app.error_handlers[403] = themed_error clock.stop('create_app flask-themes') clock.stop('create_app total') del clock return app
from werkzeug import cached_property from jinja2 import ChoiceLoader, FileSystemLoader class MeadFlask(Flask): """Enhanced Flask class for smart mead template loading.""" @cached_property def jinja_loader(self): return ChoiceLoader([ FileSystemLoader('core/admin/templates/'), super(MeadFlask, self).jinja_loader ]) app = MeadFlask(__name__) setup_themes(app) # ============= # CONFIGURATION # ============= # Load Mead defaults. app.config.from_object('mead.core.defaults') try: app.config.from_envvar( 'MEAD_SETTINGS') # Change if you have multiple instances. except RuntimeError: pass try: