Ejemplo n.º 1
0
def create_app(config="config.ini"):
    app = Flask(__name__, static_url_path='/static')
    app.config.update(MONGODB_SETTINGS={'DB': 'testapp'},
                      TESTING=True,
                      SECRET_KEY='flask+mongoengine=<3')
    # Define the WSGI application object
    db.init_app(app)
    login_manager.init_app(app)
    principals.init_app(app)
    # csrf protection
    csrf = CsrfProtect()
    csrf.init_app(app)
    # Register blueprint(s)
    from modules.inventory import inventory as inventory_blueprint
    app.register_blueprint(inventory_blueprint, url_prefix='/inventory')
    from modules.user import user as user_blueprint
    app.register_blueprint(user_blueprint, url_prefix='/user')
    from login import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    @app.route("/", methods=['GET'])
    @login_required
    @user.require(http_exception=403)
    def index():
        return render_template("index.html", menu=principal_menu())

    # Sample HTTP error handling
    @app.errorhandler(404)
    def not_found(error):
        return render_template('404.html'), 404

    @app.before_request
    def make_session_permanent():
        session.permanent = True
        app.permanent_session_lifetime = timedelta(minutes=5)
        session.modified = True

    @identity_loaded.connect_via(app)
    def on_identity_loaded(sender, identity):
        needs = []

        if identity.id in ('viewer', 'editor', 'admin'):
            needs.append(to_view)

        if identity.id in ('editor', 'admin'):
            needs.append(be_editor)

        if identity.id == 'admin':
            needs.append(be_admin)

        for n in needs:
            identity.provides.add(n)

        # If the authenticated identity is :
        # - 'the_only user' she can sign in
        # - "the_only_editor" she can sign in and edit
        # - "the_only_admin" she can sign in , edit and administrate

    return app
Ejemplo n.º 2
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config_map[config_name])
    config_map[config_name].init_app(app)
    csrf = CsrfProtect(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    # inicializa Flask extensions
    db.init_app(app)
    login_manager.init_app(app)
    moment.init_app(app)
    csrf.init_app(app)
    # retorna app configurada
    return app
Ejemplo n.º 3
0
def initialize_app(application, config, profile=False):
    # 读取配置
    application.config.from_object(config)


    # 注册蓝图
    from app_spider.views.input_data.input_api import input_data_api_view
    from app_spider.views.login.login_view import login_view
    from app_spider.views.data.data_view import data_view
    from app_spider.views.input_mongodb.input_api import input_mongodb_api_view

    application.register_blueprint(input_data_api_view)
    application.register_blueprint(login_view)
    application.register_blueprint(data_view)
    application.register_blueprint(input_mongodb_api_view)


    # restful api 不跨域保护
    csrf = CsrfProtect()
    csrf.init_app(application)
    csrf.exempt(input_data_api_view)
    csrf.exempt(login_view)
    csrf.exempt(data_view)
    csrf.exempt(input_mongodb_api_view)
Ejemplo n.º 4
0
def create_app(settings_file):
    app = Flask(__name__)
    app.config.from_pyfile(settings_file)

    cache.init_app(app)

    mail = Mail()
    csrf = CsrfProtect()

    csrf.init_app(app)
    db.init_app(app)

    toolbar = DebugToolbarExtension()
    toolbar.init_app(app)

    app.mail = mail

    mail.init_app(app)
    app.hashids = Hashids(salt="salty seafaring sailor",  min_length=8)

    register_errorhandlers(app)
    app.register_blueprint(main)
    
    return app
Ejemplo n.º 5
0
def create_app(config="config.ini"):

    app = Flask(__name__, static_url_path='/static')
    app.config.from_object(__name__)
    if os.path.exists(config):
        app.config.from_pyfile(config)
    else:
        print("The app does not have a config.ini file")
    # Define the WSGI application object
    db.init_app(app)
    # csrf protection
    login_manager.init_app(app)
    principals.init_app(app)
    csrf = CsrfProtect()
    csrf.init_app(app)
    # Register blueprint(s)
    from modules.inventory import inventory as inventory_blueprint
    app.register_blueprint(inventory_blueprint, url_prefix='/inventory')
    from modules.user import user as user_blueprint
    app.register_blueprint(user_blueprint, url_prefix='/user')
    from login import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    @app.route("/", methods=['GET'])
    @login_required
    @user.require(http_exception=403)
    def index():
        return render_template("index.html", menu=principal_menu())

    # Sample HTTP error handling
    @app.errorhandler(404)
    def not_found(error):
        return render_template('404.html'), 404

    # Sample HTTP error handling
    @app.errorhandler(403)
    def access_denied(error):
        return render_template('403.html'), 403

    # Sample HTTP error handling
    @app.errorhandler(500)
    def server_full(error):
        return render_template('500.html'), 500

    @app.before_request
    def make_session_permanent():
        session.permanent = True
        app.permanent_session_lifetime = timedelta(minutes=5)
        session.modified = True

    @identity_loaded.connect_via(app)
    def on_identity_loaded(sender, identity):
        needs = []

        if identity.id in ('viewer', 'editor', 'admin'):
            needs.append(to_view)

        if identity.id in ('editor', 'admin'):
            needs.append(be_editor)

        if identity.id == 'admin':
            needs.append(be_admin)

        for n in needs:
            identity.provides.add(n)

        # If the authenticated identity is :
        # - 'the_only user' she can sign in
        # - "the_only_editor" she can sign in and edit
        # - "the_only_admin" she can sign in , edit and administrate

    return app
Ejemplo n.º 6
0
              0,
              0,
              1 - float(random.randint(1, 10)) / 100,
              float(random.randint(1, 2)) / 500,
              0.001,
              float(random.randint(1, 2)) / 500
              ]
    img = img.transform(size, Image.PERSPECTIVE, params) # 创建扭曲

    img = img.filter(ImageFilter.EDGE_ENHANCE_MORE) # 滤镜,边界加强(阈值更大)

    return img,strs

csrf = CsrfProtect()
app = Flask(__name__)
csrf.init_app(app)
app.secret_key = os.urandom(30)

class RegisterForm(Form):
    """注册表单"""
    # SECRET_KEY = os.urandom(30)
    username = StringField(u'昵称', validators=[DataRequired(message=u'用户名必填')])
    email = StringField(u'邮箱', validators=[DataRequired(), Email(message=u'邮箱格式不正确')])
    password = PasswordField(u'密码', validators=[DataRequired(), Length(6, 12, message=u'密码长度在6到12为')])
    password1 = PasswordField(u'确认密码', validators=[DataRequired(), Length(6, 12, message=u'密码长度在6到12为'), EqualTo('password', message=u'密码必须一致')])
    verification_code = StringField(u'验证码', validators=[DataRequired(), Length(4, 4, message=u'填写4位验证码')])
    submit = SubmitField(u'注册')

class User(object):
  """docstring for User"""
  def __init__(self, username,password,email):
Ejemplo n.º 7
0
def register_form(app):
    csrf = CsrfProtect()
    csrf.init_app(app)
Ejemplo n.º 8
0
import xmltodict
import uuid
import random
import string
from flask_wtf.csrf import CsrfProtect
csrf = CsrfProtect()

db = SQLAlchemy()
# After defining `db`, import auth models due to
# circular dependency.
from mhn.auth.models import User, Role, ApiKey
user_datastore = SQLAlchemyUserDatastore(db, User, Role)

mhn = Flask(__name__)
mhn.config.from_object('config')
csrf.init_app(mhn)

# Email app setup.
mail = Mail()
mail.init_app(mhn)

# Registering app on db instance.
db.init_app(mhn)

# Setup flask-security for auth.
Security(mhn, user_datastore)

# Registering blueprints.
from mhn.api.views import api
mhn.register_blueprint(api)
Ejemplo n.º 9
0
def setup_csrf():
    # Initiate Flask-WTForms CSRF protection
    csrf = CsrfProtect()
    csrf.init_app(app)
    return None
Ejemplo n.º 10
0
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.cache import Cache
from flask.ext.script import Manager
from flask.ext.migrate import Migrate
from flask_wtf.csrf import CsrfProtect
from flask.ext.themes import setup_themes
from flask.ext.mail import Mail

from config import LOG_DIR

blog = Flask(__name__)
blog.config.from_object('config')

csrf = CsrfProtect()
csrf.init_app(blog)

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)
Ejemplo n.º 11
0
from flask_wtf.csrf import CsrfProtect
from flask import Flask
import config
from app.models import db
from app.views.admin import admin
from app.views.user import user

app = Flask(__name__)
app.config.from_object(config)
mycsrf = CsrfProtect()
mycsrf.init_app(app)
app.register_blueprint(admin, url_prefix='/admin')
app.register_blueprint(user, url_prefix='/user')


@app.route('/')
def homep():
    return 'hello'


if __name__ == '__main__':
    app.run()
Ejemplo n.º 12
0
from flask import Flask, request, session, url_for
from flask import render_template, redirect
from flask_wtf.csrf import CsrfProtect
from connections import get_connection_to
import json
# import traceback
# from PIL import Image
from decorators import login_required

shadowdashapp = Flask(__name__)
shadowdashapp.secret_key = '6wfwef6AqwdwqdSDW67waedccscaQDWD6748wdFD'
shadowdashapp.config['SESSION_TYPE'] = 'filesystem'
shadowdashapp.config[
    'WTF_CSRF_SECRET_KEY'] = 'asdaC34VERV6843CsC#$@d#$@%fewd#22342FWFQE'
csrf = CsrfProtect()
csrf.init_app(shadowdashapp)


@shadowdashapp.route('/')
@login_required
def shadowdash():
    comment_count_query = "SELECT count(*) FROM user"
    try:
        cursor, conn = get_connection_to(db_name='sf')
        comment_count_obj = cursor.execute(comment_count_query)
        if comment_count_obj:
            ((signup_user_count, ), ) = cursor.fetchall()
    except Exception as e:
        pass

    template_dict = {"signup_count": signup_user_count}
Ejemplo n.º 13
0
class Application(Flask):
    def __init__(self,
                 app_config,
                 import_name,
                 static_path=None,
                 static_url_path=None,
                 static_folder='static',
                 template_folder='templates',
                 instance_path=None,
                 instance_relative_config=False):

        from flask.ext.cache import Cache
        from ambry.library import Library
        from ambry.run import get_runconfig

        self._initialized = False
        self.csrf = CsrfProtect()
        self.login_manager = LoginManager()

        super(Application,
              self).__init__(import_name, static_path, static_url_path,
                             static_folder, template_folder, instance_path,
                             instance_relative_config)

        self.config.update(app_config)

        l = Library(get_runconfig(), read_only=True, echo=False)

        self.cache = Cache(config={
            'CACHE_TYPE': 'filesystem',
            'CACHE_DIR': l.filesystem.cache('ui')
        })
        self.cache.init_app(self)

    def __call__(self, environ, start_response):

        if not self._initialized:
            from ambry.library import Library
            from ambry.run import get_runconfig

            rc = get_runconfig()
            l = Library(rc, read_only=True, echo=False)

            secret_key = None

            if os.getenv('AMBRY_UI_SECRET'):
                app.logger.info("Using secret_key from env")
                secret_key = os.getenv('AMBRY_UI_SECRET')

            if not secret_key and l.ui_config.secret:
                app.logger.info("Using secret_key from library")
                secret_key = l.ui_config.secret

            if not secret_key:
                from uuid import uuid4
                app.logger.warn(
                    "SECRET_KEY was not set. Setting to a random value")
                secret_key = str(
                    uuid4())  # Must be the same for all worker processes.

            if not self.config['WTF_CSRF_SECRET_KEY']:
                self.config['WTF_CSRF_SECRET_KEY'] = secret_key

            self.config['SECRET_KEY'] = secret_key

            title = os.getenv('AMBRY_UI_TITLE', "Ambry Data Library"),

            if l.ui_config.website_title:
                title = l.ui_config.website_title

            self.config['website_title'] = title

            self.secret_key = secret_key

            self.csrf.init_app(self)

            self.session_interface = ItsdangerousSessionInterface()

            self.login_manager.init_app(app)
            Bootstrap(app)

            self._initialized = True

        return super(Application, self).__call__(environ, start_response)
Ejemplo n.º 14
0
def configure_extensions(app):
    # Flask-WTF
    csrf = CsrfProtect()
    csrf.init_app(app)
Ejemplo n.º 15
0
from flask import Flask
from flask_wtf.csrf import CsrfProtect

csrf = CsrfProtect()

application = Flask(__name__)
csrf.init_app(application)

application.config.from_object('config')

from app.models import Task
from app.controllers import *

if __name__ == '__main__':
    application.run(port=8000)

Ejemplo n.º 16
0
class Application(Flask):

    def __init__(self, app_config, import_name, static_path=None, static_url_path=None, static_folder='static',
                 template_folder='templates', instance_path=None, instance_relative_config=False):

        from flask.ext.cache import Cache
        from ambry.library import Library
        from ambry.run import get_runconfig

        self._initialized = False
        self.csrf = CsrfProtect()
        self.login_manager = LoginManager()

        super(Application, self).__init__(import_name, static_path, static_url_path, static_folder,
                                          template_folder, instance_path, instance_relative_config)

        self.config.update(app_config)


        l = Library(get_runconfig(), read_only=True, echo=False)

        self.cache = Cache(config={'CACHE_TYPE': 'filesystem', 'CACHE_DIR': l.filesystem.cache('ui')})
        self.cache.init_app(self)




    def __call__(self, environ, start_response):

        if not self._initialized:
            from ambry.library import Library
            from ambry.run import get_runconfig

            rc = get_runconfig()
            l = Library(rc, read_only=True, echo=False)

            secret_key = None

            if os.getenv('AMBRY_UI_SECRET'):
                app.logger.info("Using secret_key from env")
                secret_key = os.getenv('AMBRY_UI_SECRET')

            if not secret_key and l.ui_config.secret:
                app.logger.info("Using secret_key from library")
                secret_key = l.ui_config.secret

            if not secret_key:
                from uuid import uuid4
                app.logger.warn("SECRET_KEY was not set. Setting to a random value")
                secret_key = str(uuid4()) # Must be the same for all worker processes.

            if not self.config['WTF_CSRF_SECRET_KEY']:
                self.config['WTF_CSRF_SECRET_KEY'] = secret_key

            self.config['SECRET_KEY'] = secret_key

            title = os.getenv('AMBRY_UI_TITLE', "Ambry Data Library"),

            if l.ui_config.website_title:
                title = l.ui_config.website_title

            self.config['website_title'] = title

            self.secret_key = secret_key

            self.csrf.init_app(self)

            self.session_interface = ItsdangerousSessionInterface()

            self.login_manager.init_app(app)
            Bootstrap(app)


            self._initialized = True

        return super(Application, self).__call__(environ, start_response)
Ejemplo n.º 17
0
class Nereid(Flask):
    """
    ...

    Unlike typical web frameworks and their APIs, nereid depends more on
    configuration and not direct python modules written along the APIs
    Most of the functional code will remain on the modules installed on
    Tryton, and the database configurations.

    ...

    """
    #: The class that is used for request objects.  See
    #: :class:`~nereid.wrappers.Request`
    #: for more information.
    request_class = Request

    #: The class that is used for response objects.  See
    #: :class:`~nereid.wrappers.Response` for more information.
    response_class = Response

    #: The rule object to use for URL rules created.  This is used by
    #: :meth:`add_url_rule`.  Defaults to :class:`nereid.routing.Rule`.
    #:
    #: .. versionadded:: 3.2.0.9
    url_rule_class = Rule

    #: the session interface to use.  By default an instance of
    #: :class:`~nereid.session.NereidSessionInterface` is used here.
    session_interface = NereidSessionInterface()

    #: An internal attribute to hold the Tryton model pool to avoid being
    #: initialised at every request as it is quite expensive to do so.
    #: To access the pool from modules, use the :meth:`pool`
    _pool = None

    #: The attribute holds a connection to the database backend.
    _database = None

    #: Configuration file for Tryton. The path to the configuration file
    #: can be specified and will be loaded when the application is
    #: initialised
    tryton_configfile = ConfigAttribute('TRYTON_CONFIG')

    #: The location where the translations of the template are stored
    translations_path = ConfigAttribute('TRANSLATIONS_PATH')

    #: The name of the database to connect to on initialisation
    database_name = ConfigAttribute('DATABASE_NAME')

    #: The default timeout to use if the timeout is not explicitly
    #: specified in the set or set many argument
    cache_default_timeout = ConfigAttribute('CACHE_DEFAULT_TIMEOUT')

    #: the maximum number of items the cache stores before it starts
    #: deleting some items.
    #: Applies for: SimpleCache, FileSystemCache
    cache_threshold = ConfigAttribute('CACHE_THRESHOLD')

    #: a prefix that is added before all keys. This makes it possible
    #: to use the same memcached server for different applications.
    #: Applies for: MecachedCache, GAEMemcachedCache
    #: If key_prefix is none the value of site is used as key
    cache_key_prefix = ConfigAttribute('CACHE_KEY_PREFIX')

    #: a list or tuple of server addresses or alternatively a
    #: `memcache.Client` or a compatible client.
    cache_memcached_servers = ConfigAttribute('CACHE_MEMCACHED_SERVERS')

    #: The directory where cache files are stored if FileSystemCache is used
    cache_dir = ConfigAttribute('CACHE_DIR')

    #: The type of cache to use. The type must be a full specification of
    #: the module so that an import can be made. Examples for werkzeug
    #: backends are given below
    #:
    #:  NullCache - werkzeug.contrib.cache.NullCache (default)
    #:  SimpleCache - werkzeug.contrib.cache.SimpleCache
    #:  MemcachedCache - werkzeug.contrib.cache.MemcachedCache
    #:  GAEMemcachedCache -  werkzeug.contrib.cache.GAEMemcachedCache
    #:  FileSystemCache - werkzeug.contrib.cache.FileSystemCache
    cache_type = ConfigAttribute('CACHE_TYPE')

    #: If a custom cache backend unknown to Nereid is used, then
    #: the arguments that are needed for the initialisation
    #: of the cache could be passed here as a `dict`
    cache_init_kwargs = ConfigAttribute('CACHE_INIT_KWARGS')

    #: Load the template eagerly. This would render the template
    #: immediately and still return a LazyRenderer. This is useful
    #: in debugging issues that may be hard to debug with lazy rendering
    eager_template_render = ConfigAttribute('EAGER_TEMPLATE_RENDER')

    #: boolean attribute to indicate if the initialisation of backend
    #: connection and other nereid support features are loaded. The
    #: application can work only after the initialisation is done.
    #: It is not advisable to set this manually, instead call the
    #: :meth:`initialise`
    initialised = False

    #: Prefix the name of the website to the template name sutomatically
    #: This feature would be deprecated in future in lieu of writing
    #: Jinja2 Loaders which could offer this behavior. This is set to False
    #: by default. For backward compatibility of loading templates from
    #: a template folder which has website names as subfolders, set this
    #: to True
    #:
    #: .. versionadded:: 2.8.0.4
    template_prefix_website_name = ConfigAttribute(
        'TEMPLATE_PREFIX_WEBSITE_NAME'
    )

    #: Time in seconds for which the token is valid.
    token_validity_duration = ConfigAttribute(
        'TOKEN_VALIDITY_DURATION'
    )

    def __init__(self, **config):
        """
        The import_name is forced into `Nereid`
        """
        super(Nereid, self).__init__('nereid', **config)

        # Update the defaults for config attributes introduced by nereid
        self.config.update({
            'TRYTON_CONFIG': None,
            'TEMPLATE_PREFIX_WEBSITE_NAME': True,
            'TOKEN_VALIDITY_DURATION': 60 * 60,

            'CACHE_TYPE': 'werkzeug.contrib.cache.NullCache',
            'CACHE_DEFAULT_TIMEOUT': 300,
            'CACHE_THRESHOLD': 500,
            'CACHE_INIT_KWARGS': {},
            'CACHE_KEY_PREFIX': '',

            'EAGER_TEMPLATE_RENDER': False,
        })

    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 = CsrfProtect()
        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 get_urls(self):
        """
        Return the URL rules for routes formed by decorating methods with the
        :func:`~nereid.helpers.route` decorator.

        This method goes through all the models and their methods in the pool
        of the loaded database and looks for the `_url_rules` attribute in
        them. If there are URLs defined, it is added to the url map.
        """
        rules = []
        models = Pool._pool[self.database_name]['model']

        for model_name, model in models.iteritems():
            for f_name, f in inspect.getmembers(
                    model, predicate=inspect.ismethod):

                if not hasattr(f, '_url_rules'):
                    continue

                for rule in f._url_rules:
                    rules.append(
                        self.url_rule_class(
                            rule[0],
                            endpoint='.'.join([model_name, f_name]),
                            **rule[1]
                        )
                    )

        return rules

    @root_transaction_if_required
    def get_context_processors(self):
        """
        Returns the method object which wraps context processor methods
        formed by decorating methods with the
        :func:`~nereid.helpers.context_processor` decorator.

        This method goes through all the models and their methods in the pool
        of the loaded database and looks for the `_context_processor` attribute
        in them and adds to context_processor dict.
        """
        context_processors = {}
        models = Pool._pool[self.database_name]['model']

        for model_name, model in models.iteritems():
            for f_name, f in inspect.getmembers(
                    model, predicate=inspect.ismethod):

                if hasattr(f, '_context_processor'):
                    ctx_proc_as_func = getattr(Pool().get(model_name), f_name)
                    context_processors[ctx_proc_as_func.func_name] = \
                        ctx_proc_as_func

        def get_ctx():
            """Returns dictionary having method name in keys and method object
            in values.
            """
            return context_processors

        return get_ctx

    @root_transaction_if_required
    def get_template_filters(self):
        """
        Returns a list of name, function pairs for template filters registered
        in the models using :func:`~nereid.helpers.template_filter` decorator.
        """
        models = Pool._pool[self.database_name]['model']
        filters = []

        for model_name, model in models.iteritems():
            for f_name, f in inspect.getmembers(
                    model, predicate=inspect.ismethod):

                if hasattr(f, '_template_filter'):
                    filter = getattr(Pool().get(model_name), f_name)
                    filters.append((filter.func_name, filter))

        return filters

    def load_cache(self):
        """
        Load the cache and assign the Cache interface to
        """
        BackendClass = import_string(self.cache_type)

        if self.cache_type == 'werkzeug.contrib.cache.NullCache':
            self.cache = BackendClass(self.cache_default_timeout)
        elif self.cache_type == 'werkzeug.contrib.cache.SimpleCache':
            self.cache = BackendClass(
                self.cache_threshold, self.cache_default_timeout)
        elif self.cache_type == 'werkzeug.contrib.cache.MemcachedCache':
            self.cache = BackendClass(
                self.cache_memcached_servers,
                self.cache_default_timeout,
                self.cache_key_prefix)
        elif self.cache_type == 'werkzeug.contrib.cache.GAEMemcachedCache':
            self.cache = BackendClass(
                self.cache_default_timeout,
                self.cache_key_prefix)
        elif self.cache_type == 'werkzeug.contrib.cache.FileSystemCache':
            self.cache = BackendClass(
                self.cache_dir,
                self.cache_threshold,
                self.cache_default_timeout)
        else:
            self.cache = BackendClass(**self.cache_init_kwargs)

    def load_backend(self):
        """
        This method loads the configuration file if specified and
        also connects to the backend, initialising the pool on the go
        """
        if self.tryton_configfile is not None:
            warnings.warn(DeprecationWarning(
                'TRYTON_CONFIG configuration will be deprecated in future.'
            ))
            config.update_etc(self.tryton_configfile)

        register_classes()

        # Load and initialise pool
        Database = backend.get('Database')
        self._database = Database(self.database_name).connect()
        self._pool = Pool(self.database_name)
        self._pool.init()

    @property
    def pool(self):
        """
        A proxy to the _pool
        """
        return self._pool

    @property
    def database(self):
        """
        Return connection to Database backend of tryton
        """
        return self._database

    def request_context(self, environ):
        return RequestContext(self, environ)

    @root_transaction_if_required
    def create_url_adapter(self, request):
        """Creates a URL adapter for the given request.  The URL adapter
        is created at a point where the request context is not yet set up
        so the request is passed explicitly.

        """
        if request is not None:

            Website = Pool().get('nereid.website')

            website = Website.get_from_host(request.host)
            rv = website.get_url_adapter(self).bind_to_environ(
                request.environ,
                server_name=self.config['SERVER_NAME']
            )
            return rv

    def dispatch_request(self):
        """
        Does the request dispatching.  Matches the URL and returns the
        return value of the view or error handler.  This does not have to
        be a response object.
        """
        DatabaseOperationalError = backend.get('DatabaseOperationalError')

        req = _request_ctx_stack.top.request
        if req.routing_exception is not None:
            self.raise_routing_exception(req)

        rule = req.url_rule
        # if we provide automatic options for this URL and the
        # request came with the OPTIONS method, reply automatically
        if getattr(rule, 'provide_automatic_options', False) \
           and req.method == 'OPTIONS':
            return self.make_default_options_response()

        with Transaction().start(self.database_name, 0):
            Cache.clean(self.database_name)
            Cache.resets(self.database_name)

        with Transaction().start(self.database_name, 0, readonly=True):
            Website = Pool().get('nereid.website')
            website = Website.get_from_host(req.host)

            user, company = website.application_user.id, website.company.id

        for count in range(int(config.get('database', 'retry')), -1, -1):
            with Transaction().start(
                    self.database_name, user,
                    context={'company': company},
                    readonly=rule.is_readonly) as txn:
                try:
                    transaction_start.send(self)
                    rv = self._dispatch_request(req)
                    txn.cursor.commit()
                except DatabaseOperationalError:
                    # Strict transaction handling may cause this.
                    # Rollback and Retry the whole transaction if within
                    # max retries, or raise exception and quit.
                    txn.cursor.rollback()
                    if count:
                        continue
                    raise
                except Exception:
                    # Rollback and raise any other exception
                    txn.cursor.rollback()
                    raise
                else:
                    return rv
                finally:
                    transaction_stop.send(self)

    def _dispatch_request(self, req):
        """
        Implement the nereid specific _dispatch
        """

        language = 'en_US'
        if req.nereid_website:
            # If this is a request specific to a website
            # then take the locale from the website
            language = req.nereid_locale.language.code

        with Transaction().set_context(language=language):

            # pop locale if specified in the view_args
            req.view_args.pop('locale', None)

            # otherwise dispatch to the handler for that endpoint
            if req.url_rule.endpoint in self.view_functions:
                meth = self.view_functions[req.url_rule.endpoint]
            else:
                model, method = req.url_rule.endpoint.rsplit('.', 1)
                meth = getattr(Pool().get(model), method)

            if not hasattr(meth, 'im_self') or meth.im_self:
                # static or class method
                result = meth(**req.view_args)
            else:
                # instance method, extract active_id from the url
                # arguments and pass the model instance as first argument
                model = Pool().get(req.url_rule.endpoint.rsplit('.', 1)[0])
                i = model(req.view_args.pop('active_id'))
                try:
                    i.rec_name
                except UserError:
                    # The record may not exist anymore which results in
                    # a read error
                    current_app.logger.debug(
                        "Record %s doesn't exist anymore." % i
                    )
                    abort(404)
                result = meth(i, **req.view_args)

            if isinstance(result, LazyRenderer):
                result = (
                    unicode(result), result.status, result.headers
                )

            return result

    def create_jinja_environment(self):
        """
        Extend the default jinja environment that is created. Also
        the environment returned here should be specific to the current
        website.
        """
        rv = super(Nereid, self).create_jinja_environment()

        # Add the custom extensions specific to nereid
        rv.add_extension('jinja2.ext.i18n')
        rv.add_extension('nereid.templating.FragmentCacheExtension')

        rv.filters.update(**NEREID_TEMPLATE_FILTERS)

        # add the locale sensitive url_for of nereid
        rv.globals.update(url_for=url_for)

        if self.cache:
            # Setup the bytecode cache
            rv.bytecode_cache = MemcachedBytecodeCache(self.cache)
            # Setup for fragmented caching
            rv.fragment_cache = self.cache
            rv.fragment_cache_prefix = self.cache_key_prefix + "-frag-"

        # Install the gettext callables
        from .contrib.locale import TrytonTranslations
        translations = TrytonTranslations(module=None, ttype='nereid_template')
        rv.install_gettext_callables(
            translations.gettext, translations.ngettext
        )
        return rv

    @locked_cached_property
    def jinja_loader(self):
        """
        Creates the loader for the Jinja2 Environment
        """
        return ModuleTemplateLoader(
            self.database_name, searchpath=self.template_folder,
        )

    def select_jinja_autoescape(self, filename):
        """
        Returns `True` if autoescaping should be active for the given
        template name.
        """
        if filename is None:
            return False
        if filename.endswith(('.jinja',)):
            return True
        return super(Nereid, self).select_jinja_autoescape(filename)
Ejemplo n.º 18
0
from flask.ext.login import LoginManager
from flask.ext.cache import Cache
from flask.ext.script import Manager
from flask.ext.migrate import Migrate
from flask_wtf.csrf import CsrfProtect
from flask.ext.themes import setup_themes
from flask.ext.mail import Mail

from config import LOG_DIR


blog = Flask(__name__)
blog.config.from_object('config')

csrf = CsrfProtect()
csrf.init_app(blog)

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)
'''邮件'''
Ejemplo n.º 19
0
def register_form(app):
    from flask_wtf.csrf import CsrfProtect
    csrf = CsrfProtect()
    csrf.init_app(app)
Ejemplo n.º 20
0
import uuid
import random
import string
from flask_wtf.csrf import CsrfProtect
csrf = CsrfProtect()

db = SQLAlchemy()
# After defining `db`, import auth models due to
# circular dependency.
from mhn.auth.models import User, Role, ApiKey
user_datastore = SQLAlchemyUserDatastore(db, User, Role)


mhn = Flask(__name__)
mhn.config.from_object('config')
csrf.init_app(mhn)

# Email app setup.
mail = Mail()
mail.init_app(mhn)

# Registering app on db instance.
db.init_app(mhn)

# Setup flask-security for auth.
Security(mhn, user_datastore)

# Registering blueprints.
from mhn.api.views import api
mhn.register_blueprint(api)
Ejemplo n.º 21
0
def register_form(app):
    from flask_wtf.csrf import CsrfProtect
    csrf = CsrfProtect()
    csrf.init_app(app)
Ejemplo n.º 22
0
def register_form(app):
    csrf = CsrfProtect()
    csrf.init_app(app)
Ejemplo n.º 23
0
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_wtf.csrf import CsrfProtect

myapp = Flask(__name__)
myapp.config.from_object('config.ProductionConfig')
db = SQLAlchemy(myapp)
lm = LoginManager()
lm.init_app(myapp)
csrf = CsrfProtect()
csrf.init_app(myapp)

from app import views, models, api, adminviews
Ejemplo n.º 24
0
class Nereid(Flask):
    """
    ...

    Unlike typical web frameworks and their APIs, nereid depends more on
    configuration and not direct python modules written along the APIs
    Most of the functional code will remain on the modules installed on
    Tryton, and the database configurations.

    ...

    """
    #: The class that is used for request objects.  See
    #: :class:`~nereid.wrappers.Request`
    #: for more information.
    request_class = Request

    #: The class that is used for response objects.  See
    #: :class:`~nereid.wrappers.Response` for more information.
    response_class = Response

    #: the session interface to use.  By default an instance of
    #: :class:`~nereid.session.NereidSessionInterface` is used here.
    session_interface = NereidSessionInterface()

    #: An internal attribute to hold the Tryton model pool to avoid being
    #: initialised at every request as it is quite expensive to do so.
    #: To access the pool from modules, use the :meth:`pool`
    _pool = None

    #: The attribute holds a connection to the database backend.
    _database = None

    #: Configuration file for Tryton. The path to the configuration file
    #: can be specified and will be loaded when the application is
    #: initialised
    tryton_configfile = ConfigAttribute('TRYTON_CONFIG')

    #: The location where the translations of the template are stored
    translations_path = ConfigAttribute('TRANSLATIONS_PATH')

    #: The name of the database to connect to on initialisation
    database_name = ConfigAttribute('DATABASE_NAME')

    #: The default timeout to use if the timeout is not explicitly
    #: specified in the set or set many argument
    cache_default_timeout = ConfigAttribute('CACHE_DEFAULT_TIMEOUT')

    #: the maximum number of items the cache stores before it starts
    #: deleting some items.
    #: Applies for: SimpleCache, FileSystemCache
    cache_threshold = ConfigAttribute('CACHE_THRESHOLD')

    #: a prefix that is added before all keys. This makes it possible
    #: to use the same memcached server for different applications.
    #: Applies for: MecachedCache, GAEMemcachedCache
    #: If key_prefix is none the value of site is used as key
    cache_key_prefix = ConfigAttribute('CACHE_KEY_PREFIX')

    #: a list or tuple of server addresses or alternatively a
    #: `memcache.Client` or a compatible client.
    cache_memcached_servers = ConfigAttribute('CACHE_MEMCACHED_SERVERS')

    #: The directory where cache files are stored if FileSystemCache is used
    cache_dir = ConfigAttribute('CACHE_DIR')

    #: The type of cache to use. The type must be a full specification of
    #: the module so that an import can be made. Examples for werkzeug
    #: backends are given below
    #:
    #:  NullCache - werkzeug.contrib.cache.NullCache (default)
    #:  SimpleCache - werkzeug.contrib.cache.SimpleCache
    #:  MemcachedCache - werkzeug.contrib.cache.MemcachedCache
    #:  GAEMemcachedCache -  werkzeug.contrib.cache.GAEMemcachedCache
    #:  FileSystemCache - werkzeug.contrib.cache.FileSystemCache
    cache_type = ConfigAttribute('CACHE_TYPE')

    #: If a custom cache backend unknown to Nereid is used, then
    #: the arguments that are needed for the initialisation
    #: of the cache could be passed here as a `dict`
    cache_init_kwargs = ConfigAttribute('CACHE_INIT_KWARGS')

    #: boolean attribute to indicate if the initialisation of backend
    #: connection and other nereid support features are loaded. The
    #: application can work only after the initialisation is done.
    #: It is not advisable to set this manually, instead call the
    #: :meth:`initialise`
    initialised = False

    #: Prefix the name of the website to the template name sutomatically
    #: This feature would be deprecated in future in lieu of writing
    #: Jinja2 Loaders which could offer this behavior. This is set to False
    #: by default. For backward compatibility of loading templates from
    #: a template folder which has website names as subfolders, set this
    #: to True
    #:
    #: .. versionadded:: 2.8.0.4
    template_prefix_website_name = ConfigAttribute(
        'TEMPLATE_PREFIX_WEBSITE_NAME'
    )

    #: Time in seconds for which the token is valid.
    token_validity_duration = ConfigAttribute(
        'TOKEN_VALIDITY_DURATION'
    )

    def __init__(self, **config):
        """
        The import_name is forced into `Nereid`
        """
        super(Nereid, self).__init__('nereid', **config)

        # Update the defaults for config attributes introduced by nereid
        self.config.update({
            'TRYTON_CONFIG': None,
            'TEMPLATE_PREFIX_WEBSITE_NAME': True,
            'TOKEN_VALIDITY_DURATION': 60 * 60,

            'CACHE_TYPE': 'werkzeug.contrib.cache.NullCache',
            'CACHE_DEFAULT_TIMEOUT': 300,
            'CACHE_THRESHOLD': 500,
            'CACHE_INIT_KWARGS': {},
            'CACHE_KEY_PREFIX': '',
        })

    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 = CsrfProtect()
        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
        )

        # Finally set the initialised attribute
        self.initialised = True

    def get_urls(self):
        """
        Return the URL rules for routes formed by decorating methods with the
        :func:`~nereid.helpers.route` decorator.

        This method goes through all the models and their methods in the pool
        of the loaded database and looks for the `_url_rules` attribute in
        them. If there are URLs defined, it is added to the url map.
        """
        rules = []
        models = Pool._pool[self.database_name]['model']

        for model_name, model in models.iteritems():
            for f_name, f in inspect.getmembers(
                    model, predicate=inspect.ismethod):

                if not hasattr(f, '_url_rules'):
                    continue

                for rule in f._url_rules:
                    rules.append(
                        self.url_rule_class(
                            rule[0],
                            endpoint='.'.join([model_name, f_name]),
                            **rule[1]
                        )
                    )

        return rules

    @root_transaction_if_required
    def get_context_processors(self):
        """
        Returns the method object which wraps context processor methods
        formed by decorating methods with the
        :func:`~nereid.helpers.context_processor` decorator.

        This method goes through all the models and their methods in the pool
        of the loaded database and looks for the `_context_processor` attribute
        in them and adds to context_processor dict.
        """
        context_processors = {}
        models = Pool._pool[self.database_name]['model']

        for model_name, model in models.iteritems():
            for f_name, f in inspect.getmembers(
                    model, predicate=inspect.ismethod):

                if hasattr(f, '_context_processor'):
                    ctx_proc_as_func = getattr(Pool().get(model_name), f_name)
                    context_processors[ctx_proc_as_func.func_name] = \
                        ctx_proc_as_func

        def get_ctx():
            """Returns dictionary having method name in keys and method object
            in values.
            """
            return context_processors

        return get_ctx

    def load_cache(self):
        """
        Load the cache and assign the Cache interface to
        """
        BackendClass = import_string(self.cache_type)

        if self.cache_type == 'werkzeug.contrib.cache.NullCache':
            self.cache = BackendClass(self.cache_default_timeout)
        elif self.cache_type == 'werkzeug.contrib.cache.SimpleCache':
            self.cache = BackendClass(
                self.cache_threshold, self.cache_default_timeout)
        elif self.cache_type == 'werkzeug.contrib.cache.MemcachedCache':
            self.cache = BackendClass(
                self.cache_memcached_servers,
                self.cache_default_timeout,
                self.cache_key_prefix)
        elif self.cache_type == 'werkzeug.contrib.cache.GAEMemcachedCache':
            self.cache = BackendClass(
                self.cache_default_timeout,
                self.cache_key_prefix)
        elif self.cache_type == 'werkzeug.contrib.cache.FileSystemCache':
            self.cache = BackendClass(
                self.cache_dir,
                self.cache_threshold,
                self.cache_default_timeout)
        else:
            self.cache = BackendClass(**self.cache_init_kwargs)

    def load_backend(self):
        """
        This method loads the configuration file if specified and
        also connects to the backend, initialising the pool on the go
        """
        if self.tryton_configfile is not None:
            warnings.warn(DeprecationWarning(
                'TRYTON_CONFIG configuration will be deprecated in future.'
            ))
            CONFIG.update_etc(self.tryton_configfile)

        register_classes()

        # Load and initialise pool
        Database = backend.get('Database')
        self._database = Database(self.database_name).connect()
        self._pool = Pool(self.database_name)
        self._pool.init()

    @property
    def pool(self):
        """
        A proxy to the _pool
        """
        return self._pool

    @property
    def database(self):
        """
        Return connection to Database backend of tryton
        """
        return self._database

    def request_context(self, environ):
        return RequestContext(self, environ)

    @root_transaction_if_required
    def create_url_adapter(self, request):
        """Creates a URL adapter for the given request.  The URL adapter
        is created at a point where the request context is not yet set up
        so the request is passed explicitly.

        """
        if request is not None:

            Website = Pool().get('nereid.website')

            website = Website.get_from_host(request.host)
            rv = website.get_url_adapter(self).bind_to_environ(
                request.environ,
                server_name=self.config['SERVER_NAME']
            )
            return rv

    def dispatch_request(self):
        """
        Does the request dispatching.  Matches the URL and returns the
        return value of the view or error handler.  This does not have to
        be a response object.
        """
        DatabaseOperationalError = backend.get('DatabaseOperationalError')

        req = _request_ctx_stack.top.request
        if req.routing_exception is not None:
            self.raise_routing_exception(req)

        rule = req.url_rule
        # if we provide automatic options for this URL and the
        # request came with the OPTIONS method, reply automatically
        if getattr(rule, 'provide_automatic_options', False) \
           and req.method == 'OPTIONS':
            return self.make_default_options_response()

        Cache.clean(self.database_name)

        with Transaction().start(self.database_name, 0, readonly=True):
            Website = Pool().get('nereid.website')
            website = Website.get_from_host(req.host)

            user, company = website.application_user.id, website.company.id

        for count in range(int(CONFIG['retry']), -1, -1):
            with Transaction().start(
                    self.database_name,
                    user, context={'company': company}) as txn:
                try:
                    transaction_start.send(self)
                    rv = self._dispatch_request(req)
                    txn.cursor.commit()
                except DatabaseOperationalError:
                    # Strict transaction handling may cause this.
                    # Rollback and Retry the whole transaction if within
                    # max retries, or raise exception and quit.
                    txn.cursor.rollback()
                    if count:
                        continue
                    raise
                except Exception:
                    # Rollback and raise any other exception
                    txn.cursor.rollback()
                    raise
                else:
                    return rv
                finally:
                    transaction_stop.send(self)

    def _dispatch_request(self, req):
        """
        Implement the nereid specific _dispatch
        """

        language = 'en_US'
        if req.nereid_website:
            # If this is a request specific to a website
            # then take the locale from the website
            language = req.nereid_locale.language.code

        with Transaction().set_context(language=language):

            # pop locale if specified in the view_args
            req.view_args.pop('locale', None)

            # otherwise dispatch to the handler for that endpoint
            if req.url_rule.endpoint in self.view_functions:
                meth = self.view_functions[req.url_rule.endpoint]
            else:
                model, method = req.url_rule.endpoint.rsplit('.', 1)
                meth = getattr(Pool().get(model), method)

            if not hasattr(meth, 'im_self') or meth.im_self:
                # static or class method
                result = meth(**req.view_args)
            else:
                # instance method, extract active_id from the url
                # arguments and pass the model instance as first argument
                model = Pool().get(req.url_rule.endpoint.rsplit('.', 1)[0])
                i = model(req.view_args.pop('active_id'))
                result = meth(i, **req.view_args)

            if isinstance(result, LazyRenderer):
                result = (
                    unicode(result), result.status, result.headers
                )

            return result

    def create_jinja_environment(self):
        """
        Extend the default jinja environment that is created. Also
        the environment returned here should be specific to the current
        website.
        """
        rv = super(Nereid, self).create_jinja_environment()

        # Add the custom extensions specific to nereid
        rv.add_extension('jinja2.ext.i18n')
        rv.add_extension('nereid.templating.FragmentCacheExtension')

        rv.filters.update(**NEREID_TEMPLATE_FILTERS)

        # add the locale sensitive url_for of nereid
        rv.globals.update(url_for=url_for)

        if self.cache:
            # Setup the bytecode cache
            rv.bytecode_cache = MemcachedBytecodeCache(self.cache)
            # Setup for fragmented caching
            rv.fragment_cache = self.cache
            rv.fragment_cache_prefix = self.cache_key_prefix + "-frag-"

        # Install the gettext callables
        from .contrib.locale import TrytonTranslations
        translations = TrytonTranslations(module=None, ttype='nereid_template')
        rv.install_gettext_callables(
            translations.gettext, translations.ngettext
        )
        return rv

    @locked_cached_property
    def jinja_loader(self):
        """
        Creates the loader for the Jinja2 Environment
        """
        return ModuleTemplateLoader(
            self.database_name, searchpath=self.template_folder,
        )

    def select_jinja_autoescape(self, filename):
        """
        Returns `True` if autoescaping should be active for the given
        template name.
        """
        if filename is None:
            return False
        if filename.endswith(('.jinja',)):
            return True
        return super(Nereid, self).select_jinja_autoescape(filename)
Ejemplo n.º 25
0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CsrfProtect
from photolog.filters import jinja2_nice_datetime


photolog = Flask(__name__, static_folder='../public')
photolog.config.from_object('photolog.config')
csrf = CsrfProtect()
csrf.init_app(photolog)
db = SQLAlchemy(photolog)

photolog.jinja_env.filters['nice_datetime'] = jinja2_nice_datetime

from photolog import models, views
db.create_all()
Ejemplo n.º 26
0
class Environment(object):
    _instance = None

    @classmethod
    def instance(cls, config=None, test=False, test_db_uri=None):
        if cls._instance is None:
            cls._instance = cls(config, test, test_db_uri)
        return cls._instance

    def __init__(self, config, test, test_db_uri):
        if self.__class__._instance is not None:
            raise EnvironmentUninitializedError()

        self.__s3_conn = None
        self.__fixtures = None
        self.__db = SQLAlchemy()

        for path in CONFIG_PATH_LOCATIONS:
            sys.path.append(path)

        if config is None:
            # None will be passed by manage.py.
            # A default param value will get overwritten, so this is implemented here.
            config = 'splice.default_settings.DefaultConfig'

        if not test:
            # load config from environment if it exists
            config = os.environ.get('SPLICE_SETTINGS', config)

        config_obj = load_config_obj(config)

        if test:
            config_obj.ENVIRONMENT = 'test'
            config_obj.SQLALCHEMY_DATABASE_URI = test_db_uri
            config_obj.SQLALCHEMY_BINDS = {'stats': test_db_uri}
            config_obj.SQLALCHEMY_POOL_SIZE = None
            config_obj.SQLALCHEMY_POOL_TIMEOUT = None
            self.log = Mock()
            self.__s3_conn = Mock()
        else:
            self.__loggers = self.__setup_loggers(config_obj)

        self.config = config_obj
        app = Flask('splice')
        app.config.from_object(config)

        if app.config['ENVIRONMENT'] not in app.config['STATIC_ENABLED_ENVS']:
            app.config['STATIC_FOLDER'] = None
        self.__application = app

        if not test:  # pragma: no cover
            self.csrf = CsrfProtect()
            self.csrf.init_app(app)

        # A hack to keep the sqlalchemy binds state. Flask-SQLAlchemy strips it out
        sqlalchemy_binds = app.config.get('SQLALCHEMY_BINDS')
        self.db.init_app(self.__application)
        app.config.SQLALCHEMY_BINDS = sqlalchemy_binds
        Migrate(self.__application, self.db)

    @property
    def is_debug(self):
        return self.config.DEBUG

    @property
    def is_test(self):
        return self.config.ENVIRONMENT == "test"

    @property
    def is_development(self):
        return self.config.ENVIRONMENT == "dev"

    @property
    def is_production(self):
        return self.config.ENVIRONMENT == "prod"

    @property
    def application(self):
        return self.__application

    @property
    def db(self):
        return self.__db

    @property
    def s3(self):
        if not self.__s3_conn:
            if self.config.AWS:
                self.__s3_conn = boto.connect_s3(self.config.AWS["key"],
                                                 self.config.AWS["secret_key"])
            else:
                self.__s3_conn = boto.connect_s3()

        return self.__s3_conn

    @property
    def fixtures(self):
        if not self.__fixtures:
            self._load_fixtures()
        return self.__fixtures

    def _load_locales(self):
        with open(self.config.LOCALE_FIXTURE_PATH, 'r') as infile:
            data = [line.strip() for line in infile]
        data.extend(["en-US", "ERROR"])
        return data

    def _load_countries(self):
        import csv
        with open(self.config.COUNTRY_FIXTURE_PATH, 'rb') as f:
            reader = csv.reader(f)
            data = [line for line in reader]
        data.append(("ERROR", "ERROR"))
        data.append(("STAR", "All Countries"))
        return data

    def _load_fixtures(self):
        locales = set(self._load_locales())

        countries = {}
        for iso_code, name in self._load_countries():
            countries[iso_code] = name

        self.__fixtures = {
            "locales": locales,
            "countries": countries,
        }

    def __setup_loggers(self, config):  # pragma: no cover
        """
        Setup and return loggers
        """
        loggers = {}
        for name, settings in config.LOG_HANDLERS.iteritems():
            internal_name = "splice-{0}".format(name)

            handler = settings['handler'](**settings['params'])
            if 'format' in settings:
                handler.setFormatter(logging.Formatter(settings['format']))

            logger = logging.getLogger(internal_name)
            logger.setLevel(settings['level'])
            logger.addHandler(handler)
            loggers[internal_name] = logger

        return loggers

    def log(self, msg, name='console', **kwargs):  # pragma: no cover
        """
        Log messages via defined outputs
        """
        level = kwargs.pop('level', logging.INFO)
        internal_name = "splice-{0}".format(name)
        loggers = {self.__loggers.get(internal_name)}

        if self.is_debug:
            # include the console logger in development mode
            loggers.add(self.__loggers['splice-console'])

        for logger in loggers:
            if logging.handlers.SysLogHandler in logger.handlers:
                # in syslog, message starts after first colon
                logger_msg = ":{0}".format(msg)
            else:
                logger_msg = msg
            logger.log(level, logger_msg, **kwargs)
Ejemplo n.º 27
0
def create_app(config=None):
    """ config should be a python file """
    from pathlib import Path

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

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

    from flask_wtf.csrf import CsrfProtect

    from flask_assets import (Environment, Bundle)

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

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

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

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

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

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

    # Flask.sqlalchemy
    db.init_app(app)

    load_blueprints(app)

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

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

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

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

    return app
Ejemplo n.º 28
0
    app.logger.addHandler(StreamHandler())
else:
    handler = StreamHandler(stream=sys.stderr)

handler.setFormatter(
    Formatter('%(asctime)s %(levelname)s: %(message)s '
              '[in %(pathname)s:%(lineno)d]'))
handler.setLevel(app.config.get('LOG_LEVEL'))
app.logger.setLevel(app.config.get('LOG_LEVEL'))
app.logger.addHandler(handler)

### Flask-WTF CSRF Protection ###
from flask_wtf.csrf import CsrfProtect

csrf = CsrfProtect()
csrf.init_app(app)


@csrf.error_handler
def csrf_error(reason):
    app.logger.debug("CSRF ERROR: {}".format(reason))
    return render_template('csrf_error.json', reason=reason), 400


### Flask-Login ###
from flask.ext.login import LoginManager
login_manager = LoginManager()
login_manager.init_app(app)

from security_monkey.datastore import User, Role
Ejemplo n.º 29
0
from db import user

app = Flask(__name__)
login_manager = LoginManager()
app.config.from_object('config')
login_manager.init_app(app)
login_manager.login_view = 'login'

mail = Mail(app)

app.debug = True
app.use_reloader = True

crsf = CsrfProtect()
crsf.init_app(app)


# visible  web pages
@app.route("/forgotpassword", methods=["GET", "POST"])
def forgotpassword():
    form = auth.forms.ForgotPasswordForm()
    if request.method == "GET":
        return render_template("forgotpassword.html", form=form)
    if not form.validate():
        return render_template("forgotpassword.html", form=form)
    else:
        password = form.newpassword
        msg = Message("New Password", 
                sender=config.MAIL_USERNAME,
                recipients=[form.email.data])
Ejemplo n.º 30
0
import json
from flask import Flask, session, request, send_file
from flask import redirect, render_template
from flask import url_for
from flask_wtf.csrf import CsrfProtect
from connections import get_connection
import traceback

from mailer import Mailer

sfapp = Flask(__name__)
sfapp.secret_key = '6wfwef6ASDW676w6QDWD6748wd((FD'
sfapp.config['SESSION_TYPE'] = 'filesystem'
sfapp.config['WTF_CSRF_SECRET_KEY'] = 'asdaDa#$@%fewd#22342FWFQE'
csrf = CsrfProtect()
csrf.init_app(sfapp)


@sfapp.route('/')
def index():
    template_arguments = {
        "user-name": session.get('user_name', None),
        "points": session.get('points', None)
    }
    return render_template('client/index.html', template_data=template_arguments)


@sfapp.route('/collaboration')
def collaboration():
    template_arguments = {
        "user-name": session.get('user_name', None),
Ejemplo n.º 31
0
import json, os, shutil
from flask import Flask, request
from flask import render_template
from flask_wtf.csrf import CsrfProtect
from connections import get_connection_to
import traceback
from PIL import Image

dashapp = Flask(__name__)
dashapp.secret_key = '6wfwef6AqwdwqdSDW676w6QDWD6748wd((FD'
dashapp.config['SESSION_TYPE'] = 'filesystem'
dashapp.config['WTF_CSRF_SECRET_KEY'] = 'asdaDawqdwd#$@%fewd#22342FWFQE'
csrf = CsrfProtect()
csrf.init_app(dashapp)


@dashapp.route('/')
def nsdash():
    comment_count_query = "SELECT count(*) FROM comments"
    query_count_query = "SELECT count(*) FROM query"
    try:
        cursor, conn = get_connection_to(db_name='nsi')
        comment_count_obj = cursor.execute(comment_count_query)
        if comment_count_obj:
            ((comment_count, ), ) = cursor.fetchall()
        query_count_obj = cursor.execute(query_count_query)
        if query_count_obj:
            ((query_count, ), ) = cursor.fetchall()
    except Exception as e:
        pass