def _setup_i18n(self, app): global babel global LOCALES global LANGUAGES babel = Babel(app) def get_available_locale_identifiers(locales): result = set() # add available translations for locale in locales: result.add(locale.language) if locale.territory: # if a territory is specified, add that too result.add("%s_%s" % (locale.language, locale.territory)) return result LOCALES = babel.list_translations() LANGUAGES = get_available_locale_identifiers(LOCALES) @babel.localeselector def get_locale(): return self._get_locale()
def create_app(config): """A factory that returns an application object from the passed config. The factory accepts further configuration from ENV variables. Some simple checks for core configuration settings are made to raise errors early if vital information is missing. """ import os from flask import Flask from flask.ext.babel import Babel from flask.ext.cors import CORS from flask.ext.markdown import Markdown # from flask.ext.assets import Environment, Bundle from .components import api, pages from .components.commons import context_processors, encoders app_label = 'web' # Get the static and template folder for the passed theme static_folder = os.path.join('theme', 'static') template_folder = os.path.join('theme', 'templates') # Construct app and service objects app = Flask(app_label, template_folder=template_folder, static_folder=static_folder, static_url_path='/static') trans = Babel() cors = CORS(resources=r'/api/*', allow_headers='Content-Type') # assets = Environment() # Configure the app with defaults app.config.from_object(config) # Set app core services trans.init_app(app) cors.init_app(app) # assets.init_app(app) Markdown(app) # Register routable components app.register_blueprint(api.blueprint) app.register_blueprint(pages.blueprint) # Set additional jinja2 extensions app.jinja_env.add_extension('jinja2.ext.do') # Set custom context processors app.context_processor(context_processors.inject_app_data) # Set custom encoders app.json_encoder = encoders.JSONEncoder # Register webassets bundles # sass = Bundle('css/base.scss', filters='pyscss', output='css/base.css') # assets.register('sass', sass) return app
def babel_init(app): babel = Babel() babel.init_app(app) @babel.timezoneselector def get_timezone(): timezone = request.cookies.get('timezone') if timezone is not None: timezone = unquote(timezone) return timezone
def create_app(): """Create an application.""" app = Flask(__name__) app.config.from_object('flaskberry.settings') load_modules(app) socketio.init_app(app) babel = Babel(app) babel.locale_selector_func = get_locale return app
def configure_babel(app): # Load additional languages into the babel # cache. We do this so we can add Haitian Creole # using french as a model. babel_patched_load('cpf') # flask-babel babel = Babel(app) # Wire Babel into the settings # and the settings code into Babel settings_views.set_babel(babel) babel.localeselector(settings_views.current_locale) return babel
def configure_extensions(app): # configure extensions # sqlalchemy db.init_app(app) db_ean.init_app(app) # mail mail.init_app(app) # cache cache.init_app(app) # babel babel = Babel(app) # login login_manager.login_view = 'frontend.login' login_manager.refresh_view = 'frontend.reauth' @login_manager.user_loader def load_user(id): return User.query.get(int(id)) login_manager.setup_app(app) # security and Social app.flask_security = Security(app, SQLAlchemyUserDatastore(db, User, Role)) #app.flask_social = Social(app, SQLAlchemyConnectionDatastore(db, Connection)) # admin admin = Admin(app) #admin.add_view(ModelView(GenomeRule, db.session)) admin.add_view(GenomeRuleView(db.session, name="Genome Rules")) admin.add_view(GenomeCategoryView(db.session, name="Genome Categories"))
def configure_extensions(app): # flask-sqlalchemy db.init_app(app) # flask-migrate migrate.init_app(app, db) # flask-mail mail.init_app(app) # flask-cache cache.init_app(app) # flask-assets assets.init_app(app) # flask-babel babel = Babel(app) @babel.localeselector def get_locale(): return request.accept_languages.best_match(DefaultConfig.LANGUAGES) # flask-login login_manager.login_view = 'frontend.login' login_manager.refresh_view = 'frontend.reauth' @login_manager.user_loader def load_user(id): return User.query.get(id) login_manager.setup_app(app)
def configure_i18n(app): babel = Babel(app) @babel.localeselector def get_locale(): accept_languages = app.config.get('ACCEPT_LANGUAGES', ['en', 'zh']) return request.accept_languages.best_match(accept_languages)
def configure_extensions(app, chanjo_api=None): """Initialize Flask extensions.""" # Miner Chanjo API if chanjo_api is None: api.init_app(app) app.chanjo_api = chanjo_api or api # Flask-babel babel = Babel(app) @babel.localeselector def get_locale(): """Determine locale to use for translations.""" # language can be forced in config user_language = app.config.get('CHANJO_LANGUAGE') if user_language: return user_language # unless forced, go on with the guessing accept_languages = app.config.get('ACCEPT_LANGUAGES') # try to guess the language from the user accept header that # the browser transmits. We support de/fr/en in this example. # The best match wins. return request.accept_languages.best_match(accept_languages)
def init_app(app, db, extra_config_settings={}): # Initialize app config settings app.config.from_object( 'webrob.config.settings') # Read config from 'app/settings.py' file app.config.update(extra_config_settings ) # Overwrite with 'extra_config_settings' parameter if app.testing: app.config[ 'WTF_CSRF_ENABLED'] = False # Disable CSRF checks while testing # Setup Flask-Mail mail = Mail(app) babel = Babel(app) # Setup Flask-User to handle user account related forms from webrob.models.users import User db_adapter = SQLAlchemyAdapter(db, User) user_manager = UserManager(db_adapter, app) # Init Flask-User and bind to app # Load all models.py files to register db.Models with SQLAlchemy from webrob.models import users from webrob.models import tutorials # Load all views.py files to register @app.routes() with Flask from webrob.pages import views from webrob.pages import editor from webrob.pages import log from webrob.pages import login init_db(app, db) return app
def configure_extensions(app): # flask-sqlalchemy db.init_app(app) # flask-mail mail.init_app(app) # flask-cache cache.init_app(app) # flask-babel babel = Babel(app) @babel.localeselector def get_locale(): accept_languages = app.config.get('ACCEPT_LANGUAGES') return request.accept_languages.best_match(accept_languages) # flask-login login_manager.login_view = 'frontend.login' login_manager.refresh_view = 'frontend.reauth' @login_manager.user_loader def load_user(id): return User.query.get(id) login_manager.setup_app(app) # flask-openid oid.init_app(app)
def configure_extensions(app): # flask-sqlalchemy db.init_app(app) # flask-mail mail.init_app(app) # flask-cache cache.init_app(app) # flask-babel babel = Babel(app) @babel.localeselector def get_locale(): # TODO, first check user config? g.accept_languages = app.config.get('ACCEPT_LANGUAGES') accept_languages = g.accept_languages.keys() browser_default = request.accept_languages.best_match(accept_languages) if 'language' in session: language = session['language'] # current_app.logger.debug('lang from session: %s' % language) if language not in accept_languages: # clear it # current_app.logger.debug('invalid %s, clearing' % language) session['language'] = None language = browser_default else: language = browser_default # current_app.logger.debug('lang from browser: %s' % language) session['language'] = language # save it to session # and to user? return language # flask-login login_manager.login_view = 'frontend.login' login_manager.refresh_view = 'frontend.reauth' @login_manager.user_loader def load_user(id): return User.query.get(id) login_manager.setup_app(app) # flask-openid oid.init_app(app) # csrf for wtforms # from flask.ext.wtf import csrf csrf.init_app(app) # flask-restless rest.init_app(app, flask_sqlalchemy_db=db) restless_routes() # actually setup the routes # flask-admin admin = Admin(app, name='RootIO Backend', index_view=AdminHomeView()) admin_routes(admin) # add flask-admin classes
def init_i18n(app): babel = Babel(app) @babel.localeselector def get_locale(): lan = app.config.get('ACCEPT_LANGUAGES', ['zh']) return request.accept_languages.best_match(lan)
def initialise(self): """ The application needs initialisation to load the database connection etc. In previous versions this was done with the initialisation of the class in the __init__ method. This is now separated into this function. """ #: Check if the secret key is defined, if not raise an #: exception since it is required assert self.secret_key, 'Secret Key is not defined in config' #: Load the cache self.load_cache() #: Initialise the CSRF handling self.csrf_protection = NereidCsrfProtect() self.csrf_protection.init_app(self) self.view_functions['static'] = self.send_static_file # Backend initialisation self.load_backend() #: Initialise the login handler login_manager = LoginManager() login_manager.user_loader(self._pool.get('nereid.user').load_user) login_manager.header_loader( self._pool.get('nereid.user').load_user_from_header) login_manager.token_loader( self._pool.get('nereid.user').load_user_from_token) login_manager.unauthorized_handler( self._pool.get('nereid.user').unauthorized_handler) login_manager.login_view = "nereid.website.login" login_manager.anonymous_user = self._pool.get('nereid.user.anonymous') login_manager.init_app(self) self.login_manager = login_manager # Monkey patch the url_for method from flask-login to use # the nereid specific url_for flask.ext.login.url_for = url_for self.template_context_processors[None].append( self.get_context_processors()) # Add the additional template context processors self.template_context_processors[None].append( nereid_default_template_ctx_processor) # Add template_filters registered using decorator for name, function in self.get_template_filters(): self.jinja_env.filters[name] = function # Initialize Babel Babel(self) # Finally set the initialised attribute self.initialised = True
def init_app(extra_config_settings={}): # Initialize app config settings app.config.from_object( 'config.settings') # Read config from 'app/settings.py' file app.config.update(extra_config_settings ) # Overwrite with 'extra_config_settings' parameter if app.testing: app.config[ 'WTF_CSRF_ENABLED'] = False # Disable CSRF checks while testing if os.environ['EASE_DEBUG'] == 'true': app.config['DEBUG'] = True app.config['SECRET_KEY'] = app.config['DEV_SECRET_KEY'] else: try: app.config['SECRET_KEY'] = open('/etc/ease_secret/secret', 'rb').read() except IOError: app.config['SECRET_KEY'] = random_string(64) # Setup Flask-Mail mail = Mail(app) babel = Babel(app) # Setup Flask-User to handle user account related forms from postgres.users import User db_adapter = SQLAlchemyAdapter(db, User) # Init Flask-User and bind to app app.user_manager = UserManager(db_adapter, app, password_validator=oe_password_validator) # Load all models.py files to register db.Models with SQLAlchemy from postgres import users from postgres import settings # Automatically create all registered DB tables db.create_all() db.session.commit() for role in USER_ROLES: create_role(role) # Load all views.py files to register @app.routes() with Flask from pages import main from pages import api from pages import neem_discovery from pages import editor from pages import tutorials from pages import oauth add_user(user_manager=app.user_manager, name='admin', mail=os.environ.get('OPENEASE_MAIL_USERNAME', '*****@*****.**'), pw=ADMIN_USER_DEFAULT_PW, roles=['admin']) app.logger.info("Webapp started.") return app
def configure_i18n(app): babel = Babel(app) @babel.localeselector def get_locale(): language = request.values.get("lan") if not language: language = request.cookies.get("lan", "zh") return language
def create_app(): create_db() Babel(app) Mail(app) db_adapter = SQLAlchemyAdapter(db, models.User) UserManager(db_adapter, app) searcher = Searcher() init_routes(app, db.session, searcher) return app
def create_app(config='dev'): """ Flask application factory :param str config: type of app to build, either "prod" or "dev" """ # Create flask application app = Flask(__name__) app.config.from_object('settings') app.config['ENV'] = config app.jinja_env.trim_blocks = True # Debug toolbar (when debug=true) debug_toolbar = DebugToolbarExtension(app) app.config['DEBUG_TB_PROFILER_ENABLED'] = True app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False # Register Blueprints app.register_blueprint(views_base.base) app.register_blueprint(views_blog.blog) # Flask-Assets; bundles all css/js files in minifed file assets = Environment(app) css_all = Bundle('css/bootstrap-flatly.min.css', 'css/highlightjs.min.css', 'css/font-awesome.css', 'css/main.css', filters='cssmin', output='gen/style.css') js_all = Bundle('js/vendor/jquery.min.js', 'js/vendor/bootstrap.min.js', 'js/vendor/showdown-gfm.min.js', 'js/vendor/highlight.min.js', 'js/main.js', filters='jsmin', output='gen/libs.js') assets.register('css_all', css_all) assets.register('js_all', js_all) if app.config['DEBUG']: assets.debug = True app.config['ASSETS_DEBUG'] = True # Set up Flask-User babel = Babel(app) db_adapter = SQLAlchemyAdapter(db, User) user_manager = UserManager(db_adapter, app) # Init Flask-User and bind to app # Init the cache cache.init_app(app) Moment(app) # moment.js Misaka(app, autolink=True, # Misaka Markdown fenced_code=True, lax_html=True, strikethrough=True, superscript=True, tables=True, wrap=True) # Init Admin page admin = Admin(app, index_view=AdminMain(endpoint='admin')) admin.add_view(PostAdminView()) admin.add_view(NewPostView()) admin.add_view(ModelView(Comment, db.session)) static_path = os.path.join(BASE_DIR, 'app', 'static') admin.add_view(FileAdminView(static_path, '/static/', name='Static Files')) # Initialize DB db.init_app(app) return app
def configure_extensions(app): # flask-sqlalchemy db.init_app(app) # flask-babel babel = Babel(app) @babel.localeselector def get_locale(): accept_languages = app.config.get('ACCEPT_LANGUAGES') return request.accept_languages.best_match(accept_languages)
def init_app(self, app): self.app = app app.config.setdefault('CSRF_ENABLED', True) app.config.setdefault('SENTRY_ENABLED', False) app.config.setdefault('BEHIND_REVERSE_PROXY', False) app.config.setdefault('REDIS_SESSIONS_ENABLED', False) app.config.setdefault('REDIS_SESSIONS_DB', 1) app.config.setdefault('REDIS_SESSIONS_HOST', '127.0.0.1') app.config.setdefault('REDIS_SESSIONS_PORT', 6379) app.config.setdefault('REDIS_SESSIONS_PICKLE_PROTO', 3) app.config.setdefault('BABEL_ENABLED', False) bp = Blueprint('boilerplate', __name__, template_folder='templates') self.app.register_blueprint(bp) # Inject various globals into jinja app.jinja_env.globals['csrf_setup'] = csrf_setup app.jinja_env.globals['render_field'] = render_field app.jinja_env.filters['percent_escape'] = percent_escape app.jinja_env.filters['time_since'] = timesince if app.config.get('CSRF_ENABLED'): from flask_wtf.csrf import CsrfProtect app.csrf = CsrfProtect(app) if app.config.get('BEHIND_REVERSE_PROXY'): from .ReverseProxied import ReverseProxied app.wsgi_app = ReverseProxied(app.wsgi_app) if app.config.get('SENTRY_ENABLED') and not app.debug: from raven.contrib.flask import Sentry app.sentry = Sentry(app) if app.config.get('REDIS_SESSIONS_ENABLED'): from .RedisSessionInterface import RedisSessionInterface from redis import Redis redis = Redis(host=app.config.get('REDIS_SESSIONS_HOST'), port=app.config.get('REDIS_SESSIONS_PORT'), db=app.config.get('REDIS_SESSIONS_DB')) app.session_interface = RedisSessionInterface( redis=redis, pickle_protocol=app.config.get('REDIS_SESSIONS_PICKLE_PROTO')) if app.config.get('BABEL_ENABLED'): from flask.ext.babel import Babel from .filters import local_date, local_date_time app.babel = Babel(app) app.jinja_env.filters['local_date'] = local_date app.jinja_env.filters['local_date_time'] = local_date_time return True
def register_babel(app): from flask.ext.babel import Babel babel = Babel(app) @babel.localeselector def get_locale(): app.config.setdefault('BABEL_SUPPORTED_LOCALES', ['en', 'zh']) app.config.setdefault('BABEL_DEFAULT_LOCALE', 'en') match = app.config['BABEL_SUPPORTED_LOCALES'] default = app.config['BABEL_DEFAULT_LOCALE'] return request.accept_languages.best_match(match, default)
def register_extensions(app): """ All extensions used by the application are registered here """ # Register database db.init_app(app) # Flask Babel for translations babel = Babel(app) @babel.localeselector def get_locale(): accept_languages = app.config.get('ACCEPT_LANGUAGES') return request.accept_languages.best_match(accept_languages) # Flask Login login_manager.setup_app(app)
def create_app(config): app = Flask(__name__) app.config.from_object(config) login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'website.login' @login_manager.user_loader def load_user(user_id): return User.load(user_id) @app.before_request def on_request(): g.db = database.connect() @app.teardown_request def on_teardown(exception): db = getattr(g, 'db', None) if db is not None: db.close() @app.after_request def after_request_calls(response): for callback in getattr(g, 'after_request_callbacks', ()): callback(response) return response babel = Babel(app) @babel.localeselector def select_locale(): if 'lang' in request.args: lang = request.args.get('lang') @call_after_request def set_cookie(request): request.set_cookie('lang', lang, 60 * 60 * 24 * 31 * 12) return lang return request.cookies.get('lang') or \ request.accept_languages.best_match(app.config.get('LANGUAGES')) from .website import website app.register_blueprint(website) from .api import api app.register_blueprint(api, url_prefix='/api') return app
def init_app(app, db_instance, extra_config_settings={}): # Initialize app config settings app.config.from_object('webrob.config.settings') # Read config from 'app/settings.py' file app.config.update(extra_config_settings) # Overwrite with 'extra_config_settings' parameter if app.testing: app.config['WTF_CSRF_ENABLED'] = False # Disable CSRF checks while testing if os.environ['EASE_DEBUG'] == 'true': app.config['DEBUG'] = True app.config['SECRET_KEY'] = app.config['DEV_SECRET_KEY'] else: try: app.config['SECRET_KEY'] = open('/etc/ease_secret/secret', 'rb').read() except IOError: app.config['SECRET_KEY'] = random_string(64) # Setup Flask-Mail mail = Mail(app) babel = Babel(app) # Setup Flask-User to handle user account related forms from webrob.models.users import User db_adapter = SQLAlchemyAdapter(db_instance, User) user_manager = UserManager(db_adapter, app) # Init Flask-User and bind to app # Load all models.py files to register db.Models with SQLAlchemy from webrob.models import users from webrob.models import tutorials from webrob.models import experiments # Load all views.py files to register @app.routes() with Flask from webrob.pages import api from webrob.pages import db from webrob.pages import editor from webrob.pages import experiments from webrob.pages import knowrob from webrob.pages import login from webrob.pages import meshes from webrob.pages import mongo from webrob.pages import tutorials init_db(app, db_instance) init_webapp(app, db_instance) add_user(app,db_instance,user_manager,'admin', os.environ.get('OPENEASE_MAIL_USERNAME', '*****@*****.**'), os.environ.get('OPENEASE_ADMIN_PASSWORD'), ['admin']) app.logger.info("Webapp started.") return app
def register_babel(app): babel = Babel(app) babel.init_app(app) app.babel = babel @app.before_request def append_session_globals(): """ Add two-character and three-char session locale to global template contexts: session_locale, session_locale_long_iso. """ loc = get_locale() app.jinja_env.globals['session_locale'] = loc @babel.localeselector def get_locale(): """ This function defines the behavior involved in selecting a locale. """ default_locale = 'nb' # Does the locale exist already? ses_lang = session.get('locale', None) if ses_lang is not None: return ses_lang else: # Is there a default locale specified in config file? ses_lang = default_locale session.locale = ses_lang session['locale'] = ses_lang app.jinja_env.globals['session'] = session return ses_lang return app
def configure_extensions(app): #from simplekv.memory import DictStore #from flask.ext.kvsession import KVSessionExtension #store = DictStore() ## this will replace the app's session handling #KVSessionExtension(store, app) mongo.init_app(app, "FUNFUNSAY") # cache cache.init_app(app) # babel #print "create babel object" babel = Babel(app) @babel.localeselector def get_locale(): # if a user is logged in, use the locale from the user settings if current_user.is_authenticated(): return current_user.locale # otherwise try to guess the language from the user accept # header the browser transmits. We support de/fr/en in this # example. The best match wins. return request.accept_languages.best_match(['zh_CN', 'en']) @babel.timezoneselector def get_timezone(): if current_user.is_authenticated(): return current_user.timezone return app.config['BABEL_DEFAULT_TIMEZONE'] # login. from flask.ext.login import LoginManager login_manager = LoginManager() login_manager.session_protection = None #@fixme! login_manager.login_view = 'homesite.login' login_manager.refresh_view = 'homesite.reauth' login_manager.login_message = _("Please log in to access this page.") @login_manager.user_loader def load_user(id): #print "####: loaduser ", id return User.load_user(id) login_manager.setup_app(app) from flask.ext.markdown import Markdown Markdown(app, safe_mode="escape")
def init_app(app, db_instance, extra_config_settings={}): _init_app_config_settings(app, extra_config_settings) # Setup Flask-Mail mail = Mail(app) babel = Babel(app) # Setup Flask-User to handle user account related forms from webrob.models.users import User db_adapter = SQLAlchemyAdapter(db_instance, User) app.user_manager = UserManager(db_adapter, app) # Init Flask-User and bind to app # Load all models.py files to register db.Models with SQLAlchemy # Needs to remain in code, even if IDEs might show it's unused, Flask will use them during runtime from webrob.models import users from webrob.models import tutorials from webrob.models import teaching from webrob.models import experiments # Load all views.py files to register @app.routes() with Flask # Needs to remain in code, even if IDEs might show it's unused, Flask will use them during runtime from webrob.pages import api from webrob.pages import db from webrob.pages import editor from webrob.pages import experiments from webrob.pages import knowrob from webrob.pages import login from webrob.pages import meshes from webrob.pages import mongo from webrob.pages import tutorials from webrob.pages import oauth init_db(app, db_instance) init_webapp(app, db_instance) add_user(app=app, db=db_instance, user_manager=app.user_manager, name='admin', mail=evg.get_variable_with_default('OPENEASE_MAIL_USERNAME', '*****@*****.**'), pw=evg.get_required_variable('OPENEASE_ADMIN_PASSWORD'), roles=['admin']) _log_webapp_started(app) return app
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
def create_app(**config_overrides): app = web.create_app(__name__, __path__, **config_overrides) tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates') static_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static') app.template_folder = tmpl_dir app.static_folder = static_dir oauth.init_app(app) assets.init_app(app) babel = Babel(app) # So we can use Jade templates. app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension') return app
def __init__(self, config, manager=False): from flask.ext.babel import Babel from utils.mysql import FlaskFyMySQL self.prepared = False self.config = config self.app = Flask(__name__, template_folder=self.config.TEMPLATE_FOLDER, static_folder=self.config.STATIC_FOLDER) self.app.config.from_object(config) self.app.wsgi_app = ProxyFix(self.app.wsgi_app) self.babel = Babel(self.app) self.db = FlaskFyMySQL(self.app) if not manager: self.prepare()
def locale_handlers(app): """ Registers application handlers for the localization strategy. """ def get_request_locale(): default_culture = app.config["DEFAULT_CULTURE"] cultures = app.config["CULTURES"].keys() # if the culture is set in the header, then use it (needed to ensure consistency when multiple tabs are open) header_value = request.headers.get("X-Request-Culture") if header_value and header_value in cultures: # set and exit return header_value # if the user identity is known, support user favorite language user = request.user if hasattr(request, "user") else None if user is not None and user.culture: user_culture = user.culture if user_culture and user_culture in cultures: return user_culture culture_cookie = request.cookies.get("culture") if culture_cookie and culture_cookie in cultures: return culture_cookie # set culture by browser setting, or application default best_match = request.accept_languages.best_match(cultures) if best_match: return best_match return default_culture # localization: babel = Babel(app) @babel.localeselector def get_locale(): locale = get_request_locale() request.culture = locale return locale @app.after_request def add_culture_cookie(response): culture = request.culture if hasattr(request, "culture") else None if culture: response.set_cookie("culture", value=culture) return response
def configi18n(app): babel = Babel(app) @babel.localeselector def get_locale(): accept_languages = app.config.get('accept_languages', ['en_us', 'zh_cn']) default_language = app.config.get('babel_default_locale', ['en_us']) lang = request.accept_languages.best_match(default_language) for language in request.accept_languages: lang = language[0].replace('-', '_') if lang in accept_languages: break return lang
def test_i18n_enabled(self): from flask import request from flask.ext.babel import Babel babel = Babel(self.app) @babel.localeselector def get_locale(): return request.accept_languages.best_match(['en', 'zh'], 'en') self.app.config['CSRF_ENABLED'] = False response = self.client.post( "/", headers={'Accept-Language': 'zh-CN,zh;q=0.8'}, data={}) assert '\u8be5\u5b57\u6bb5\u662f' in to_unicode(response.data) response = self.client.post("/", data={}) assert b'This field is required.' in response.data
def create_app(): app = Flask(__name__) app.config.from_object("config") database.init_database(app) app.toolbar = DebugToolbarExtension(app) app.babel = Babel(app) @app.before_request def before_request(): g.context = {} # elixir.setup_all() return app
def configure_i18n(app): """ tanzimate marbot be i18n va systeme tarjome dar in bakhsh emal mishavad """ babel = Babel(app) @babel.localeselector def get_locale(): return request.accept_languages.best_match(['fa']) # return 'fa' # find set lang # TODO: user az inja gerefte mishe?! # aslan to in marhale user darim ma ya ye chize zafeyi hast?! user = getattr(g, 'user', None) if user is not None: pass accept_languages = app.config.get('ACCEPT_LANGUAGES', ['fa', 'en']) return request.accept_languages.best_match(accept_languages)
def __init__(self, *args, **kwargs): BabelBase.__init__(self, *args, **kwargs)
def create_app(app_name=config.APP_NAME): """Create the Flask application, startup logging and dynamically load additional modules (blueprints) that are found in this directory.""" app = PgAdmin(__name__, static_url_path='/static') # Removes unwanted whitespace from render_template function app.jinja_env.trim_blocks = True app.config.from_object(config) ########################################################################## # Setup session management ########################################################################## app.session_interface = ServerSideSessionInterface(config.SESSION_DB_PATH) ########################################################################## # Setup logging and log the application startup ########################################################################## # Add SQL level logging, and set the base logging level logging.addLevelName(25, 'SQL') app.logger.setLevel(logging.DEBUG) app.logger.handlers = [] # We also need to update the handler on the webserver in order to see # request. Setting the level prevents werkzeug from setting up it's own # stream handler thus ensuring all the logging goes through the pgAdmin # logger. logger = logging.getLogger('werkzeug') logger.setLevel(logging.INFO) # File logging fh = logging.FileHandler(config.LOG_FILE) fh.setLevel(config.FILE_LOG_LEVEL) fh.setFormatter(logging.Formatter(config.FILE_LOG_FORMAT)) app.logger.addHandler(fh) logger.addHandler(fh) # Console logging ch = logging.StreamHandler() ch.setLevel(config.CONSOLE_LOG_LEVEL) ch.setFormatter(logging.Formatter(config.CONSOLE_LOG_FORMAT)) app.logger.addHandler(ch) logger.addHandler(ch) # Log the startup app.logger.info('########################################################') app.logger.info('Starting %s v%s...', config.APP_NAME, config.APP_VERSION) app.logger.info('########################################################') app.logger.debug("Python syspath: %s", sys.path) ########################################################################## # Setup i18n ########################################################################## # Initialise i18n babel = Babel(app) app.logger.debug('Available translations: %s' % babel.list_translations()) @babel.localeselector def get_locale(): """Get the best language for the user.""" language = request.accept_languages.best_match(config.LANGUAGES.keys()) return language ########################################################################## # Setup authentication ########################################################################## app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{0}?timeout={1}'.format( config.SQLITE_PATH.replace('\\', '/'), getattr(config, 'SQLITE_TIMEOUT', 500) ) # Only enable password related functionality in server mode. if config.SERVER_MODE is True: # TODO: Figure out how to disable /logout and /login app.config['SECURITY_RECOVERABLE'] = True app.config['SECURITY_CHANGEABLE'] = True # Create database connection object and mailer db.init_app(app) Mail(app) import pgadmin.utils.paths as paths paths.init_app(app) # Setup Flask-Security user_datastore = SQLAlchemyUserDatastore(db, User, Role) security = Security(app, user_datastore) # Upgrade the schema (if required) with app.app_context(): version = Version.query.filter_by(name='ConfigDB').first() # Pre-flight checks if int(version.value) < int(config.SETTINGS_SCHEMA_VERSION): app.logger.info( """Upgrading the database schema from version {0} to {1}.""".format( version.value, config.SETTINGS_SCHEMA_VERSION ) ) from setup import do_upgrade do_upgrade(app, user_datastore, security, version) # Load all available server drivers driver.init_app(app) ########################################################################## # Register any local servers we can discover ########################################################################## @user_logged_in.connect_via(app) def on_user_logged_in(sender, user): # Keep hold of the user ID user_id = user.id # Get the first server group for the user servergroup_id = 1 servergroups = ServerGroup.query.filter_by( user_id=user_id ).order_by("id") if servergroups.count() > 0: servergroup = servergroups.first() servergroup_id = servergroup.id '''Add a server to the config database''' def add_server(user_id, servergroup_id, name, superuser, port, discovery_id, comment): # Create a server object if needed, and store it. servers = Server.query.filter_by( user_id=user_id, discovery_id=svr_discovery_id ).order_by("id") if servers.count() > 0: return; svr = Server(user_id=user_id, servergroup_id=servergroup_id, name=name, host='localhost', port=port, maintenance_db='postgres', username=superuser, ssl_mode='prefer', comment=svr_comment, discovery_id=discovery_id) db.session.add(svr) db.session.commit() # Figure out what servers are present if os.name == 'nt': proc_arch = os.environ['PROCESSOR_ARCHITECTURE'].lower() proc_arch64 = os.environ['PROCESSOR_ARCHITEW6432'].lower() if proc_arch == 'x86' and not proc_arch64: arch_keys = {0} elif proc_arch == 'x86' or proc_arch == 'amd64': arch_keys = { KEY_WOW64_32KEY, KEY_WOW64_64KEY } for arch_key in arch_keys: for server_type in { 'PostgreSQL', 'EnterpriseDB'}: try: root_key = OpenKey(HKEY_LOCAL_MACHINE, "SOFTWARE\\" + server_type + "\Services", 0, KEY_READ | arch_key) for i in xrange(0, QueryInfoKey(root_key)[0]): inst_id = EnumKey(root_key, i) inst_key = OpenKey(root_key, inst_id) svr_name = QueryValueEx(inst_key, 'Display Name')[0] svr_superuser = QueryValueEx(inst_key, 'Database Superuser')[0] svr_port = QueryValueEx(inst_key, 'Port')[0] svr_discovery_id = inst_id svr_comment = gettext("Auto-detected %s installation with the data directory at %s" % ( QueryValueEx(inst_key, 'Display Name')[0], QueryValueEx(inst_key, 'Data Directory')[0])) add_server(user_id, servergroup_id, svr_name, svr_superuser, svr_port, svr_discovery_id, svr_comment) inst_key.Close() except: pass else: # We use the postgres-reg.ini file on non-Windows try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser # Python 2 registry = ConfigParser() try: registry.read('/etc/postgres-reg.ini') sections = registry.sections() # Loop the sections, and get the data from any that are PG or PPAS for section in sections: if section.startswith('PostgreSQL/') or section.startswith('EnterpriseDB/'): svr_name = registry.get(section, 'Description') svr_superuser = registry.get(section, 'Superuser') svr_port = registry.getint(section, 'Port') svr_discovery_id = section svr_comment = gettext("Auto-detected %s installation with the data directory at %s" % ( registry.get(section, 'Description'), registry.get(section, 'DataDirectory'))) add_server(user_id, servergroup_id, svr_name, svr_superuser, svr_port, svr_discovery_id, svr_comment) except: pass ########################################################################## # Load plugin modules ########################################################################## for module in app.find_submodules('pgadmin'): app.logger.info('Registering blueprint module: %s' % module) app.register_blueprint(module) ########################################################################## # Handle the desktop login ########################################################################## @app.before_request def before_request(): """Login the default user if running in desktop mode""" if config.SERVER_MODE is False: user = user_datastore.get_user(config.DESKTOP_USER) # Throw an error if we failed to find the desktop user, to give # the sysadmin a hint. We'll continue to try to login anyway as # that'll through a nice 500 error for us. if user is None: app.logger.error( 'The desktop user %s was not found in the configuration database.' % config.DESKTOP_USER ) abort(401) login_user(user) ########################################################################## # Minify output ########################################################################## @app.after_request def response_minify(response): """Minify html response to decrease traffic""" if config.MINIFY_HTML and not config.DEBUG: if response.content_type == u'text/html; charset=utf-8': response.set_data( html_minify(response.get_data(as_text=True)) ) return response @app.context_processor def inject_blueprint(): """Inject a reference to the current blueprint, if any.""" return { 'current_app': current_app, 'current_blueprint': current_blueprint } ########################################################################## # All done! ########################################################################## app.logger.debug('URL map: %s' % app.url_map) return app
def test_human_name_is_i18n(self): app = self._get_flask() babel = Babel(app) with app.test_request_context('/'): babel.localeselector(lambda: 'fr') self.assertEquals(u'Météo', unicode(self._weather_app.human_name))
def i18n_init(app): """ initialize Flask-Babel """ babel = Babel(app) babel.localeselector(get_locale) babel.timezoneselector(get_timezone)
from flask import Flask, render_template, request, g from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from flask.ext.babel import Babel app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) babel = Babel(app) print babel.list_translations() print babel.default_locale login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = "user.login" @login_manager.user_loader def load_user(userid): import models as m user = db.session.query(m.user.User).filter(m.user.User.id == int(userid)).first() user.set_authenticated() g.user = user return user @babel.localeselector def get_locale():
DEFAULT_FETCH_COUNT = 10 app = flask.Flask(__name__) app.config.from_pyfile('config.py') app.static_folder = app.config['STATIC_PATH'] app.template_folder = app.config['TEMPLATE_PATH'] app.root_path = app.config['BASE_DIR'] db.init_app(app) # init babel babel = Babel() babel.init_app(app) print babel.list_translations() @babel.localeselector def get_locale(): user = getattr(flask.g, 'user', None) if user is not None: return getattr(user, 'locale', 'zh_Hans_CN') accept_languages = app.config.get('ACCEPT_LANGUAGES', ['zh_Hans_CN']) return flask.request.accept_languages.best_match(accept_languages) app.json_encoder = utils.MyJsonEncoder
from flask.ext.babel import Babel, get_locale from wtforms import TextField, HiddenField, ValidationError, RadioField,\ BooleanField, SubmitField from wtforms.validators import Required try: from wtforms.fields import HiddenField except ImportError: def is_hidden_field_filter(field): raise RuntimeError('WTForms is not installed.') else: def is_hidden_field_filter(field): return isinstance(field, HiddenField) login_manager = LoginManager() babel = Babel() app = Flask(__name__) login_manager.init_app(app) babel.init_app(app) app.jinja_env.globals['bootstrap_is_hidden_field'] =\ is_hidden_field_filter # in a real app, these should be configured through Flask-Appconfig app.config['SECRET_KEY'] = 'devkey' app.config['RECAPTCHA_PUBLIC_KEY'] = \ '6Lfol9cSAAAAADAkodaYl9wvQCwBMr3qGR_PPHcw' # import all files inside the view module from domogik.admin.views.index import *
from flask.ext.login import LoginManager from flask.ext.principal import Principal, Permission, RoleNeed, identity_loaded, UserNeed from flask.ext.babel import Babel from babel import Locale from watchdog.observers import Observer import os import logging import logging.config import atexit SUCCESS = {} NO_CONTENT = ("", 204) app = Flask("octoprint") babel = Babel(app) debug = False printer = None printerProfileManager = None fileManager = None slicingManager = None analysisQueue = None userManager = None eventManager = None loginManager = None pluginManager = None appSessionManager = None principals = Principal(app) admin_permission = Permission(RoleNeed("admin"))
def create_app(self): app = Flask(__name__) babel = Babel(app, default_locale='fr', default_timezone=USER_TZ) babel.localeselector(en_locale) babel.timezoneselector(user_tz) return app
def create_app(app_name=config.APP_NAME): """Create the Flask application, startup logging and dynamically load additional modules (blueprints) that are found in this directory.""" app = PgAdmin(__name__, static_url_path='/static') app.config.from_object(config) ########################################################################## # Setup logging and log the application startup ########################################################################## # Add SQL level logging, and set the base logging level logging.addLevelName(25, 'SQL') app.logger.setLevel(logging.DEBUG) app.logger.handlers = [] # We also need to update the handler on the webserver in order to see request. # Setting the level prevents werkzeug from setting up it's own stream handler # thus ensuring all the logging goes through the pgAdmin logger. logger = logging.getLogger('werkzeug') logger.setLevel(logging.INFO) # File logging fh = logging.FileHandler(config.LOG_FILE) fh.setLevel(config.FILE_LOG_LEVEL) fh.setFormatter(logging.Formatter(config.FILE_LOG_FORMAT)) app.logger.addHandler(fh) logger.addHandler(fh) # Console logging ch = logging.StreamHandler() ch.setLevel(config.CONSOLE_LOG_LEVEL) ch.setFormatter(logging.Formatter(config.CONSOLE_LOG_FORMAT)) app.logger.addHandler(ch) logger.addHandler(ch) # Log the startup app.logger.info('################################################################################') app.logger.info('Starting %s v%s...', config.APP_NAME, config.APP_VERSION) app.logger.info('################################################################################') app.logger.debug("Python syspath: %s", sys.path) ########################################################################## # Setup i18n ########################################################################## # Initialise i18n babel = Babel(app) app.logger.debug('Available translations: %s' % babel.list_translations()) @babel.localeselector def get_locale(): """Get the best language for the user.""" language = request.accept_languages.best_match(config.LANGUAGES.keys()) return language ########################################################################## # Setup authentication ########################################################################## app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + config.SQLITE_PATH.replace('\\', '/') # Only enable password related functionality in server mode. if config.SERVER_MODE is True: # TODO: Figure out how to disable /logout and /login app.config['SECURITY_RECOVERABLE'] = True app.config['SECURITY_CHANGEABLE'] = True # Create database connection object and mailer db.init_app(app) Mail(app) # Setup Flask-Security user_datastore = SQLAlchemyUserDatastore(db, User, Role) security = Security(app, user_datastore) # Upgrade the schema (if required) with app.app_context(): version = Version.query.filter_by(name='ConfigDB').first() # Pre-flight checks if int(version.value) < int(config.SETTINGS_SCHEMA_VERSION): app.logger.info( """Upgrading the database schema from version {0} to {1}.""".format( version.value, config.SETTINGS_SCHEMA_VERSION ) ) from setup import do_upgrade do_upgrade(app, user_datastore, security, version) ########################################################################## # Load plugin modules ########################################################################## for module in app.find_submodules('pgadmin'): app.logger.info('Registering blueprint module: %s' % module) app.register_blueprint(module) ########################################################################## # Handle the desktop login ########################################################################## @app.before_request def before_request(): """Login the default user if running in desktop mode""" if config.SERVER_MODE is False: user = user_datastore.get_user(config.DESKTOP_USER) # Throw an error if we failed to find the desktop user, to give # the sysadmin a hint. We'll continue to try to login anyway as # that'll through a nice 500 error for us. if user is None: app.logger.error('The desktop user %s was not found in the configuration database.' % config.DESKTOP_USER) abort(401) login_user(user) ########################################################################## # Minify output ########################################################################## @app.after_request def response_minify(response): """Minify html response to decrease traffic""" if config.MINIFY_HTML and not config.DEBUG: if response.content_type == u'text/html; charset=utf-8': response.set_data( html_minify(response.get_data(as_text=True)) ) return response @app.context_processor def inject_blueprint(): """Inject a reference to the current blueprint, if any.""" return { 'current_app': current_app, 'current_blueprint': current_blueprint } ########################################################################## # All done! ########################################################################## app.logger.debug('URL map: %s' % app.url_map) return app
def init_babel(app): babel = Babel(app) babel.timezoneselector(_get_timezone) app.before_request(_set_context_locale)
def make_app(): babel = Babel() security = Security() social = Social() user_datastore = SQLAlchemyUserDatastore(mdl.DB, mdl.User, mdl.Role) app = Flask(__name__) @login_failed.connect_via(app) def auto_add_user(sender, provider, oauth_response): connection_values = get_connection_values_from_oauth_response( provider, oauth_response) email = connection_values['email'] if not email or not email.strip(): email = '' if provider.name.lower() == 'facebook': fname = connection_values['full_name'] email = fb.get_email(oauth_response) elif provider.name.lower() == 'twitter': fname = connection_values['display_name'][1:] # cut off leading @ else: fname = connection_values['display_name'] user = user_datastore.create_user( email=email, name=fname, active=True, confirmed_at=datetime.now(), ) role_query = mdl.DB.session.query(mdl.Role).filter_by( name='authenticated') try: role = role_query.one() except NoResultFound: role = mdl.Role(name='authenticated') user.roles.append(role) user_datastore.commit() connection_values['user_id'] = user.id connect_handler(connection_values, provider) login_user(user) mdl.DB.session.commit() flash(gettext( 'Successfully linked login with {}. ' 'Ignore the message saying: "{}"').format( provider.name, '... account not associated with an existing user'), 'info') return redirect(url_for('root.profile')) app.user_datastore = user_datastore app.localconf = lconf = Config('mamerwiselen', 'lost-tracker', version='2.0', require_load=True) app.config['SECRET_KEY'] = lconf.get('app', 'secret_key') app.config['SQLALCHEMY_DATABASE_URI'] = lconf.get('db', 'dsn') mdl.DB.init_app(app) # Social connections social_connections = {} _add_social_params(social_connections, 'facebook', app.localconf) _add_social_params(social_connections, 'twitter', app.localconf) _add_social_params(social_connections, 'google', app.localconf) if len(social_connections) < 1: LOG.error('No Social/OAuth providers defined! Users will not be ' 'able to log-in!') app.config.update(social_connections) social.init_app(app, SQLAlchemyConnectionDatastore(mdl.DB, mdl.Connection)) security.init_app(app, user_datastore) app.register_blueprint(COMMENT, url_prefix=COMMENT_PREFIX) app.register_blueprint(GROUP, url_prefix=GROUP_PREFIX) app.register_blueprint(PHOTO, url_prefix=PHOTO_PREFIX) app.register_blueprint(QR, url_prefix=QR_PREFIX) app.register_blueprint(REGISTRATION, url_prefix=REGISTRATION_PREFIX) app.register_blueprint(ROOT) app.register_blueprint(STATION, url_prefix=STATION_PREFIX) app.register_blueprint(TABULAR, url_prefix=TABULAR_PREFIX) app.register_blueprint(USER, url_prefix=USER_PREFIX) babel.init_app(app) babel.localeselector(get_locale) return app
def translations(): babel = Babel(current_app) languages = babel.list_translations() return render_template('admin/translations.html',languages = languages)
def init_app(app): babel = Babel(app) babel.localeselector(get_locale)