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
def init_uploads(): global docs global TEMP_DIR logger.info("Uploads will be written to %s", TEMP_DIR) databasic.app.config['UPLOADED_DOCS_DEST'] = TEMP_DIR docs = UploadSet(name='docs', extensions=('txt', 'docx', 'rtf', 'csv', 'xlsx', 'xls')) configure_uploads(databasic.app, (docs))
def edit_event(uurl, eid): event = Event.query.get_or_404(int(eid)) edit_form = EditForm() if request.method == 'POST' and edit_form.validate_on_submit(): event.detail = edit_form.detail.data poster = request.files.get('poster') if poster.filename is not None: poster_upload = UploadSet(name='posters', extensions=('jpg', 'jpeg', 'png', 'bmp')) configure_uploads(current_app, (poster_upload)) #加载上传集配置 try: filename = poster_upload.save(poster) event.poster_url = poster_upload.url(filename) except UploadNotAllowed: pass else: flash('海报上传失败……', 'alert-warning') db.session.add(event) flash('更新成功', 'alert-success') return redirect(url_for('event.event_page', eid=event.id)) edit_form.detail.data = event.detail return render_template('institution/event_edit.html', insti=current_insti(), event=event, edit_form=edit_form)
def create_app(config_name): config_name = 'production' app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///book_catalog.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = None csrf.init_app(app) app.config['UPLOADED_PHOTOS_DEST'] = 'app/static/img' configure_uploads(app, photos) bootstrap.init_app(app) db.init_app(app) migrate = Migrate(app, db) login_manager.init_app(app) login_manager.login_message = "You must be logged in to access this page." login_manager.login_view = "user.login" from app import models from .user import user as user_blueprint app.register_blueprint(user_blueprint) from .main import main as main_blueprint app.register_blueprint(main_blueprint) return app
def create_app(config=None, modules=None): if modules is None: modules = DEFAULT_MODULES app = Flask(DEFAULT_APP_NAME) # config app.config.from_pyfile(config) configure_extensions(app) configure_identity(app) configure_logging(app) configure_errorhandlers(app) configure_before_handlers(app) configure_template_filters(app) configure_context_processors(app) configure_uploads(app, (photos,)) configure_i18n(app) # register module configure_modules(app, modules) 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 build_app(app): app.register_blueprint(home_bundle) app.register_blueprint(admin_bundle) # Config to Flask from objects app.config.from_object('saef_app.core.config.DevelopmentConfig') db.init_app(app) configure_uploads(app, photos)
def profile_handler(form, insti, req): insti.name = form.name.data insti.intro = form.intro.data logo = request.files.get('logo') if not (logo.filename is None or logo.filename == ''): logo_upload = UploadSet('logos', ('jpg', 'png')) configure_uploads(current_app, (logo_upload)) try: filename = logo_upload.save(logo) logo_url = logo_upload.url(filename) insti.logo_url = logo_url except UploadNotAllowed: return (False, '上传LOGO时出错') poster = request.files.get('poster') if not (poster.filename is None or poster.filename == ''): poster_upload = UploadSet('posters', ('jpg', 'png')) configure_uploads(current_app, (poster_upload)) try: filename = poster_upload.save(poster) poster_url = poster_upload.url(filename) insti.poster_url = poster_url except UploadNotAllowed: return (False, '上传海报时出错') db.session.add(insti) return (True, '资料更新成功')
def create_app(config=None, blueprints=None): if blueprints is None: blueprints = DEFAULT_BLUEPRINTS app = Flask(DEFAULT_APP_NAME) # config app.config.from_pyfile(config) configure_extensions(app) configure_identity(app) configure_logging(app) configure_errorhandlers(app) configure_before_handlers(app) configure_template_filters(app) configure_context_processors(app) configure_uploads(app, (uploader,)) configure_i18n(app) configure_creole(app) # register module configure_blueprints(app, blueprints) return app
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 post(self): if 'photo' in request.files: upload_type = 'photo' upload_files = UploadSet('photos',IMAGES) configure_uploads(app, upload_files) filename = upload_files.save(request.files[upload_type]) splits = [] for item in filename.split('.'): splits.append(item) extension = filename.split('.')[len(splits) - 1] else: return {'status':'error', 'description':'No attached Files'}, 400 f = File(filename=filename, user_id=g.user.id, extension=extension, type=upload_type) try: db.session.add(f) db.session.commit() except: return {'status':'error', 'description':'Something went wrong'}, 500 return {'status':'success', 'description':'Upload Succeeded', 'data':{'id':f.id, 'url':upload_files.url(f.name)}}, 201
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 group_new(): group_form = GroupForm() if request.method == 'POST' and group_form.validate_on_submit(): name = group_form.name.data intro = group_form.intro.data icon = request.files.get('icon') if not (icon is None or icon == ''): icon_upload = UploadSet('icons', ('jpg', 'png')) configure_uploads(current_app, (icon_upload)) try: filename = icon_upload.save(icon) icon_url = icon_upload.url(filename) #得到icon的URL except UploadNotAllowed: flash('请上传小组图标', 'alert-danger') return render_template('group/new.html', form=group_form) else: flash('小组图标没上传', 'alert-danger') return render_template('group/new.html', form=group_form) group = Group(name=name, icon_url=icon_url, intro=intro, owner_id=current_user.id) #_get_current_object() db.session.add(group) flash('新建小组 %s 成功!' % name, 'alert-success') return redirect(url_for('group.group_index')) return render_template('group/new.html', form=group_form)
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))
def upload(): if request.method == 'POST' and 'photo' in request.files: app.config[ 'UPLOADED_PHOTOS_DEST'] = 'homework' + '/' + current_user.nickname configure_uploads(app, photos) filename = photos.save(request.files['photo']) newfile = request.files['photo'].filename return testcommand() return render_template('upload2.html')
def create_app(sqlalchemy_uri=None): from flask import Flask, request_started, request, request_finished, g from flask_bootstrap import Bootstrap from flask.ext.dogpile_cache import DogpileCache import os app = Flask(__name__) app.config.from_object('APITaxi_front.default_settings') if 'APITAXI_CONFIG_FILE' in os.environ: app.config.from_envvar('APITAXI_CONFIG_FILE') if not 'ENV' in app.config: app.logger.error('ENV is needed in the configuration') return None if app.config['ENV'] not in ('PROD', 'STAGING', 'DEV'): app.logger.error("""Here are the possible values for conf['ENV']: ('PROD', 'STAGING', 'DEV') your's is: {}""".format(app.config['env'])) return None #Load configuration from environment variables for k in app.config.keys(): if not k in os.environ: continue app.config[k] = os.environ[k] if sqlalchemy_uri: app.config['SQLALCHEMY_DATABASE_URI'] = sqlalchemy_uri from APITaxi_models import db db.init_app(app) from . import backoffice backoffice.init_app(app) from . import documentation documentation.init_app(app) Bootstrap(app) from APITaxi_utils.version import check_version, add_version_header request_started.connect(check_version, app) request_finished.connect(add_version_header, app) from flask.ext.uploads import configure_uploads from .backoffice.extensions import images configure_uploads(app, (images)) from APITaxi_utils.login_manager import init_app as init_login_manager from .backoffice.forms.login import LoginForm from .extensions import user_datastore init_login_manager(app, user_datastore, LoginForm) from . import demo demo.create_app(app) from APITaxi_models import security user_datastore.init_app(db, security.User, security.CachedUser, security.Role) cache = DogpileCache() cache.init_app(app) return app
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
def member_edit(): edit_form = EditForm() if request.method == 'POST' and edit_form.validate_on_submit(): user = User.query.get(current_user.id) user.name = edit_form.username.data avatar = request.files.get('avatar') # print(avatar) # <FileStorage: '' ('application/octet-stream')> # print(avatar.filename) if avatar.filename is not None: # and avatar.filename!='' avatar_upload = UploadSet(name='avatars', extensions=('jpg', 'jpeg', 'png', 'bmp')) configure_uploads(current_app, (avatar_upload)) #加载上传集配置 try: filename = avatar_upload.save(avatar) # avatar_upload.resolve_conflict(avatar_upload, fname) #解决可能存在的文件名冲突问题 user.avatar_url = avatar_upload.url(filename) except UploadNotAllowed: pass else: flash('头像上传失败', 'alert-warning') portrait = request.files.get('portrait') if portrait.filename is not None: portrait_upload = UploadSet(name='portraits', extensions=('jpg', 'jpeg', 'png', 'bmp')) configure_uploads(current_app, (portrait_upload)) #加载上传集配置 try: filename = portrait_upload.save(portrait) # portrait_upload.resolve_conflict(portrait_upload, fname) #解决可能存在的文件名冲突问题 user.portrait_url = portrait_upload.url(filename) except UploadNotAllowed: pass else: flash('半身像上传失败', 'alert-warning') user.signature = edit_form.signature.data user.intro = edit_form.intro.data password = edit_form.password.data if password is not None and password != '': #更改密码 if user.verify_password(edit_form.old_password.data): if len(password) > 6 and len(password) < 24: if password == edit_form.password2.data: user.password = password flash('密码更改成功!', 'alert-success') else: flash('两次密码输入不一致,密码未更改', 'alert-warning') else: flash('密码长度必须 6-24 位,密码未更改', 'alert-warning') else: flash('当前密码错误,密码未更改', 'alert-danger') db.session.add(user) flash('个人资料更新成功!', 'alert-success') return redirect(url_for('member.member_page', userid=user.id)) edit_form.username.data = current_user.name edit_form.signature.data = current_user.signature edit_form.intro.data = current_user.intro return render_template('member/edit.html', form=edit_form)
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 create_app(config_name): app = Flask(__name__) configure_uploads(app,photos) app.config.from_object(config[config_name]) config[config_name].init_app(app) db.init_app(app) from .api_0_1 import api as api_0_1_blueprint app.register_blueprint(api_0_1_blueprint,url_prefix='/api/v0.1') return app
def create_app(config_name): app = Flask(__name__) configure_uploads(app, photos) app.config.from_object(config[config_name]) config[config_name].init_app(app) db.init_app(app) from .api_0_1 import api as api_0_1_blueprint app.register_blueprint(api_0_1_blueprint, url_prefix='/api/v0.1') return app
def configure_extensions(self): bootstrap.init_app(self) babel.init_app(self) mail.init_app(self) db.init_app(self) security._state = security.init_app(self, user_datastore, register_form=RegisterForm, confirm_register_form=ConfirmRegisterForm) configure_uploads(self, (images_set,)) #self.configure_admin() cache.init_app(self)
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
def init_extentions(app): db.init_app(app) migrate.init_app(app) bs.init_app(app) mail.init_app(app) configure_uploads(app, photos) moment.init_app(app) lm.init_app(app) lm.login_view = 'userbp.login' lm.login_message = 'login required!' lm.session_protection = 'strong'
def configure_extensions(app): db.init_app(app) sijax.init_app(app) login_manager.init_app(app) login_manager.login_view = 'account.signin' sys_mail.init_app(app) cache.init_app(app) admin.init_app(app) configure_i18n(app) configure_uploads(app, album)
def create_app(instance_path=None, config={}): app = Flask(__name__, instance_path=instance_path, instance_relative_config=True) app.config.update(DEFAULT_CONFIG) app.config.from_pyfile('settings.py', silent=True) configure_db(app) configure_blueprints(app, BLUEPRINTS) configure_templates(app) configure_authentication(app) configure_admin(app) configure_uploads(app, admin.files) configure_statics(app) return app
def init_uploads(app): # setup Flask-Upload for ebook uploads ebooks = UploadSet('ebooks', extensions=app.config['EBOOK_DEFINITIONS'].keys()) # setup log file uploads logs = UploadSet('logs', ALL) # ensure directory exists if not os.path.exists(app.config['UPLOADED_EBOOKS_DEST']): os.makedirs(app.config['UPLOADED_EBOOKS_DEST']) configure_uploads(app, (ebooks, logs)) return ebooks, logs
def create_app(config=None, modules=None): logger.info("Setting up Appliaction") if modules is None: modules = DEFAULT_MODULES app = Flask(DEFAULT_APP_NAME) app.config.from_pyfile(config) configure_extensions(app) configure_logging(app) configure_uploads(app, (photos,)) configure_template_filters(app) configure_i18n(app) configure_modules(app, modules) return app
def __init__(self, app): self.videos = UploadSet('videos', ( 'mp4', 'webm', 'wmv', 'avi', 'mov', )) self.images = UploadSet('images', ('jpeg', )) configure_uploads(app, ( self.videos, self.images, ))
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)
def init_extentions(app): # 为扩展对象绑定app db.init_app(app) migrate.init_app(app) bs.init_app(app) # 为mail绑定app mail.init_app(app) moment.init_app(app) lm.init_app(app) # 绑定app和US对象photos configure_uploads(app, photos)
def create_app(): app = flask.Flask(__name__) app.config.from_object('config') init_db(app) api.init_app(app) security = Security() security.init_app(app, users) principals = Principal() principals.init_app(app) configure_uploads(app, logos) from app.views import menu, bp menu.init_app(app) app.register_blueprint(bp) if False: login_manager = LoginManager(app) @login_manager.request_loader def load_user_from_request(request): if request.authorization: email, password = request.authorization.username, request.authorization.password user = User.query.filter_by(email=unicode(email)).first() if user is not None: if verify_password(password, user.password): return user @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): if not isinstance(identity, AnonymousIdentity): identity.provides.add(UserNeed(identity.id)) for role in current_user.roles: identity.provides.add(RoleNeed(role.name)) @principals.identity_loader def read_identity_from_flask_login(): if current_user.is_authenticated(): return Identity(current_user.id) return AnonymousIdentity() return app
def create_app(sqlalchemy_uri=None): from .extensions import (db, redis_store, regions, configure_uploads, documents, images) app = Flask(__name__) app.config.from_object('APITaxi.default_settings') if 'APITAXI_CONFIG_FILE' in os.environ: app.config.from_envvar('APITAXI_CONFIG_FILE') if not 'ENV' in app.config: app.logger.error('ENV is needed in the configuration') return None if app.config['ENV'] not in ('PROD', 'STAGING', 'DEV'): app.logger.error("""Here are the possible values for conf['ENV']: ('PROD', 'STAGING', 'DEV') your's is: {}""".format(app.config['env'])) return None #Load configuration from environment variables for k in app.config.keys(): if not k in os.environ: continue app.config[k] = os.environ[k] if sqlalchemy_uri: app.config['SQLALCHEMY_DATABASE_URI'] = sqlalchemy_uri db.init_app(app) redis_store.init_app(app) redis_store.connection_pool.get_connection(0).can_read() from . import backoffice backoffice.init_app(app) from . import api api.init_app(app) from . import documentation documentation.init_app(app) Bootstrap(app) request_started.connect(check_version, app) request_finished.connect(add_version_header, app) configure_uploads(app, (documents, images)) from .utils.login_manager import init_app as init_login_manager init_login_manager(app) from . import demo demo.create_app(app) for region in regions.values(): if not region.is_configured: region.configure(app.config['DOGPILE_CACHE_BACKEND']) from . import tasks tasks.init_app(app) models_committed.connect_via(app)(commit_signal) return app
def create_app(cfg): app = Flask(__name__) app.config.from_pyfile(cfg) # Register Blueprints blueprints = [questions_bp, events_bp, tabs_bp, trade_bp, users_bp, artists_bp] for bp in blueprints: app.register_blueprint(bp) # Init app db.init_app(app) login_mgr.init_app(app) configure_uploads(app, (images, )) return app
def create_app(instance_path=None, config={}): app = flask.Flask(__name__, instance_path=instance_path, instance_relative_config=True) configure_app(app, config) configure_blueprints(app) configure_assets(app) configure_static(app) configure_authentication(app) configure_templating(app) configure_error_pages(app) configure_uploads(app, files) configure_context_processor(app) configure_email(app) if app.config.get("SENTRY_DSN"): configure_sentry(app) db.init_app(app) return app
def create_app(object_name): """ An flask application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/ Arguments: object_name: the python path of the config object, e.g. appname.settings.ProdConfig """ app = Flask(__name__) app.config.from_object(object_name) # Fix for NginX app.wsgi_app = ProxyFix(app.wsgi_app) # initialize the cache cache.init_app(app) # initialize SQLAlchemy db.init_app(app) login_manager.init_app(app) mail.init_app(app) # Import and register the different asset bundles assets_env.init_app(app) assets_loader = PythonAssetsLoader(assets) for name, bundle in assets_loader.load_bundles().items(): assets_env.register(name, bundle) # register our blueprints app.register_blueprint(main) app.register_blueprint(g) app.register_blueprint(p) app.register_blueprint(ev) # configure uploads configure_uploads(app, ( flyers, press, )) return app
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
def create_app(self): app = super(TestFileUpload, self).create_app() app.config['CSRF_ENABLED'] = False app.config['UPLOADED_FILES_DEST'] = 'uploads' app.config['UPLOADS_DEFAULT_DEST'] = 'uploads' configure_uploads(app, [images, text]) @app.route("/upload-image/", methods=("POST",)) def upload_image(): form = ImageUploadForm() if form.validate_on_submit(): return "OK" return "invalid" @app.route("/upload-text/", methods=("POST",)) def upload_text(): form = TextUploadForm() if form.validate_on_submit(): return "OK" return "invalid" @app.route("/upload-multiple/", methods=("POST",)) def upload_multiple(): form = MultipleFileUploadForm() if form.validate_on_submit(): assert len(form.uploads.entries) == 3 for upload in form.uploads.entries: assert upload.has_file() return "OK" @app.route("/upload/", methods=("POST",)) def upload(): form = FileUploadForm() if form.validate_on_submit(): filedata = form.upload.data else: filedata = None return render_template("upload.html", filedata=filedata, form=form) return app
def create_app(instance_path=None, config={}): app = flask.Flask(__name__, instance_path=instance_path, instance_relative_config=True) configure_app(app, config) configure_blueprints(app) configure_assets(app) configure_static(app) configure_authentication(app) configure_templating(app) configure_error_pages(app) configure_uploads(app, files) configure_context_processor(app) configure_email(app) if app.config.get('SENTRY_DSN'): configure_sentry(app) db.init_app(app) return app
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 create_app(): ''' Create an instance of the app. ''' app = Flask(__name__, template_folder="templates") ordbok = FlaskOrdbok(app) ordbok.load() app.config.update(ordbok) #app.config.update(config or {}) app.register_blueprint(views) babel.init_app(app) cache.init_app(app) csrf.init_app(app) mail.init_app(app) bcrypt.init_app(app) #security.init_app(app, bcrypt) s3.init_app(app) configure_uploads(app, (photos)) # Setup Flask-Security user_datastore = SQLAlchemyUserDatastore(db, User, Role) security.init_app(app, datastore=user_datastore) db.init_app(app) #login_manager.init_app(app) assets.init_app(app) app.jinja_env.filters['slug'] = lambda x: slugify(x).lower() app.jinja_env.filters['noop'] = lambda x: '' # Constant that should be available for all templates. app.jinja_env.globals['ORG_TYPES'] = ORG_TYPES app.jinja_env.globals['CONTENT'] = CONTENT app.jinja_env.globals['NOI_COLORS'] = NOI_COLORS app.jinja_env.globals['LEVELS'] = LEVELS app.jinja_env.globals['DOMAINS'] = DOMAINS app.jinja_env.globals['QUESTIONS_BY_ID'] = QUESTIONS_BY_ID 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)
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 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)
def create_app(config_name): app.config.from_object(config[config_name]) app.secret_key = config[config_name].SECRET_KEY db.init_app(app) configure_uploads(app, uploaded_papers) toolbar.init_app(app) # convert unicode to string app.jinja_env.filters['split'] = str.split app.jinja_env.filters['str'] = str app.jinja_env.filters['date_thedaybefore'] = format_date_thedaybefore app.jinja_env.filters['date'] = format_date app.jinja_env.filters['unix_time'] = time.mktime app.jinja_env.filters['product_has_sold'] = product_has_sold from modules.main import main as main_blueprint app.register_blueprint(main_blueprint) from .api import api as api_blueprint app.register_blueprint(api_blueprint, url_prefix='/api') return app
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
import os from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from flask.ext.bootstrap import Bootstrap from flask.ext.pagedown import PageDown from flask.ext.uploads import UploadSet, IMAGES, configure_uploads app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) lm = LoginManager(app) bootstrap = Bootstrap(app) pagedown = PageDown(app) avatars = UploadSet('avatars', IMAGES) configure_uploads(app, avatars) from app.main import main, auth, user, book, comment, library, log from app.api import api_bp for blueprint in [main, auth, user, book, comment, library, log, api_bp]: app.register_blueprint(blueprint) from app import models exists_db = os.path.isfile(app.config['DATABASE']) if not exists_db: from . import db_fill
def register_uploadsets(app): from .uploadsets import workimages configure_uploads(app, (workimages))
documents = UploadSet('documents', AllExcept(SCRIPTS + EXECUTABLES)) # configuration DATABASE = 'tmp/explorer.db' DEBUG = True SECRET_KEY = 'development key' USERNAME = '******' PASSWORD = '******' # Create flask application app = Flask(__name__) app.config.from_object(__name__) app.config['UPLOADS_DEFAULT_DEST'] = '' # Setup Database, bootstrap, login, analytics Bootstrap(app) configure_uploads(app, documents) # Setup Database, bootstrap, login, analytics def connect_db(): return sqlite3.connect(app.config['DATABASE']) @app.route('/') @app.route('/index') @app.route('/refunded') def index(): con = sql.connect(DATABASE) con.row_factory = sql.Row cur = con.cursor() cur.execute("select * from refunds") rows = cur.fetchall(); return render_template('refunded.html', rows=rows)
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
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):
from flask import Flask, render_template, request, jsonify import pickle from flask.ext.uploads import UploadSet, configure_uploads, IMAGES from make_image import make_image from make_model import make_model from flask_bootstrap import Bootstrap app = Flask(__name__) photos = UploadSet('photos', IMAGES) app.config['UPLOADED_PHOTOS_DEST'] = 'static/img' configure_uploads(app, photos) @app.route('/') def index(): return render_template('index.html') @app.route('/upload', methods=['GET', 'POST']) def upload(): if request.method == 'POST' and 'photo' in request.files: filename = photos.save(request.files['photo']) return predict(filename) return render_template('upload.html') @app.route('/predict', methods=['GET', 'POST']) def predict(filename = False): """Recieve the article to be classified from an input form and use the model to classify. """