Exemple #1
0
def create_app(config_name):
    app.config.from_object(config[config_name])
    db.init_app(app)
    login_manager.init_app(app)
    login_manager.session_protection = 'strong'
    login_manager.login_view = 'admin.login'

    if not app.debug:
        import logging
        from logging import FileHandler, Formatter

        file_handler = FileHandler(Constant.LOG_DIR, encoding='utf8')
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(
            Formatter('[%(asctime)s] %(levelname)s: %(message)s '
                      '[in %(pathname)s:%(lineno)d]'))
        app.logger.addHandler(file_handler)

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

    from admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    patch_request_class(app, size=16 * 1024 * 1024)  # 16MB
    configure_uploads(app, resource_uploader)

    return app
Exemple #2
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    lm.init_app(app)
    api_manager.init_app(app, flask_sqlalchemy_db=db)
    fujs.init_app(app)
    configure_uploads(app, (lectures))
    patch_request_class(app, 8 * 1024 * 1024)        # 16 megabytes

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

    from auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    from institutions import institutions as institutions_blueprint
    app.register_blueprint(institutions_blueprint, url_prefix='/institutions')

    return app
Exemple #3
0
def configure_uploads(app):
    """
    Attach upload sets to the app and initialise uploads.
    """
    flask_configure_uploads(app, profile_pics)
    # Only allow uploads up to 5MiB
    patch_request_class(app, size=(5 * 1024 * 1024))
Exemple #4
0
def create_app(config=None):
    app = Flask(__name__)

    # logger
    init_app_logger(app)

    # config
    app.config.from_object(config)

    # blueprint
    app.register_blueprint(views.home)
    app.register_blueprint(views.post)
    app.register_blueprint(views.member)
    app.register_blueprint(views.admin)

    # database
    db.init_app(app)

    # app context
    init_app_context(app)

    init_jinja_filters(app)

    # flask-login
    configure_login(app)

    # flask-uploads
    configure_uploads(app, (upload_set, ))
    patch_request_class(app)  # default 16M limit

    return app
Exemple #5
0
def setup_attachments(app):
    # max upload size
    patch_request_class(app, 6 * 1024 * 1024)

    # attachment store
    global store
    store = setup_store(app)

    # set for the current thread, useful for debugging
    push_store_context(store)

    # link attachment store implicitly to the request chain
    @app.before_request
    def start_implicit_store_context():
        global pushed
        push_store_context(store)
        pushed = True

    @app.teardown_request
    def stop_implicit_store_context(exception=None):
        global pushed
        if pushed:
            pop_store_context()
            pushed = False
    push_store_context(store)
Exemple #6
0
def create_app(config=None):
    app = Flask(__name__)

    # logger
    init_app_logger(app)

    # config
    app.config.from_object(config)

    # blueprint
    app.register_blueprint(views.home)
    app.register_blueprint(views.post)
    app.register_blueprint(views.member)
    app.register_blueprint(views.admin)

    # database
    db.init_app(app)

    # app context
    init_app_context(app)

    init_jinja_filters(app)

    # flask-login
    configure_login(app)

    # flask-uploads
    configure_uploads(app, (upload_set, ))
    patch_request_class(app)    # default 16M limit

    return app
def create_app(config_name):
    app.config.from_object(config[config_name])
    db.init_app(app)
    login_manager.init_app(app)
    login_manager.session_protection = 'strong'
    login_manager.login_view = 'admin.login'

    if not app.debug:
        import logging
        from logging import FileHandler, Formatter

        file_handler = FileHandler(Constant.LOG_DIR, encoding='utf8')
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(Formatter(
            '[%(asctime)s] %(levelname)s: %(message)s '
            '[in %(pathname)s:%(lineno)d]'))
        app.logger.addHandler(file_handler)

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

    from admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    patch_request_class(app, size=16*1024*1024) # 16MB
    configure_uploads(app, resource_uploader)

    return app
def configure_uploads(app):
    """
    Attach upload sets to the app and initialise uploads.
    """
    flask_configure_uploads(app, profile_pics)
    # Only allow uploads up to 5MiB
    patch_request_class(app, size=(5 * 1024 * 1024))
Exemple #9
0
def setup_attachments(app):
    # max upload size
    patch_request_class(app, 6 * 1024 * 1024)

    # attachment store
    global store
    store = setup_store(app)

    # set for the current thread, useful for debugging
    push_store_context(store)

    # link attachment store implicitly to the request chain
    @app.before_request
    def start_implicit_store_context():
        global pushed
        push_store_context(store)
        pushed = True

    @app.teardown_request
    def stop_implicit_store_context(exception=None):
        global pushed
        if pushed:
            pop_store_context()
            pushed = False

    push_store_context(store)
Exemple #10
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    lm.init_app(app)
    api_manager.init_app(app, flask_sqlalchemy_db=db)
    fujs.init_app(app)
    configure_uploads(app, (lectures))
    patch_request_class(app, 8 * 1024 * 1024)  # 16 megabytes

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

    from auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    from institutions import institutions as institutions_blueprint
    app.register_blueprint(institutions_blueprint, url_prefix='/institutions')

    return app
Exemple #11
0
def init(app):
    """
    Attach upload sets to the app and initialise uploads.
    """
    for set in UPLOAD_SETS:
        configure_uploads(app, UPLOAD_SETS[set])
    # Allow uploads up to 20MiB
    patch_request_class(app, size=(20 * 1024 * 1024))
Exemple #12
0
def init(app):
    """
    Attach upload sets to the app and initialise uploads.
    """
    for set in UPLOAD_SETS:
        configure_uploads(app, UPLOAD_SETS[set])
    # Allow uploads up to 20MiB
    patch_request_class(app, size=(20 * 1024 * 1024))
Exemple #13
0
def create_app(option):
    app = Flask(__name__)
    config = config_factory.get(option)
    app.config.from_object(config)
    from common import create_jinja_filters, random_pwd

    create_jinja_filters(app)
    from webapp.api import api
    from webapp.client import client
    from webapp.media import media

    app.register_blueprint(client)
    app.register_blueprint(api, url_prefix=Constants.API_V1_URL_PREFIX)
    app.register_blueprint(media, url_prefix=Constants.MEDIA_URL_PREFIX)

    csrf.init_app(app)
    compress.init_app(app)
    gravatar.init_app(app)
    db.init_app(app)
    migrate.init_app(app, db)
    admin.init_app(app)
    mail.init_app(app)
    from models import User, Role
    from webapp.forms import ExtendedRegisterForm

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security.init_app(app, user_datastore, register_form=ExtendedRegisterForm)
    with app.app_context():
        api_manager.init_app(app, flask_sqlalchemy_db=db)

        @app.before_request
        def before_request():
            g.constants = Constants
            g.config = app.config
            g.mode = app.config.get('MODE')

        @app.after_request
        def redirect_if_next(response_class):
            payload = request.args if request.method == 'GET' else request.form
            if 'api_next' in payload:
                if not response_class.status_code == 200:
                    flash(response_class.data)
                    return redirect(request.referrer)
                return redirect(payload.get('api_next'))
            return response_class

    patch_request_class(app, Constants.MAX_FILE_SIZE)

    from webapp.common import make_json_error

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

    configure_uploads(app, (user_images, ))

    return app
Exemple #14
0
def create_app(option):
    app = Flask(__name__)
    config = config_factory.get(option)
    app.config.from_object(config)

    # Initialize extensions
    from models import User, Role
    from webapp.forms import ExtendedRegisterForm

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security.init_app(app, user_datastore, register_form=ExtendedRegisterForm)
    csrf.init_app(app)
    db.init_app(app)
    admin.init_app(app)
    babel.init_app(app)
    migrate.init_app(app, db)
    socketio.init_app(app)
    gravatar.init_app(app)
    gmap.init_app(app)

    configure_uploads(app, (user_images,))
    patch_request_class(app, Constants.MAX_FILE_SIZE)

    # Set up API via Flask-Restless
    import webapp.api.views

    with app.app_context():
        api_manager.init_app(app, flask_sqlalchemy_db=db)

        @app.before_request
        def before_request():
            request.x_remote_addr = request.remote_addr
            if 'X-Real-Ip' in request.headers:
                request.x_remote_addr = request.headers.get('X-Real-Ip')
            g.constants = Constants
            g.config = app.config
            g.mode = app.config.get('MODE')

    # Set up client blueprint
    from webapp.client import client

    app.register_blueprint(client)

    from webapp.media import media

    app.register_blueprint(media, url_prefix=Constants.MEDIA_URL_PREFIX)

    from util.common import create_jinja_helpers

    create_jinja_helpers(app)

    from flask.ext.babel import refresh;

    refresh()
    return app
def get_application():
    """Get global application instance.

    :returns: Flask application object."""
    if not hasattr(get_application, "application"):
        application = Flask(__name__)
        application.config.from_pyfile(os.path.join(os.path.dirname(__file__), "config.py"))
        configure_uploads(application, [REPORTS])
        patch_request_class(application, MAX_REPORT_SIZE)

        get_application.application = application
    return get_application.application
Exemple #16
0
def configure_extensions(app):
    """ Load and configure 3rd party flask extensions

    :param app: Application instance
    :type app: Flask
    """

    # flask-mail
    mail.init_app(app)

    # flask-socketio
    socketio.init_app(app)

    # flask-uploads
    from tranny.forms import torrent_file_set
    configure_uploads(app, [torrent_file_set])
    patch_request_class(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 = 'user.login'
    login_manager.refresh_view = 'frontend.reauth'

    from tranny.models import User

    @login_manager.user_loader
    def user_loader(user_id):
        return Session().query(User).filter_by(user_id=user_id).first()

    @login_manager.needs_refresh_handler
    def refresh():
        # do stuff
        confirm_login()
        return True

    @login_manager.unauthorized_handler
    def login_redir():
        return redirect(url_for("user.login"))

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

    login_manager.init_app(app)
Exemple #17
0
def configure_extensions(app):
    """ Load and configure 3rd party flask extensions

    :param app: Application instance
    :type app: Flask
    """

    # flask-mail
    mail.init_app(app)

    # flask-socketio
    socketio.init_app(app)

    # flask-uploads
    from tranny.forms import torrent_file_set
    configure_uploads(app, [torrent_file_set])
    patch_request_class(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 = 'user.login'
    login_manager.refresh_view = 'frontend.reauth'

    from tranny.models import User

    @login_manager.user_loader
    def user_loader(user_id):
        return Session().query(User).filter_by(user_id=user_id).first()

    @login_manager.needs_refresh_handler
    def refresh():
        # do stuff
        confirm_login()
        return True

    @login_manager.unauthorized_handler
    def login_redir():
        return redirect(url_for("user.login"))

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

    login_manager.init_app(app)
Exemple #18
0
def create_app(option):
    app = Flask(__name__)
    config = config_factory.get(option)
    app.config.from_object(config)

    # Initialize extensions
    from models import User, Role

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security.init_app(app, user_datastore)
    admin.init_app(app)
    csrf.init_app(app)
    db.init_app(app)
    migrate.init_app(app, db)
    socketio.init_app(app)
    gravatar.init_app(app)
    babel.init_app(app)
    gmap.init_app(app)

    patch_request_class(app, Constants.MAX_FILE_SIZE)

    with app.app_context():
        @app.before_request
        def before_request():
            request.x_remote_addr = request.remote_addr
            if 'X-Real-Ip' in request.headers:
                request.x_remote_addr = request.headers.get('X-Real-Ip')
            g.constants = Constants
            g.config = app.config
            g.mode = app.config.get('MODE')

        @app.after_request
        def after_request(response):
            signed_in_value = '1' if current_user and current_user.is_authenticated else '0'
            response.set_cookie('signed_in', value=signed_in_value)
            return response

    # Set up client blueprint
    from webapp.client import client

    app.register_blueprint(client)

    from util.common import create_jinja_helpers
    create_jinja_helpers(app)

    return app
Exemple #19
0
def create_app(config_name='default'):
    """
    :param config_name: developtment, production or testing
    :return: flask application

    flask application generator
    """
    app = create_app_min(config_name)

    cors.init_app(app, resources={r"/v1/*": {"origins": "*"}})
    oauth.init_app(app)
    security.init_app(app)
    debug_toolbar.init_app(app)
    mail.init_app(app)
    admin.init_app(app)
    bootstrap.init_app(app)
    thumbnail.init_app(app)

    from flask.ext.uploads import configure_uploads, patch_request_class
    from .modules.foo.uploads import upload_sets

    configure_uploads(app, upload_sets)
    patch_request_class(app)

    from sample_app.core import core as main_blueprint

    app.register_blueprint(main_blueprint)

    from sample_app.modules.posts import post_bp as post_blueprint

    app.register_blueprint(post_blueprint, url_prefix='/posts')

    from sample_app.modules.thingy import mod as foo_blueprint

    app.register_blueprint(foo_blueprint, url_prefix='/thingy')

    from sample_app.core.api_1_0 import api as api_1_0_blueprint

    app.register_blueprint(api_1_0_blueprint, url_prefix='/v1')

    import sample_app.core.admin
    import sample_app.modules.posts.admin
    import sample_app.modules.thingy.admin

    return app
Exemple #20
0
def create_app(config=None):
    app = Flask(__name__)
    app.config.from_object(config)
    db.init_app(app)
    Gemoji.init_app(app)
    themes.init_themes(app)

    configure_modules(app)
    config_error_handlers(app)
    configure_flasklogin(app)
    config_before_request(app)
    # configure_uploads(app, (photos, ))
    patch_request_class(app)    # 16M limit

    CsrfProtect(app)
    configure_identity(app)

    return app
Exemple #21
0
def create_app(config=None):
    app = Flask(__name__)
    app.config.from_object(config)
    db.init_app(app)
    Gemoji.init_app(app)
    themes.init_themes(app)

    configure_modules(app)
    config_error_handlers(app)
    configure_flasklogin(app)
    config_before_request(app)
    # configure_uploads(app, (photos, ))
    patch_request_class(app)  # 16M limit

    CsrfProtect(app)
    configure_identity(app)

    return app
Exemple #22
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    db.init_app(app)
    login_manager.init_app(app)

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

    from admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    from ajax import ajax as ajax_blueprint
    app.register_blueprint(ajax_blueprint, url_prefix='/ajax')

    patch_request_class(app, size=16*1024*1024) # 16MB
    configure_uploads(app, resource_uploader)

    return app
def _configure_uploads(app):
    app.config['FILES_PATH'] = files_path = path(app.instance_path) / 'files'
    app.config['PATH_BACKGROUNDS_KEY'] = path_backgrounds_key = 'backgrounds'
    app.config['PATH_CROP_KEY'] = path_crop_key = 'crops'
    app.config['PATH_CUSTOM_KEY'] = path_custom_key = 'custom_uploads'
    app.config['PATH_LOGOS_KEY'] = path_logos_key = 'logos'
    app.config['PATH_THUMB_KEY'] = path_thumb_key = 'thumbnails'
    app.config['PATH_PRINTOUTS_KEY'] = path_printouts_key = 'printouts'

    if 'UPLOADED_BACKGROUNDS_DEST' not in app.config:
        app.config['UPLOADED_BACKGROUNDS_DEST'] = (files_path /
                                                   path_backgrounds_key)
    if 'UPLOADED_CROP_DEST' not in app.config:
        app.config['UPLOADED_CROP_DEST'] = files_path / path_crop_key
    if 'UPLOADED_CUSTOM_DEST' not in app.config:
        app.config['UPLOADED_CUSTOM_DEST'] = files_path / path_custom_key
    if 'UPLOADED_LOGOS_DEST' not in app.config:
        app.config['UPLOADED_LOGOS_DEST'] = files_path / path_logos_key
    if 'UPLOADED_PRINTOUTS_DEST' not in app.config:
        app.config['UPLOADED_PRINTOUTS_DEST'] = files_path / path_printouts_key

    # ensure logos and printouts folders exist
    app.config['UPLOADED_LOGOS_DEST'].makedirs_p()
    app.config['UPLOADED_PRINTOUTS_DEST'].makedirs_p()

    if 'MEDIA_FOLDER' not in app.config:
        app.config['MEDIA_FOLDER'] = files_path
    if 'MEDIA_THUMBNAIL_FOLDER' not in app.config:
        app.config['MEDIA_THUMBNAIL_FOLDER'] = \
            app.config['UPLOADED_THUMBNAIL_DEST'] = files_path / path_thumb_key
    app.config['MEDIA_THUMBNAIL_URL'] = '/static/files/thumbnails/'

    app.add_url_rule('/static/files/<filename>', 'files', build_only=True)
    app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
        '/static/files': files_path,
    })

    # limit upload size to 1MB
    patch_request_class(app, app.config.get('UPLOAD_SIZE', 1 * 1024 * 1024))
    configure_uploads(app, (backgrounds, custom_upload, logos_upload))
    Thumbnail(app)
Exemple #24
0
def create_app(conf_module):
    app = Flask(__name__, static_url_path='/static',
                static_folder='../static/{}'.format(CURRENT_SITE),
                template_folder='../templates/{}'.format(CURRENT_SITE))
    app.config.from_object(conf_module)
    # Cache(app)

    Mail(app)
    MongoSet(app)
    # SQLAlchemy(app)
    app.extensions['celery'] = celery
    images = UploadSet('image')
    configure_uploads(app, (images))
    patch_request_class(app)

    # setup local assets
    try:
        from city_lang.assets_local import setup_assets
        setup_assets(app)
    except ImportError, e:
        print "No module assets_local: {}".format(e)
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    bootstrap.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    mail.init_app(app)
    socketio.init_app(app)
    triangle.init_app(app)
    configure_uploads(app, avatars)

    # Limit uploads to 50 megabyte files
    patch_request_class(app, 50 * 1024 * 1024)

    # routes and custom error pages

    with app.app_context():
        from main import main as main_blueprint
        app.register_blueprint(main_blueprint)

        from .auth import auth as auth_blueprint
        app.register_blueprint(auth_blueprint, url_prefix='/auth')

        from .admin import admin as admin_blueprint
        app.register_blueprint(admin_blueprint, url_prefix='/admin')

        # from .restful_api import restful_api as restful_api_blueprint
        # app.register_blueprint(restful_api_blueprint)

        from .api_2_0 import api as api_2_0_blueprint
        app.register_blueprint(api_2_0_blueprint, url_prefix='/api/v2.0')

        from .ws_2_0 import ws as ws_2_0_blueprint
        app.register_blueprint(ws_2_0_blueprint)

        # print_routes(app)

    return app
Exemple #26
0
def init():
    app.config.from_pyfile('config.py')
    db.init_app(app)
    mail.init_app(app)
    import logging
    from logging import FileHandler
    from logging import Formatter

    file_handler = FileHandler(app.root_path + "/log/web_errors.log")
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(Formatter(
        '%(asctime)s %(levelname)s: %(message)s '
        '[in %(pathname)s:%(lineno)d]'))
    app.logger.addHandler(file_handler)
    login_manager.init_app(app)
    login_manager.login_view = "main.login"
    app.register_blueprint(main)
    app.register_blueprint(admin)
    app.register_blueprint(profile)
    app.register_blueprint(ajax)
    patch_request_class(app, size=16*1024*1024)
    configure_uploads(app, resource)
Exemple #27
0
def init():
    app.config.from_pyfile('config.py')
    db.init_app(app)
    mail.init_app(app)
    import logging
    from logging import FileHandler
    from logging import Formatter

    file_handler = FileHandler(app.root_path + "/log/web_errors.log")
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(Formatter(
        '%(asctime)s %(levelname)s: %(message)s '
        '[in %(pathname)s:%(lineno)d]'))
    app.logger.addHandler(file_handler)
    login_manager.init_app(app)
    login_manager.login_view = "main.login"
    app.register_blueprint(main)
    app.register_blueprint(admin)
    app.register_blueprint(profile)
    app.register_blueprint(ajax)
    patch_request_class(app, size=16*1024*1024)
    configure_uploads(app, resource)
Exemple #28
0
def create_app(conf_module):
    app = Flask(__name__,
                static_url_path='/static',
                static_folder='../static/{}'.format(CURRENT_SITE),
                template_folder='../templates/{}'.format(CURRENT_SITE))
    app.config.from_object(conf_module)
    # Cache(app)

    Mail(app)
    MongoSet(app)
    # SQLAlchemy(app)
    app.extensions['celery'] = celery
    images = UploadSet('image')
    configure_uploads(app, (images))
    patch_request_class(app)

    # setup local assets
    try:
        from city_lang.assets_local import setup_assets
        setup_assets(app)
    except ImportError, e:
        print "No module assets_local: {}".format(e)
Exemple #29
0
def create_app(config_name="default"):
    """
    Application factory.

    Pass in the appropriate configuration as a parameter, either:
        'development' (or 'default'),
        'testing',
        'production'.
    """
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    moment.init_app(app)
    db.init_app(app)
    mail.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    pagedown.init_app(app)
    configure_uploads(app, images)
    patch_request_class(app, size=2 * 1024 * 1024)

    if not app.debug and not app.testing and not app.config["SSL_DISABLE"]:
        from flask_sslify import SSLify

        sslify = SSLify(app)

    from .bp_main import main
    from .bp_auth import auth
    from .bp_user import user
    from .bp_post import post

    app.register_blueprint(main)
    app.register_blueprint(auth, url_prefix="/auth")
    app.register_blueprint(user, url_prefix="/user")
    app.register_blueprint(post, url_prefix="/post")

    return app
Exemple #30
0
def create_app(config_name='default'):
    """
    Application factory.

    Pass in the appropriate configuration as a parameter, either:
        'development' (or 'default'),
        'testing',
        'production'.
    """
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    moment.init_app(app)
    db.init_app(app)
    mail.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    pagedown.init_app(app)
    configure_uploads(app, images)
    patch_request_class(app, size = 2*1024*1024)

    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask_sslify import SSLify
        sslify = SSLify(app)

    from .bp_main import main
    from .bp_auth import auth
    from .bp_user import user
    from .bp_post import post
    app.register_blueprint(main)
    app.register_blueprint(auth, url_prefix='/auth')
    app.register_blueprint(user, url_prefix='/user')
    app.register_blueprint(post, url_prefix='/post')

    return app
Exemple #31
0
''' Runs our blog engine. Register blueprints, configurations and initialize
exetensions here. Clears cache before launching app.'''
from flask.ext.uploads import configure_uploads, patch_request_class
from blog import app, login_manager, md, admin, db, photos, cache
from blog.posts.models import Post
from blog.admin.posts import posts

app.config.from_object('config')
app.register_blueprint(posts)

# initialize extensions
configure_uploads(app, photos)
patch_request_class(app, 32 * 1024 * 1024)
login_manager.init_app(app)
md.init_app(app)
db.init_app(app)
cache.init_app(app, config=app.config)

with app.app_context():
	cache.clear()

if __name__ == '__main__':
	app.run(debug=True)
Exemple #32
0
from __future__ import unicode_literals, print_function

from flask import Flask, render_template, send_from_directory, abort
from flask.ext.uploads import UploadSet, ALL, configure_uploads, patch_request_class
from werkzeug import secure_filename

from memes import get_memes

# Flask
app = Flask(__name__)
app.config.from_pyfile('config.py')

# Flask-Uploads
memes_up = UploadSet('memes', ALL)
configure_uploads(app, memes_up)
patch_request_class(app, app.config['MAX_CONTENT_LENGTH'])


@app.route('/')
@app.route('/<filter>')
def index(filter=None):
    """Hall of memes"""

    if filter not in [None, 'audio', 'video']:
        abort(404)
    return render_template('index.html', memes=get_memes(filter))


@app.route('/meme/<filename>')
def get_meme(filename):
    return send_from_directory(app.config['UPLOADS_DEFAULT_DEST'], secure_filename(filename))
Exemple #33
0
def configure_upload_sets(app):
    u"""设置 Upload Sets"""
    from xiaoli.extensions.upload_set import image_resources
    configure_uploads(app, (image_resources,))
    patch_request_class(app, app.config["DEFAULT_UPLOAD_IMAGE_SIZE"])
Exemple #34
0
def create_app(option):
    app = FlaskOpinewExt(__name__)
    config = config_factory.get(option)
    app.config.from_object(config)

    from common import create_jinja_filters, random_pwd, verify_initialization

    create_jinja_filters(app)
    from webapp.client import client
    from webapp.media import media

    app.register_blueprint(client)
    app.register_blueprint(media, url_prefix=Constants.MEDIA_URL_PREFIX)

    compress.init_app(app)
    gravatar.init_app(app)
    resize.init_app(app)
    db.init_app(app)
    admin.init_app(app)
    mail.init_app(app)
    migrate.init_app(app, db)
    babel.init_app(app)
    from models import User, Role
    from webapp.forms import ExtendedRegisterForm

    assets.init_app(app)
    assets.register('js_all', js_assets)
    assets.register('css_all', css_assets)

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security.init_app(app,
                      user_datastore,
                      confirm_register_form=ExtendedRegisterForm)
    with app.app_context():
        from providers import database, payment

        if not app.testing:
            verify_initialization()

        if app.testing:
            from async import tasks
        api_manager.init_app(app, flask_sqlalchemy_db=db)

        @app.before_request
        def before_request():
            # hack to allow browsers who don't set 3rd party cookies
            x_session = request.headers.get('X-Session')
            if x_session:
                rc = dict(request.cookies)
                rc['session'] = x_session
                request.cookies = ImmutableTypeConversionDict(rc)
                # refresh session
                refreshed_csrf_token = app.session_interface.open_session(
                    app, request).get('csrf_token')
                session['csrf_token'] = refreshed_csrf_token
            user_agent = parse(request.user_agent.string)
            g.mobile = False
            if user_agent.is_mobile or user_agent.is_tablet:
                g.mobile = True
            g.constants = Constants
            g.config = app.config
            g.mode = app.config.get('MODE')
            g.response_context = []
            g.s = strings
            g.payment = payment.StripeAPI()
            g.db = database.OpinewSQLAlchemyFacade()

        @app.after_request
        def redirect_if_next(response_class):
            if request.endpoint == 'static':
                response_class.headers['Access-Control-Allow-Origin'] = '*'
            payload = request.args if request.method == 'GET' else request.form
            if 'api_next' in payload:
                if not response_class.status_code == 200:
                    flash(response_class.data)
                    return redirect(request.referrer)
                return redirect(payload.get('api_next'))
            return response_class

    # register here CSRF so that the before_request is executed after the hack above
    csrf.init_app(app)
    patch_request_class(app, Constants.MAX_FILE_SIZE)

    from webapp.common import make_json_error

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

    configure_uploads(app, (
        user_images,
        review_images,
        shop_images,
    ))
    admins = [email for name, email in config.ADMINS]

    if not (app.debug or app.testing):
        mail_handler = SMTPHandler(
            app.config.get('MAIL_SERVER'),
            '*****@*****.**',
            admins,
            'Your Application Failed',
            credentials=(app.config.get('MAIL_USERNAME'),
                         app.config.get('MAIL_PASSWORD')),
            secure=())
        mail_handler.setLevel(logging.ERROR)
        mail_handler.setFormatter(
            Formatter('''
Time        : %(asctime)s
Location    : %(pathname)s:%(lineno)d
Module      : %(module)s
Function    : %(funcName)s

%(message)s'''))
        app.logger.addHandler(mail_handler)

    return app
Exemple #35
0
 def __init__(self):
     self.img = UploadSet('surveyimg', IMAGES)
     configure_uploads(app, (self.img))
     patch_request_class(app, 16 * 1024 * 1024) #: 16 MB limit.
Exemple #36
0
 def __init__(self):
     self.img = UploadSet('surveyimg', IMAGES)
     configure_uploads(app, (self.img))
     patch_request_class(app, 16 * 1024 * 1024)  #: 16 MB limit.
Exemple #37
0
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

db = SQLAlchemy(app)

'''
Flask-login
'''
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

'''
Flask-uploads
'''
APP_ROOT = os.path.dirname(os.path.abspath(__file__))

dest = os.path.join(APP_ROOT, 'static/data/')

app.config['UPLOADS_DEFAULT_DEST'] = dest
app.config['UPLOADED_PHOTOS_ALLOW'] = ['png', 'jpg', 'jpeg', 'gif']

photos = flask_uploads.UploadSet('photos', flask_uploads.IMAGES)
flask_uploads.configure_uploads(app, (photos))
flask_uploads.patch_request_class(app, 32 * 1024 * 1024)


from app import views, models, settings, users, posts

db.create_all()
Exemple #38
0
host = 'bqmayq5x95g1sgr9.cbetxkdyhwsb.us-east-1.rds.amazonaws.com'
dbname = 'nss6p3d5ap6mnznd'
SQLALCHEMY_DATABASE_URI = 'mysql://' + user + ':' + password + '@' + host + ':3306/' + dbname
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

db = SQLAlchemy(app)
'''
Flask-login
'''
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
'''
Flask-uploads
'''
APP_ROOT = os.path.dirname(os.path.abspath(__file__))

dest = os.path.join(APP_ROOT, 'static/data/')

app.config['UPLOADS_DEFAULT_DEST'] = dest
app.config['UPLOADED_PHOTOS_ALLOW'] = ['png', 'jpg', 'jpeg', 'gif']

photos = flask_uploads.UploadSet('photos', flask_uploads.IMAGES)
flask_uploads.configure_uploads(app, (photos))
flask_uploads.patch_request_class(app, 32 * 1024 * 1024)

from app import views, models, settings, users, posts

db.create_all()
	# if app.debug:
	# 	peewee_logger = logging.getLogger('peewee')
	# 	peewee_logger.setLevel(logging.DEBUG)
	# 	peewee_logger.addHandler(logging.StreamHandler())
	# 	peewee_logger.addHandler(file_handler)

__version__ = '2.0'

app = Flask(__name__)
app.config.from_object('provaai.config.Configuration')
app.config.from_envvar('PROVAAI_SETTINGS', silent=True)
db = Database(app)

setup_logging()

# Extension setup
videos_manager = UploadSet('videos', ('mp4',))
images_manager = UploadSet('images', IMAGES)
configure_uploads(app, (videos_manager,images_manager))
patch_request_class(app, app.config['UPLOADED_MAX_FILE_SIZE'])

from flask.ext import admin
admin = admin.Admin(app, name='Prova Ai')

login_manager = LoginManager()
login_manager.init_app(app)
import api


Exemple #40
0
from flask.ext.uploads import UploadSet, configure_uploads, IMAGES, patch_request_class #from stackoverflow by chirag maliwal

####### Applicaiton configs #######
app = Flask(__name__)
app.debug = True
app.use_reloader = True
app.config['SECRET_KEY'] = 'thisoneishardtoguess'
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL') or "postgresql://localhost/SI364finalprojecthhsurk"
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATION'] = False
app.config['HEROKU_ON'] = os.environ.get('HEROKU')
app.config['UPLOADED_PHOTOS_DEST'] = os.getcwd()

photos = UploadSet('photos', IMAGES)
configure_uploads(app, photos)
patch_request_class(app) 
####### app set up #######
manager = Manager(app)
db = SQLAlchemy(app)
migrate = Migrate(app,db)
manager.add_command('db',MigrateCommand)

####### Login configs #########
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'login'
login_manager.init_app(app)


###### association table model #######
Exemple #41
0
import time
import hashlib

from flask import Flask, render_template, redirect, url_for, request
from flask.ext.uploads import UploadSet, configure_uploads, IMAGES, patch_request_class
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired, FileAllowed
from wtforms import SubmitField

app = Flask(__name__)
app.config['SECRET_KEY'] = 'I have a dream'
app.config['UPLOADED_PHOTOS_DEST'] = os.getcwd() + '/static'

photos = UploadSet('photos', IMAGES)
configure_uploads(app, photos)
patch_request_class(app)  # set maximum file size, default is 16MB


class UploadForm(FlaskForm):
    photo = FileField(validators=[
        FileAllowed(photos, u'Image Only!'),
        FileRequired(u'Choose a file!')
    ])
    submit = SubmitField(u'Upload')


@app.route('/', methods=['GET', 'POST'])
def upload_file():
    form = UploadForm()
    if form.validate_on_submit():
        for filename in request.files.getlist('photo'):
Exemple #42
0
}

app.secret_key = 'development'
oauth = OAuth(app)

qq = oauth.remote_app(
    'qq',
    consumer_key = QQ_APP_ID,
    consumer_secret = QQ_APP_KEY,
    base_url = 'https://graph.qq.com',
    request_token_url = None,
    request_token_params= {'scope' : 'get_user_info'},
    access_token_url = '/oauth2.0/token',
    authorize_url = '/oauth2.0/authorize',
)

db = SQLAlchemy(app)
#TO-DO: 'simple' cache is not thread-safe
cache = Cache(app, config={'CACHE_TYPE': 'simple'})

avatar_uploader = UploadSet('avatars', IMAGES)
configure_uploads(app, avatar_uploader)
patch_request_class(app, 5 * 1024 * 1024)  #Max 5M photos

background_image_uploader = UploadSet('backgrounds', IMAGES)
configure_uploads(app, background_image_uploader)
easemob = Easemob(app)

from app import views, models

Exemple #43
0
def config_uploads(app):
    images = UploadSet('image')
    configure_uploads(app, images)
    patch_request_class(app)
    access_token_key=os.environ['TWITTER_ACCESS_TOKEN'],
    access_token_secret=os.environ['TWITTER_TOKEN_SECRET'])

photos = UploadSet('photos', IMAGES)
manuals = UploadSet('manuals')

app.config['UPLOADED_PHOTOS_DEST'] = 'static/images'
app.config['UPLOADED_PHOTOS_ALLOW'] = set(['jpg', 'JPG'])
app.config['UPLOADED_MANUALS_ALLOW']= set(['pdf', 'PDF'])
app.config['UPLOADED_MANUALS_DEST'] = 'static/pdfs'


configure_uploads(app, (photos, manuals))


patch_request_class(app)

@app.route('/')
def index():
    """Homepage"""

    if session.get("user_id"):
        return redirect("/user")

    else:
        return render_template("homepage.html")


@app.route('/sign_in', methods=['POST'])
def handle_sign_in_form():
    """Handle submission of the sign in form."""
Exemple #45
0
 def add_upload_sets(self, upload_sets, upload_max_size=16777216):
     """Configure the app with the argument upload sets."""
     configure_uploads(self.app, upload_sets)
     # Limit the size of uploads to 16MB
     patch_request_class(self.app, upload_max_size)
Exemple #46
0
''' Runs our blog engine. Register blueprints, configurations and initialize
exetensions here. Clears cache before launching app.'''
from flask.ext.uploads import configure_uploads, patch_request_class
from blog import app, login_manager, md, admin, db, photos, cache
from blog.posts.models import Post
from blog.admin.posts import posts

app.config.from_object('config')
app.register_blueprint(posts)

# initialize extensions
configure_uploads(app, photos)
patch_request_class(app, 32 * 1024 * 1024)
login_manager.init_app(app)
md.init_app(app)
db.init_app(app)
cache.init_app(app, config=app.config)

with app.app_context():
    cache.clear()

if __name__ == '__main__':
    app.run(debug=True)
Exemple #47
0
 def file(self, file_content):
     uploader = UploadSet('surveyimg', IMAGES)
     configure_uploads(app, (uploader))
     patch_request_class(app, 16 * 1024 * 1024)  #: 16 MB limit.
     self.filename = uploader.save(file_content,
                                   name="{0}.".format(str(self)))
Exemple #48
0
def configure_upload_blueprint(app):
    configure_uploads(app, (us_eadata, us_maipubkeys, us_maisignatures))
    patch_request_class(app, app.config['MAX_CONTENT_LENGTH'])
Exemple #49
0
def create_app(option):
    app = FlaskOpinewExt(__name__)
    config = config_factory.get(option)
    app.config.from_object(config)

    from common import create_jinja_filters, random_pwd, verify_initialization

    create_jinja_filters(app)
    from webapp.client import client
    from webapp.media import media

    app.register_blueprint(client)
    app.register_blueprint(media, url_prefix=Constants.MEDIA_URL_PREFIX)

    compress.init_app(app)
    gravatar.init_app(app)
    resize.init_app(app)
    db.init_app(app)
    admin.init_app(app)
    mail.init_app(app)
    migrate.init_app(app, db)
    babel.init_app(app)
    from models import User, Role
    from webapp.forms import ExtendedRegisterForm

    assets.init_app(app)
    assets.register('js_all', js_assets)
    assets.register('css_all', css_assets)

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security.init_app(app, user_datastore, confirm_register_form=ExtendedRegisterForm)
    with app.app_context():
        from providers import database, payment

        if not app.testing:
            verify_initialization()

        if app.testing:
            from async import tasks
        api_manager.init_app(app, flask_sqlalchemy_db=db)

        @app.before_request
        def before_request():
            # hack to allow browsers who don't set 3rd party cookies
            x_session = request.headers.get('X-Session')
            if x_session:
                rc = dict(request.cookies)
                rc['session'] = x_session
                request.cookies = ImmutableTypeConversionDict(rc)
                # refresh session
                refreshed_csrf_token = app.session_interface.open_session(app, request).get('csrf_token')
                session['csrf_token'] = refreshed_csrf_token
            user_agent = parse(request.user_agent.string)
            g.mobile = False
            if user_agent.is_mobile or user_agent.is_tablet:
                g.mobile = True
            g.constants = Constants
            g.config = app.config
            g.mode = app.config.get('MODE')
            g.response_context = []
            g.s = strings
            g.payment = payment.StripeAPI()
            g.db = database.OpinewSQLAlchemyFacade()

        @app.after_request
        def redirect_if_next(response_class):
            if request.endpoint == 'static':
                response_class.headers['Access-Control-Allow-Origin'] = '*'
            payload = request.args if request.method == 'GET' else request.form
            if 'api_next' in payload:
                if not response_class.status_code == 200:
                    flash(response_class.data)
                    return redirect(request.referrer)
                return redirect(payload.get('api_next'))
            return response_class

    # register here CSRF so that the before_request is executed after the hack above
    csrf.init_app(app)
    patch_request_class(app, Constants.MAX_FILE_SIZE)

    from webapp.common import make_json_error

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

    configure_uploads(app, (user_images, review_images, shop_images, ))
    admins = [email for name, email in config.ADMINS]

    if not (app.debug or app.testing):
        mail_handler = SMTPHandler(app.config.get('MAIL_SERVER'),
                                   '*****@*****.**',
                                   admins,
                                   'Your Application Failed',
                                   credentials=(app.config.get('MAIL_USERNAME'), app.config.get('MAIL_PASSWORD')),
                                   secure=())
        mail_handler.setLevel(logging.ERROR)
        mail_handler.setFormatter(Formatter('''
Time        : %(asctime)s
Location    : %(pathname)s:%(lineno)d
Module      : %(module)s
Function    : %(funcName)s

%(message)s'''))
        app.logger.addHandler(mail_handler)

    return app