def config_app(app, db, oid, babel, config): app.config.from_pyfile(config) setup_themes(app, app_identifier="application") db.init_app(app) oid.init_app(app) babel.init_app(app) formatter = logging.Formatter( '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]') file_handler = RotatingFileHandler(app.config['ERROR_LOG'], maxBytes=100000, backupCount=0) file_handler.setLevel(logging.ERROR) file_handler.setFormatter(formatter) app.logger.addHandler(file_handler) @app.before_request def before_request(): g.user = None if 'user' in session: g.user = User.query.filter_by(id=session['user']).first() g.url = request.url @app.after_request def after_request(response): try: db.session.commit() except Exception, e: db.session.rollback() #app.log.error(str(e)) print str(e) abort(500) return response
def config_app(app, db, oid, babel, config): app.config.from_pyfile(config) setup_themes(app, app_identifier="application") db.init_app(app) oid.init_app(app) babel.init_app(app) formatter = logging.Formatter( '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]' ) file_handler = RotatingFileHandler(app.config['ERROR_LOG'], maxBytes=100000, backupCount=0) file_handler.setLevel(logging.ERROR) file_handler.setFormatter(formatter) app.logger.addHandler(file_handler) @app.before_request def before_request(): g.user = None if 'user' in session: g.user = User.query.filter_by(id=session['user']).first() g.url= request.url @app.after_request def after_request(response): try: db.session.commit() except Exception, e: db.session.rollback() #app.log.error(str(e)) print str(e) abort(500) return response
def configExtensions(app): JSCDN(app) setup_themes(app) cache.init_app(app) if app.debug: DebugToolbarExtension(app) DebuggedApplication(app, evalex=True)
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 create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) cache.init_app(app) db.init_app(app) db.app = app login_manager.init_app(app) mail.init_app(app) setup_themes(app) Mobility(app) from .utils.filters import register_filters register_filters(app) from .utils.processors import utility_processor app.context_processor(utility_processor) from .api import api as api_blueprint app.register_blueprint(api_blueprint, url_prefix='/api') from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .account import account as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/account') from .admins import admin admin.init_app(app) @app.route('/favicon.ico') def favicon(): return send_from_directory(app.static_folder, 'favicon.ico', mimetype='image/vnd.microsoft.icon') @app.route('/robots.txt') def robotstxt(): return send_from_directory(app.static_folder, 'robots.txt') # 暂时解决因Gunicorn中引发ERROR 11而无法正常提交的问题 #@app.teardown_request #def teardown_request(response_or_exc): # if app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']: # try: # db.session.commit() # except: # db.session.rollback() # db.session.remove() return app
def configure_extensions(app): mail.init_app(app) db.init_app(app) oid.init_app(app) cache.init_app(app) setup_themes(app, app_identifier='newsmeme') # more complicated setups configure_identity(app) configure_i18n(app)
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 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 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 create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) db.init_app(app) db.app = app if not app.config['TESTING']: configure_custom_settings(app) config[config_name].init_app(app) thumbnail.init_app(app) babel.init_app(app) cache.init_app(app) login_manager.init_app(app) mail.init_app(app) setup_themes(app) Mobility(app) from .utils.filters import register_filters register_filters(app) from .utils.processors import utility_processor app.context_processor(utility_processor) from .api import api as api_blueprint app.register_blueprint(api_blueprint, url_prefix='/api') from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .account import account as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/account') from .admins import admin admin.init_app(app) @app.route('/favicon.ico') def favicon(): return send_from_directory(app.static_folder, 'favicon.ico', mimetype='image/vnd.microsoft.icon') @app.route('/robots.txt') def robotstxt(): return send_from_directory(app.static_folder, 'robots.txt') return app
def create_app(**config): app = Flask(__name__) app.config["HTAUTH_HTPASSWD_PATH"] = Path(__file__, "..", "htpasswd").absolute() app.config["HTAUTH_REALM"] = "inupypi Authentication" app.config["THEME"] = app.config.get("THEME", "inupypi") app.config["VERSION"] = __version__ setup_themes(app) htauth.HTAuth(app) app.config.update(config) app.register_blueprint(admin) app.register_blueprint(error) app.register_blueprint(main) return app
def create_app(**config): app = Flask(__name__) app.config['HTAUTH_HTPASSWD_PATH'] = Path(__file__, '..', 'htpasswd').absolute() app.config['HTAUTH_REALM'] = 'inupypi Authentication' app.config['THEME'] = app.config.get('THEME', 'inupypi') app.config['VERSION'] = __version__ setup_themes(app) htauth.HTAuth(app) app.config.update(config) app.register_blueprint(admin) app.register_blueprint(error) app.register_blueprint(main) return app
def init_for(env): init_app(app, env) init_app(eventapp, env) app.config['tz'] = timezone(eventapp.config['TIMEZONE']) eventframe.models.db.init_app(app) eventframe.models.db.init_app(eventapp) lastuser.init_app(app) lastuser.init_usermanager(UserManager(eventframe.models.db, eventframe.models.User)) assets.register('js_all', js) assets.register('css_all', css) eventassets.register('js_baseframe', baseframe_js) eventassets.register('css_baseframe', baseframe_css) setup_themes(eventapp, app_identifier='eventframe') setup_themes(app, app_identifier='eventframe') # To list themes in the admin views for theme in eventapp.theme_manager.list_themes(): load_theme_assets(eventassets, theme) return DomainDispatcher(app.config['ADMIN_HOSTS'], app, eventapp)
def create_app(config_name): app = Flask(__name__) app.config['APPENV'] = str(get_appconfig()) app.config.from_object(config[config_name]) config[config_name].init_app(app) cache.init_app(app) db.init_app(app) db.app = app login_manager.init_app(app) mail.init_app(app) setup_themes(app) Mobility(app) from .utils.filters import register_filters register_filters(app) from .utils.processors import utility_processor app.context_processor(utility_processor) from .api import api as api_blueprint app.register_blueprint(api_blueprint, url_prefix='/api') from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .account import account as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/account') from .admins import admin admin.init_app(app) # 暂时解决因Gunicorn中引发ERROR 11而无法正常提交的问题 @app.teardown_request def teardown_request(response_or_exc): if app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']: try: db.session.commit() except: db.session.rollback() db.session.remove() return app
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")
def init_for(env): coaster.app.init_app(app, env) coaster.app.init_app(eventapp, env) app.config['tz'] = timezone(eventapp.config['TIMEZONE']) eventframe.models.db.init_app(app) eventframe.models.db.init_app(eventapp) lastuser.init_app(app) lastuser.init_usermanager( UserManager(eventframe.models.db, eventframe.models.User)) assets.register('js_all', js) assets.register('css_all', css) eventassets.register('js_baseframe', baseframe_js) eventassets.register('css_baseframe', baseframe_css) setup_themes(eventapp, app_identifier='eventframe') setup_themes( app, app_identifier='eventframe') # To list themes in the admin views for theme in eventapp.theme_manager.list_themes(): load_theme_assets(eventassets, theme) return DomainDispatcher(app.config['ADMIN_HOSTS'], app, eventapp)
def init_for(env): init_app(app, env) init_app(eventapp, env) app.config['tz'] = timezone(eventapp.config['TIMEZONE']) eventframe.models.db.init_app(app) eventframe.models.db.init_app(eventapp) baseframe.baseframe.init_app(app, requires=['baseframe', 'toastr', 'eventframe']) baseframe.baseframe.init_app(eventapp, requires=[], assetenv=eventassets) eventapp.assets = eventassets # Replace baseframe-provided Environment with ThemeAwareEnvironment lastuser.init_app(app) lastuser.init_usermanager(UserManager(eventframe.models.db, eventframe.models.User)) eventassets.register('js_baseframe', Bundle(baseframe.assets.require('baseframe.js'), filters='uglipyjs', output='js/packed.js')) eventassets.register('css_baseframe', Bundle(baseframe.assets.require('baseframe.css'), filters='cssmin', output='css/packed.css')) setup_themes(eventapp, app_identifier='eventframe') setup_themes(app, app_identifier='eventframe') # To list themes in the admin views for theme in eventapp.theme_manager.list_themes(): load_theme_assets(eventassets, theme) return DomainDispatcher(app.config['ADMIN_HOSTS'], app, eventapp)
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 BaseConverter class ItemNameConverter(BaseConverter): """Like the default :class:`UnicodeConverter`, but it also matches slashes (except at the beginning AND end). This is useful for wikis and similar applications:: Rule('/<itemname:wikipage>') Rule('/<itemname:wikipage>/edit') """ regex = '[^/]+?(/[^/]+?)*' weight = 200 app.url_map.converters['itemname'] = ItemNameConverter # 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
from flask.ext.cache import Cache from flask.ext.themes import setup_themes from flask.ext.mongokit import MongoKit from application import register_views, register_filters, register_db, set_logging, \ configure_errorhandlers, configure_develop_handlers from config import DefaultConfig config = DefaultConfig() app = Flask(__name__) app.debug = config.DEBUG app.secret_key = config.SECRET_KEY app.config['CACHE_TYPE'] = config.CACHE_TYPE app.config['MONGODB_HOST'] = config.MONGODB_HOST app.config['MONGODB_PORT'] = config.MONGODB_PORT app.config['MONGODB_DATABASE'] = config.MONGODB_DATABASE db = MongoKit(app) setup_themes(app, app_identifier='wordstore', theme_url_prefix='/themes') cache = Cache(app) register_db(db) register_views(app) register_filters(app) configure_errorhandlers(app) if config.DEV: configure_develop_handlers(app) if not config.DEBUG: set_logging(app)
eventframe.models.db.init_app(app) eventframe.models.db.init_app(eventapp) # Fourth, setup baseframe, assets and theme assets on both apps app.register_blueprint(baseframe) eventapp.register_blueprint(baseframe) assets = Environment(app) eventassets = ThemeAwareEnvironment(eventapp) js = Bundle(baseframe_js, toastr_js, filters='jsmin', output='js/packed.js') css = Bundle(baseframe_css, toastr_css, 'css/app.css', filters='cssmin', output='css/packed.css') assets.register('js_all', js) assets.register('css_all', css) eventassets.register('js_baseframe', baseframe_js) eventassets.register('css_baseframe', baseframe_css) setup_themes(eventapp, app_identifier='eventframe') setup_themes(app, app_identifier='eventframe') # To list themes in the admin views for theme in eventapp.theme_manager.list_themes(): load_theme_assets(eventassets, theme) application = DomainDispatcher(app.config['ADMIN_HOSTS'], app, eventapp)
from flask import (Flask, url_for, redirect, session, Markup, abort) from flask.ext.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()
lm = LoginManager() lm.init_app(blog) lm.login_view = 'login' lm.login_message = u"请先登录" cache = Cache(blog) '''控制台''' manager = Manager(blog) '''数据库迁移''' migrate = Migrate(blog, db) '''邮件''' mymail = Mail(blog) '''主题''' setup_themes(blog, app_identifier='blog') '''Urls''' from blog import Urls '''日志设置''' ''' if not blog.debug: import logging from logging.handlers import SMTPHandler credentials = None if MAIL_USERNAME or MAIL_PASSWORD: credentials = (MAIL_USERNAME, MAIL_PASSWORD) mail_handler = SMTPHandler((MAIL_SERVER, MAIL_PORT), 'no-reply@' + MAIL_SERVER, ADMINS, 'microblog failure', credentials) mail_handler.setLevel(logging.ERROR) blog.logger.addHandler(mail_handler) '''
db = SQLAlchemy(blog) lm = LoginManager() lm.init_app(blog) lm.login_view = 'login' lm.login_message = u"请先登录" cache = Cache(blog) '''控制台''' manager = Manager(blog) '''数据库迁移''' migrate = Migrate(blog, db) '''邮件''' mymail = Mail(blog) '''主题''' setup_themes(blog, app_identifier='blog') '''Urls''' from blog import Urls '''日志设置''' ''' if not blog.debug: import logging from logging.handlers import SMTPHandler credentials = None if MAIL_USERNAME or MAIL_PASSWORD: credentials = (MAIL_USERNAME, MAIL_PASSWORD) mail_handler = SMTPHandler((MAIL_SERVER, MAIL_PORT), 'no-reply@' + MAIL_SERVER, ADMINS, 'microblog failure', credentials) mail_handler.setLevel(logging.ERROR) blog.logger.addHandler(mail_handler) '''
def configure_extensions(app): # configure extensions db.init_app(app) mail.init_app(app) cache.init_app(app) setup_themes(app)
class TestSetup(object): def test_manager(self): app = Flask(__name__) manager = ThemeManager(app, 'testing') assert app.theme_manager is manager app.config['THEME_PATHS'] = [join(TESTS, 'morethemes')] manager.refresh() themeids = manager.themes.keys() themeids.sort() assert themeids == ['cool', 'plain'] assert manager.themes['cool'].name == 'Cool Blue v2' 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') assert '_themes' in app.blueprints assert 'theme' in app.jinja_env.globals assert 'theme_static' in app.jinja_env.globals 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
def create_app(config_filename, appname): app = Flask(appname) app.config.from_pyfile(config_filename) setup_themes(app, theme_url_prefix="/" + appname) return app