Example #1
0
def create_app(debug=False):
    if debug:
        print "Debug mode."
        app = Flask('wire', static_path='/static/')

    else:
        app = Flask('wire', static_path='/')

    app.config.from_object('wire.settings')
    app.config.from_envvar('WIRE_SETTINGS', silent=True)
    app.config['DEBUG'] = debug
    configure_uploads(app, uploaded_avatars)
    configure_uploads(app, uploaded_images)
    Markdown(app)

    if not debug:
        configure_logging(app)

    from wire.frontend import frontend
    app.register_blueprint(frontend, url_prefix='')

    configure_base_views(app)

    if app.config['SECRET_KEY'] == '':
        print 'Please setup a secret key in local_settings.py!!!'

    return app
Example #2
0
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
Example #3
0
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
Example #4
0
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
Example #5
0
    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.file is not None

            return "OK"

        @app.route("/upload-multiple-field/", methods=("POST",))
        def upload_multiple_field():
            form = MultipleFileFieldUploadForm()
            if form.validate_on_submit():
                assert len(form.uploads.files) == 3
                for upload in form.uploads.files:
                    assert "flask.png" in upload.filename
                
            return "OK"

        @app.route("/upload/", methods=("POST",))
        def upload():
            form = FileUploadForm()
            if form.validate_on_submit():

                filedata = form.upload.file
            
            else:
                
                filedata = None

            return render_template("upload.html",
                                   filedata=filedata,
                                   form=form)
        
        return app
Example #6
0
def configure_media_uploads(app=None):
    """
    ABOUT
        This configures the uploading and hosting of our image
        files.  UploadSet is pretty flexible, but we don't do
        a whole lot to customize this.
    """
    uploaded_photos = UploadSet('photos', IMAGES)
    configure_uploads(app, uploaded_photos)
    app.uploaded_photos = uploaded_photos
Example #7
0
def configure_media_uploads(app=None):
    """
    ABOUT
        This configures the uploading and hosting of our image
        files.  UploadSet is pretty flexible, but we don't do
        a whole lot to customize this.
    """
    uploaded_photos = UploadSet('photos', IMAGES)
    configure_uploads(app, uploaded_photos)
    app.uploaded_photos = uploaded_photos
Example #8
0
 def test_url_based(self):
     app = Flask(__name__)
     app.config.update(UPLOADED_FILES_DEST='/uploads',
                       UPLOADED_FILES_URL='http://localhost:5001/')
     uset = UploadSet('files')
     configure_uploads(app, uset)
     with app.test_request_context():
         url = uset.url('foo.txt')
         assert url == 'http://localhost:5001/foo.txt'
     assert '_uploads' not in app.modules
Example #9
0
def create_app(debug=False):
    # Change static path based on whether we're debugging.
    if debug:
        print "Debug mode."
        app = Flask('btnfemcol', static_path='/static')

    else:
        app = Flask('btnfemcol', static_path='')

    # Handle configuration
    app.config.from_object('btnfemcol.settings')
    app.config.from_envvar('BTNFEMCOL_SETTINGS', silent=True)
    app.config['DEBUG'] = debug

    # Initialise uploads
    configure_uploads(app, uploaded_avatars)
    configure_uploads(app, uploaded_images)

    # Initialise database
    db.app = app
    db.init_app(app)

    # Initialise cache
    cache.init_app(app)

    # Initialise Markdown
    Markdown(app,
        extensions=[
            'extra',
            'wikilinks',
            'toc'
        ],
        output_format='html5',
        safe_mode=True
    )
    if not debug:
        configure_logging(app)

    # Initialise Mail
    mail.init_app(app)

    # Sub applications
    from btnfemcol.frontend import frontend
    app.register_blueprint(frontend, url_prefix='')
    from btnfemcol.admin import admin
    app.register_blueprint(admin, url_prefix='/admin')

    configure_base_views(app)

    configure_pre_post_request(app)
    
    if app.config['SECRET_KEY'] == '':
        print 'Please setup a secret key in local_settings.py!!!'

    return app
 def test_url_based(self):
     app = Flask(__name__)
     app.config.update(
         UPLOADED_FILES_DEST='/uploads',
         UPLOADED_FILES_URL='http://localhost:5001/'
     )
     uset = UploadSet('files')
     configure_uploads(app, uset)
     with app.test_request_context():
         url = uset.url('foo.txt')
         assert url == 'http://localhost:5001/foo.txt'
     assert '_uploads' not in app.modules
Example #11
0
 def test_url_generated(self):
     app = Flask(__name__)
     app.config.update(UPLOADED_FILES_DEST='/uploads')
     uset = UploadSet('files')
     configure_uploads(app, uset)
     with app.test_request_context():
         url = uset.url('foo.txt')
         gen = url_for('_uploads.uploaded_file',
                       setname='files',
                       filename='foo.txt',
                       _external=True)
         assert url == gen
Example #12
0
def create_app(config=None):
    app = Flask(__name__)
    app.config.from_object(config)
    configure_extensions(app)
    Markdown(app)
    configure_i18n(app)
    configure_identity(app)
    configure_errorhandlers(app)
    configure_before_handlers(app)
    configure_uploads(app, (photos,))
    register_blueprints(app)
    return app
Example #13
0
def create_app(config=None):
    app = Flask(__name__)
    app.config.from_object(config)
    configure_extensions(app)
    Markdown(app)
    configure_i18n(app)
    configure_identity(app)
    configure_errorhandlers(app)
    configure_before_handlers(app)
    configure_uploads(app, (photos, ))
    register_blueprints(app)
    return app
 def test_url_generated(self):
     app = Flask(__name__)
     app.config.update(
         UPLOADED_FILES_DEST='/uploads'
     )
     uset = UploadSet('files')
     configure_uploads(app, uset)
     with app.test_request_context():
         url = uset.url('foo.txt')
         gen = url_for('_uploads.uploaded_file', setname='files',
                       filename='foo.txt', _external=True)
         assert url == gen
Example #15
0
def create_app(debug=False):
    # Change static path based on whether we're debugging.
    if debug:
        print "Debug mode."
        app = Flask('btnfemcol', static_path='/static')

    else:
        app = Flask('btnfemcol', static_path='')

    # Handle configuration
    app.config.from_object('btnfemcol.settings')
    app.config.from_envvar('BTNFEMCOL_SETTINGS', silent=True)
    app.config['DEBUG'] = debug

    # Initialise uploads
    configure_uploads(app, uploaded_avatars)
    configure_uploads(app, uploaded_images)

    # Initialise database
    db.app = app
    db.init_app(app)

    # Initialise cache
    cache.init_app(app)

    # Initialise Markdown
    Markdown(app,
             extensions=['extra', 'wikilinks', 'toc'],
             output_format='html5',
             safe_mode=True)
    if not debug:
        configure_logging(app)

    # Initialise Mail
    mail.init_app(app)

    # Sub applications
    from btnfemcol.frontend import frontend
    app.register_blueprint(frontend, url_prefix='')
    from btnfemcol.admin import admin
    app.register_blueprint(admin, url_prefix='/admin')

    configure_base_views(app)

    configure_pre_post_request(app)

    if app.config['SECRET_KEY'] == '':
        print 'Please setup a secret key in local_settings.py!!!'

    return app
Example #16
0
    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.file is not None

            return "OK"

        @app.route("/upload/", methods=("POST", ))
        def upload():
            form = FileUploadForm()

            if form.validate_on_submit():

                filedata = form.upload.file
            else:
                filedata = None

            return render_template("upload.html", filedata=filedata, form=form)

        return app
Example #17
0
def admin_app_factory():
    """ Generate the admin wsgi application """
    app = Flask(__name__, static_folder='lesimo/admin/static')
    app.secret_key = 'UI*&@762d(GDXaqq'
    app.debug = True
    Menu(app=app)

    app.config.from_pyfile('config.py')
    app.config['UPLOADED_IMAGES_DEST'] = os.path.join(app.root_path, 'static', 'uploads', 'images')
    app.config['UPLOADED_FILES_DEST'] = os.path.join(app.root_path, 'static', 'uploads', 'files')
    app.config['GENERATED_DIR'] = os.path.join(app.root_path, app.config['BUILD_DEST'])

    configure_uploads(app, (common.image_uploader, common.file_uploader))

    app.register_blueprint(AdminModule.blueprint)
    app.register_blueprint(PostsModule.blueprint, url_prefix=PostsModule.target_dir)
    app.register_blueprint(PagesModule.blueprint, url_prefix=PagesModule.target_dir)
    return app
Example #18
0
def create_app(**config):
    app = Flask(__name__)
    app.url_rule_class = NamespaceRouteRule
    app.url_map.converters['fmt'] = FormatConverter
    app.url_map.converters['nodot'] = NoDotConverter

    app.config.from_object(default_settings)
    app.config.from_envvar('OPENSPENDING_SETTINGS', silent=True)
    app.config.update(config)

    app.jinja_options['extensions'].extend(
        [formencode_jinja2.formfill, 'jinja2.ext.i18n'])

    db.init_app(app)
    cache.init_app(app)
    mail.init_app(app)
    assets.init_app(app)
    login_manager.init_app(app)
    configure_uploads(app, (sourcefiles, ))

    @app.before_request
    def require_basic_auth(*args, **kwargs):
        LOCKDOWN_FORCE = app.config['LOCKDOWN_FORCE']
        if not current_user.is_authenticated() and request.path not in [
                "/lockdown", "/__ping__"
        ] and LOCKDOWN_FORCE:
            return redirect("/lockdown", code=302)
        from openspending.model.search import SearchForm
        g.search_form = SearchForm()
        if request.method == "POST" and request.path not in ["/lockdown"]:
            token = session.get('csrf_token', None)
            resquesttoken = request.form.get('csrf_token', None)
            if request.json and not resquesttoken:
                resquesttoken = request.json.get('csrf_token')
            if not token or resquesttoken != token:
                abort(403)

    with app.app_context():
        app.cubes_workspace = Workspace()

        app.cubes_workspace.register_default_store('OpenSpendingStore')

    return app
Example #19
0
def create_app():
    app = Flask(__name__)
    app.config.from_object('config')
    bootstrap.init_app(app)
    db.init_app(app)
    lm.init_app(app)

    configure_uploads(app, images)

    event.listen(Item, 'before_delete', receive_before_delete)

    from .main import main
    app.register_blueprint(main)
    from .auth import auth
    app.register_blueprint(auth)
    from .api import api
    app.register_blueprint(api, url_prefix='/api')

    return app
Example #20
0
def create_app(**config):
    app = Flask(__name__)
    app.url_rule_class = NamespaceRouteRule
    app.url_map.converters["fmt"] = FormatConverter
    app.url_map.converters["nodot"] = NoDotConverter

    app.config.from_object(default_settings)
    app.config.from_envvar("OPENSPENDING_SETTINGS", silent=True)
    app.config.update(config)

    app.jinja_options["extensions"].extend([formencode_jinja2.formfill, "jinja2.ext.i18n"])

    db.init_app(app)
    cache.init_app(app)
    mail.init_app(app)
    assets.init_app(app)
    login_manager.init_app(app)
    configure_uploads(app, (sourcefiles,))

    @app.before_request
    def require_basic_auth(*args, **kwargs):
        LOCKDOWN_FORCE = app.config["LOCKDOWN_FORCE"]
        if not current_user.is_authenticated() and request.path not in ["/lockdown", "/__ping__"] and LOCKDOWN_FORCE:
            return redirect("/lockdown", code=302)
        from openspending.model.search import SearchForm

        g.search_form = SearchForm()
        if request.method == "POST" and request.path not in ["/lockdown"]:
            token = session.get("csrf_token", None)
            resquesttoken = request.form.get("csrf_token", None)
            if request.json and not resquesttoken:
                resquesttoken = request.json.get("csrf_token")
            if not token or resquesttoken != token:
                abort(403)

    with app.app_context():
        app.cubes_workspace = Workspace()

        app.cubes_workspace.register_default_store("OpenSpendingStore")

    return app
Example #21
0
def config(debug=None):
    if debug:
        print "Debug mode."
        #        static_types = [
        #            'ico'
        #        ]
        app = Flask(__name__)

    else:
        #        static_types = [
        #            'gif', 'jpg', 'jpeg', 'css', 'gif', 'woff', 'ttf', 'ico', 'js'
        #        ]
        app = Flask(__name__, static_path="/")

    app.config.from_object(__name__)
    app.config.from_envvar("WIRE_SETTINGS", silent=True)
    configure_uploads(app, uploaded_avatars)
    configure_uploads(app, uploaded_images)
    Markdown(app)

    return app
Example #22
0
def create_app(config=None, app_name=None, modules=None):
    """Creates and configures the Flask application."""
    if app_name is None:
        app_name = DEFAULT_APP_NAME

    if modules is None:
        modules = DEFAULT_MODULES

    # Create the application object
    app = Flask(app_name)

    # Configure the various components of the application
    configure_app(app)
    configure_logging(app)
    configure_extensions(app)
    configure_session(app)
    configure_errorhandlers(app)
    configure_modules(app, modules)
    configure_uploads(app, photos)

    return app
Example #23
0
def configure_app(app):
    # load configs
    app.config.from_object(settings)

    # set up photo upload set    
    configure_uploads(app, [settings.PHOTO_UPLOAD_SET])
    patch_request_class(app, 2 * 1024 * 1024)

    # apply app to extentions
    db.init_app(app)
    with app.test_request_context():
        db.create_all()

    # register modules
    app.register_module(profiles_module)


    # setup error pages
    @app.errorhandler(404)
    @app.errorhandler(500)
    def page_not_found(error):
        return render_template('page_not_found.html'), 404

    # setup jinja filters
    app.jinja_env.filters['pretty_date'] = pretty.date
    app.jinja_env.filters['format_datetime'] = lambda d: format_datetime(d, locale=settings.LOCALE)
    app.jinja_env.filters['format_date'] = lambda d: format_date(d, locale=settings.LOCALE)

    # setup logger
    if not app.debug:
        from logging import FileHandler, WARNING, Formatter

        file_handler = FileHandler(settings.LOG_FILE)
        file_handler.setLevel(WARNING)
        file_handler.setFormatter(Formatter(
            '%(asctime)s %(levelname)s: %(message)s '
            '[in %(pathname)s:%(lineno)d]'
        ))
        app.logger.addHandler(file_handler)
Example #24
0
def configure_app(app):
    # load configs
    app.config.from_object(settings)

    # set up photo upload set
    configure_uploads(app, [settings.PHOTO_UPLOAD_SET])
    patch_request_class(app, 2 * 1024 * 1024)

    # apply app to extentions
    db.init_app(app)
    with app.test_request_context():
        db.create_all()

    # register modules
    app.register_module(profiles_module)

    # setup error pages
    @app.errorhandler(404)
    @app.errorhandler(500)
    def page_not_found(error):
        return render_template('page_not_found.html'), 404

    # setup jinja filters
    app.jinja_env.filters['pretty_date'] = pretty.date
    app.jinja_env.filters['format_datetime'] = lambda d: format_datetime(
        d, locale=settings.LOCALE)
    app.jinja_env.filters['format_date'] = lambda d: format_date(
        d, locale=settings.LOCALE)

    # setup logger
    if not app.debug:
        from logging import FileHandler, WARNING, Formatter

        file_handler = FileHandler(settings.LOG_FILE)
        file_handler.setLevel(WARNING)
        file_handler.setFormatter(
            Formatter('%(asctime)s %(levelname)s: %(message)s '
                      '[in %(pathname)s:%(lineno)d]'))
        app.logger.addHandler(file_handler)
Example #25
0
def create_app(config=None, app_name=None, blueprints=None):
    """创建应用配置"""
    
    if app_name is None:
        app_name = DEFAULT_APP_NAME

    ## if modules is None:
    ##     modules = DEFAULT_MODULES

    if blueprints is None:
        blueprints = DEFAULT_BLUEPRINTS
        
    app = Flask(app_name)

    configure_app(app, config)
    ## configure_modules(app, modules)
    configure_blueprints(app, blueprints)
    configure_extensions(app)
    configure_login(app)

    configure_errorhandler(app)
    configure_uploads(app, photos)  ## 图片上传配置

    return app
Example #26
0
def init_uploads():
    from ifanhao.uploads import upload_list
    configure_uploads(app, upload_list)
Example #27
0
from datetime import datetime
from sys import exit

from flask import Flask, render_template
from flask.ext.mongoengine import MongoEngine
from flaskext.uploads import UploadSet, configure_uploads, patch_request_class
from flask.ext.assets import Environment, Bundle
from mongoengine.connection import ConnectionError

# Configure Flask app
app = Flask(__name__)
app.config.from_object('settings')

# Configure uploads
vcf_uploads = UploadSet(name = 'vcf', extensions = tuple(app.config['UPLOAD_FORMAT_EXTENSIONS']))
configure_uploads(app, vcf_uploads)
patch_request_class(app, app.config['UPLOADED_VCF_MAX_SIZE']) # 128MB max upload size

# Attempt connection to MongoDB instance
try:
	db = MongoEngine(app)
except ConnectionError, e:
	print str(e)
	print "----"
	print "Are you sure your MongoDB instance is running?"
	print "If on another server or port, look at settings.py."
	exit(1) 

from autozygosity import views, models, helpers, modules

# Configure Jinja2 filters
Example #28
0
app = Flask(__name__)
app.config.from_object(setting)

app.debug = True
toolbar = DebugToolbarExtension(app)

mail = Mail(app)
babel = Babel(app)
cache = Cache(app)
#db = SQLAlchemy(app)
principals = Principal(app)
login_manager = LoginManager()
login_manager.setup_app(app)
userimage = UploadSet('userimage', IMAGES)
configure_uploads(app, (userimage))

# setting
# fix issue of unicode
reload(sys)
sys.setdefaultencoding("utf-8")

# fix issue of forerign_keys problem for SQLite
#db.session.execute('PRAGMA foreign_keys=ON;')
class SQLiteForeignKeysListener(PoolListener):
    def connect(self, dbapi_con, con_record):
        db_cursor = dbapi_con.execute('pragma foreign_keys=ON')


class StrictSQLAlchemy(SQLAlchemy):
    def apply_driver_hacks(self, app, info, options):
Example #29
0
mail = Mail(app)

menu.Menu(app=app)

lm = LoginManager()
lm.init_app(app)
lm.login_view = 'user.login'

celery = make_celery(app)

bcrypt = Bcrypt(app)

code_upload_set = UploadSet('code',
                            extensions=app.config['UPLOADED_FILES_ALLOW'])
configure_uploads(app, code_upload_set)
patch_request_class(app, 2 * 1024 * 1024)  # 2MB

app.jinja_env.add_extension('jinja2.ext.do')

from app.common import views
from app.user.views import user_module, UserView
from app.contest.views import contest_module, ContestView
from app.problem.views import problem_module, ProblemView
from app.hint.views import HintView
from app.submission.views import submission_module, SubmissionView
from app.api.v1.views import api_v1_module

app.register_blueprint(user_module, url_prefix='/user')
app.register_blueprint(contest_module, url_prefix='/contest')
app.register_blueprint(problem_module, url_prefix='/problem')
 def configure(self, *sets, **options):
     self.app.config.update(options)
     configure_uploads(self.app, sets)
     return self.app.upload_set_config
Example #31
0
    help="glia server")

args = parser.parse_args()
app.config['LOCAL_PORT'] = args.port
app.config['NO_UI'] = args.no_ui
app.config['LOGIN_SERVER'] = args.glia

# Setup SQLAlchemy database
db = SQLAlchemy(app)

# Setup Blinker namespace
notification_signals = Namespace()

# Setup attachment access
attachments = uploads.UploadSet('attachments', uploads.IMAGES)
uploads.configure_uploads(app, (attachments))

# Setup loggers
# Flask is configured to route logging events only to the console if it is in debug
# mode. This overrides this setting and enables a new logging handler which prints
# to the shell.
loggers = [app.logger, logging.getLogger('synapse')]
console_handler = logging.StreamHandler(stream=sys.stdout)
console_handler.setFormatter(logging.Formatter(app.config['LOG_FORMAT']))

for l in loggers:
    del l.handlers[:]  # remove old handlers
    l.setLevel(logging.DEBUG)
    l.addHandler(console_handler)
    l.propagate = False  # setting this to true triggers the root logger
Example #32
0
from api.controller import api

# import upload
from account.core import photos
from flaskext.uploads import configure_uploads

# import error
from error import OutputError

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

app.wsgi_app = ProxyFix(app.wsgi_app)

# configure uploadset
configure_uploads(app, photos)

app.config.update(mail_config)

# 把数据库和应用相关联
db.init_app(app)

# 注册Blueprint
from app import views
app.register_blueprint(account, url_prefix='/account')
app.register_blueprint(share, url_prefix='/share')
app.register_blueprint(comment, url_prefix='/comment')
app.register_blueprint(extension, url_prefix='/extension')
app.register_blueprint(collection, url_prefix='/collection')
app.register_blueprint(api, url_prefix='/api')
Example #33
0
# Uso de helpers
import backend.helpers as helpers

# Manejo de archivos
from flaskext.uploads import UploadSet, IMAGES, configure_uploads

# authenticate
from flask import g, session, request, flash, redirect
import backend.auth as auth

app = Flask(__name__)
app.secret_key = "Kuak Team key"

# Carpeta para fotos de los proyectos
imagenes = UploadSet(name="fotos", extensions=IMAGES, default_dest=lambda app: "fotos/")
configure_uploads(app, imagenes)

# Filtros personalados
# env = Environment('app')
# env.filters['format_currency'] = helpers.format_currency
jinja2.filters.FILTERS["format_currency"] = helpers.format_currency

# login
@app.before_request
def before_request():
    g.user = auth.usuario_en_session(session)
    # print str(g.user)


@app.after_request
def after_request(response):
Example #34
0
output_json.func_globals['settings'] = {
    'ensure_ascii': False,
    'encoding': 'utf8'
}

app = Flask(__name__)

# Obtiene la variable de entorno FLASK_CONFIG_MODE. En caso de no encontrarse
# seteada, el valor por defecto es 'production', por ser el más seguro.
flask_config_mode = os.getenv('FLASK_CONFIG_MODE', 'production')
# Configura la aplicación en base a la clase de configuración que maneja el
# modo especificado.
app.config.from_object(get_config_class(flask_config_mode))

# por ahora lo coloco acá pero debería ir en la parte del config.
configure_uploads(app, config.Config.uploaded_photos)

db.app = app
db.init_app(app)

# Configuración de migraciones de la base de datos.
migrate = Migrate(app, db)

manager = Manager(app)
manager.add_command('db', MigrateCommand)

# Manejo global de solicitudes CORS
cors = CORS(app)

# Importación del manejo de autenticación HTTP.
from .mod_shared.models import auth
Example #35
0
def create_app(app_name, config_obj, with_api=True):
    """ Generates and configures the main shop application. All additional """
    # Launching application
    app = Flask(app_name)  # So the engine would recognize the root package

    # Load Configuration
    app.config.from_object(config_obj)

    # Loading assets
    assets = Environment(app)
    assets.from_yaml('assets.yaml')
    app.assets = assets

    # Initialize Mail
    app.mail = Mail(app)

    # Initializing login manager
    login_manager = LoginManager()
    login_manager.login_view = app.config.get('LOGIN_VIEW', 'main.index')
    # login_manager.login_message = 'You need to be logged in to access this page'
    login_manager.session_protection = 'strong'
    login_manager.setup_app(app)
    app.login_manager = login_manager

    # Initializing principal manager
    app.principal = Principal(app)

    # Initializing bcrypt password encryption
    bcrypt = Bcrypt(app)
    app.bcrypt = bcrypt

    # Initializing Database
    db = SQLAlchemy(app)
    app.db = db

    # Initializing Migrate
    migrate = Migrate(app, db, "from fitted.models import *")
    app.migrate = migrate

    photos = UploadSet('photos', IMAGES)
    archives = UploadSet('archives', ARCHIVES)

    configure_uploads(app, (photos, archives))

    patch_request_class(app,
                        2 * 1024 * 1024)  # Patches to 2MB file uploads max.

    app.photos = photos
    app.archives = archives

    # Integrate Elasticsearch

    es_config = app.config.get("ES_CONFIG", [])

    app.es = Elasticsearch(es_config)

    # Integrate sms with Twilio
    app.sms = TwilioRestClient(app.config.get("TWILIO_API_SID"),
                               app.config.get("TWILIO_API_TOKEN"))

    # Redis store for session management
    # The process running Flask needs write access to this directory:
    # store = RedisStore(redis.StrictRedis())

    # # this will replace the app's session handling
    # KVSessionExtension(store, app)

    # configure sentry
    # if not app.config.get("DEBUG", False):
    # 	sentry = Sentry(app)

    # 	app.sentry = sentry

    # inject celery into the app
    app.celery = make_celery(app)

    # injecting mongodb support
    # app.mongo = PyMongo(app)

    # flask s3 integration
    app.s3 = FlaskS3(app)

    # Facebook & Twitter Integration
    app.facebook = oauth.remote_app('facebook', app_key='FACEBOOK')

    oauth.init_app(app)

    # Initializing the restful API
    if with_api:
        api = restful.Api(app, prefix='/api/v1')
        app.api = api

    # Initialize Logging
    if not app.debug:
        import logging
        from logging.handlers import RotatingFileHandler
        file_handler = RotatingFileHandler(
            "/var/log/fitted/%s.log" %
            app.config.get("LOGFILE_NAME", app_name),
            maxBytes=500 * 1024)
        file_handler.setLevel(logging.WARNING)
        from logging import Formatter
        file_handler.setFormatter(
            Formatter('%(asctime)s %(levelname)s: %(message)s '
                      '[in %(pathname)s:%(lineno)d]'))
        app.logger.addHandler(file_handler)

    #include an api_registry to the application
    app.api_registry = []  #a simple list holding the values to be registered

    return app
Example #36
0
ADMIN_USERNAME = '******'
ADMIN_PASSWORD = '******'

COUCHDB_SERVER = 'http://localhost:5984/'
COUCHDB_DATABASE = 'flask-photolog'

# application

app = Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('PHOTOLOG_SETTINGS', silent=True)

# uploads

uploaded_photos = UploadSet('photos', IMAGES)
configure_uploads(app, uploaded_photos)

# documents

manager = CouchDBManager()


def unique_id():
    return hex(uuid.uuid4().time)[2:-1]


class Post(Document):
    doc_type = 'post'
    title = TextField()
    filename = TextField()
    caption = TextField()
Example #37
0
#! /usr/bin/env python
#coding=utf-8

from flask import Flask, request, render_template
import hashlib,random,os.path
app = Flask(__name__)
app.debug = True#for debug

app.config['UPLOADED_FILES_DEST'] = './static/uploads'
app.config['UPLOADED_FILES_URL']  = '/static/uploads/'#need trailing slash
#upload set
from flaskext.uploads import UploadSet, IMAGES, configure_uploads
photos = UploadSet('photos', IMAGES, default_dest=lambda app:app.config['UPLOADED_FILES_DEST'])
configure_uploads(app, photos)


from wtforms import Form, BooleanField, TextField, IntegerField, SelectField, validators, FileField

class MyForm(Form):
    title = TextField(u'标题',[validators.Length(min=3, max=10, message=u"我擦,太长了")])
    num = IntegerField(u'数字', [validators.NumberRange(min=0, max=1000, message=u'请输入一个数字')])
    photo = FileField(u'文件')#, [validators.Required()])
    
    
@app.route("/upload", methods=['GET','POST'])
def upload():
    form = MyForm(request.form)
    if request.method == 'POST' and form.validate() and 'photo' in request.files and request.files['photo'].filename is not None:
        hashname = hashlib.md5(request.files['photo'].filename + str(random.random())).hexdigest()#sha1,sha224,sha256
        filename = photos.save(request.files['photo'], name=hashname+os.path.splitext(request.files['photo'].filename)[1])
        return 'uploaded'
Example #38
0
@app.context_processor
def override_url_for():
    return dict(url_for=dated_url_for)


def dated_url_for(endpoint, **values):
    if endpoint == 'static':
        filename = values.get('filename', None)
        if filename:
            file_path = os.path.join(app.root_path, endpoint, filename)
            try:
                values['q'] = int(os.stat(file_path).st_mtime)
            except OSError as e:
                warnings.warn(e)
    return url_for(endpoint, **values)


site_images = UploadSet(
    'sites',
    IMAGES,
    default_dest=lambda app: os.path.join(app.instance_path, 'sites'))
configure_uploads(app, (site_images, ))

mail = Mail(app)

import estragon.views
import estragon.db

# vim: sts=4 sw=4 et
Example #39
0
oauth = OAuth()
facebook = oauth.remote_app(
    'facebook',
    base_url='https://graph.facebook.com/',
    request_token_url=None,
    access_token_url='/oauth/access_token',
    authorize_url='https://www.facebook.com/dialog/oauth',
    consumer_key=FACEBOOK_APP_ID,
    consumer_secret=FACEBOOK_APP_SECRET,
    request_token_params={'scope': 'email'})

app.config['UPLOADS_DEFAULT_DEST'] = settings.UPLOADS_DEFAULT_DEST
app.config['UPLOADS_DEFAULT_URL'] = settings.UPLOADS_DEFAULT_URL

photos = UploadSet('photos', IMAGES)
configure_uploads(app, (photos, ))

#admin = Admin(app)


def setup_logging(app):
    log_filename = app.config['LOGFILE']
    file_handler = RotatingFileHandler(log_filename)
    if app.config['DEBUG']:
        file_handler.setLevel(logging.INFO)
    else:
        file_handler.setLevel(logging.ERROR)

    kb_fmt = u'[%(asctime)s %(levelname)s] - %(processName)s (%(process)s) - (%(module)s:%(funcName)s:%(lineno)s) %(message)s'
    kb_formatter = logging.Formatter(fmt=kb_fmt)
    file_handler.setFormatter(kb_formatter)
from app import app

from flaskext.uploads import configure_uploads, UploadSet

electionHeader = UploadSet('election', app.config['UPLOADS_DEFAULT_DEST'])
configure_uploads(app, (electionHeader))
Example #41
0
 def configure(self, *sets, **options):
     self.app.config.update(options)
     configure_uploads(self.app, sets)
     return self.app.upload_set_config
Example #42
0
import const

ROOT_PATH = os.path.dirname(__file__)
ABS_PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))

DEBUG = True
SECRET_KEY = 'ZL=_K8RJ:e{+6WwdlnX~tR6a|`BoYBi>'
UPLOADS_DEFAULT_DEST = ABS_PROJECT_ROOT + "/static"
UPLOADS_DEFAULT_URL = 'http://127.0.0.1:5000/static'

app = Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('YOUTHING_SETTINGS', silent=True)

uploads = UploadSet('uploads', IMAGES)
configure_uploads(app, uploads)

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

	entries = Entry().query(None, 0, const.PAGE_SIZE * 2)
	categories = Category().query(None, 0, const.MAX_CATEGORY_SIZE)

	return render_template("index.html", entries=entries, 
		categories=categories, page=2,  cat="")

@app.route("/login", methods=["GET", "POST"])
def login():
	error = None
	if request.method == "POST":
		username = request.form["username"]
Example #43
0
def init(app):
    app.register_blueprint(uploads)
    configure_uploads(app, media)
    app.signals.signal('pre-edit').connect(extra_actions)
    patch_request_class(app, 32 * 1024 * 1024)      # limit 32mb
Example #44
0
from flask import Flask, render_template, request, jsonify, abort, session
from flask import send_file
from flaskext import uploads

from histogram import gen_histogram
from thumbnail import gen_thumbnail
from crop import do_crop
from resize import do_resize

app = Flask(__name__)
app.config.from_object("config")
if app.config['UPLOADED_FILES_DEST'][-1] != '/':
    app.config['UPLOADED_FILES_DEST'] += '/'

photos = uploads.UploadSet('files', uploads.IMAGES)
uploads.configure_uploads(app, photos)


def setup_session():
    """Add all the images in the stock folder to a new session."""
    session['files'] = []
    for filename in os.listdir("images/stock/"):
        if filename[-5:] != "t.jpg" and filename[-5:] != "h.png":
            session['files'].append({
                "name": "stock/" + filename,
                "url": photos.url("stock/" + filename)
            })
            session.modified = True


def temp_file_path(ip, ext):
Example #45
0
from flask import redirect
from flask import url_for
from flask import json
from flask import jsonify

import hashlib

from flaskext.uploads import (UploadSet, configure_uploads, UploadNotAllowed,
                              patch_request_class)

app = Flask(__name__)
app.config.from_object('observatory.default_settings')
app.config.from_envvar('OBS_SETTINGS', silent=True)

userApks = UploadSet('apks', ('apk'))
configure_uploads(app, userApks)
patch_request_class(app)

from persistance import *
from template_filters import *


@app.route('/', methods=['GET', 'POST'])
def app_search():
    q, s = None, 'name'
    apps = []
    search_types = {
        'name': "name",
        'pkg': "package name",
        'binhash': "APK hash",
        'certhash': "cert. fingerprint",
Example #46
0
from flaskext.uploads import (UploadSet, configure_uploads, IMAGES,
                              UploadNotAllowed)

SECRET_KEY = 'development key'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
UPLOADED_PHOTOS_DEST = '/home/linstead/flask/pandachrome.flask/UPLOADS'

app = Flask(__name__)
app.config.from_object(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
app.config['UPLOADED_FILES_DEST'] = '/home/linstead/flask/pandachrome.flask/UPLOADS'
app.config['UPLOADED_FILES_URL'] = '/files/'

uploaded_photos = UploadSet('photos', IMAGES)
configure_uploads(app, uploaded_photos)

db = SQLAlchemy(app)

def to_index():
    return redirect(url_for('index'))

def unique_id():
    return hex(uuid.uuid4().time)[2:-1]

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

def require_login(f):
    @wraps(f)
Example #47
0
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from flask import Flask, request, redirect, make_response
from flaskext.uploads import UploadSet, ALL, configure_uploads
from time import time
from os import listdir, path
from mimetypes import guess_type

PATH = '/home/cryptoparty'

app = Flask(__name__)

messages = UploadSet('messages', ALL, default_dest=lambda _: PATH)
configure_uploads(app, (messages, ))


@app.route('/', methods=['GET'])
def form():
    return """\
<html>
  <head>
    <title>InsecureDrop</title>
  </head>
  <body>
    <h1>InsecureDrop</h1>
    Upload a new file:<br />
    <form method="POST" enctype="multipart/form-data">
      <input type="file" name="message" />
      <input type="submit" value="upload" />
Example #48
0
def create_app(**config):
    app = Flask(__name__)
    app.url_rule_class = NamespaceRouteRule
    app.url_map.converters['fmt'] = FormatConverter
    app.url_map.converters['nodot'] = NoDotConverter

    app.config.from_object(default_settings)
    app.config.from_envvar('OPENSPENDING_SETTINGS', silent=True)
    app.config.update(config)

    app.jinja_options['extensions'].extend([
        formencode_jinja2.formfill,
        'jinja2.ext.i18n'
    ])

    #add some sqlalchemy connection numbers
    app.config['SQLALCHEMY_POOL_SIZE'] = 50
    app.config['SQLALCHEMY_MAX_OVERFLOW'] = 200

    db.init_app(app)
    cache.init_app(app)
    mail.init_app(app)
    assets.init_app(app)
    login_manager.init_app(app)
    configure_uploads(app, (sourcefiles,))

    # f = open('profiler.log', 'w')
    # stream = MergeStream(sys.stdout, f)
    # app.config['PROFILE'] = True
    # app.wsgi_app = ProfilerMiddleware(app.wsgi_app, stream=stream, sort_by=['cumtime'], restrictions=[300])#, profile_dir=app.config.get("UPLOADS_FOLDER") + "/profiler")

    

    @app.before_request
    def require_basic_auth(*args, **kwargs):
        LOCKDOWN_FORCE = app.config['LOCKDOWN_FORCE']
        if not current_user.is_authenticated() \
            and request.path not in ["/lockdown", "/__ping__"] \
            and LOCKDOWN_FORCE:
            return redirect("/lockdown", code=302)
        from openspending.model.search import SearchForm
        g.search_form = SearchForm()
        if request.method == "POST" and request.path not in ["/lockdown"] and not app.config.get("CSRF_DISABLE", None):
            token = session.get('csrf_token', None)
            resquesttoken = request.form.get('csrf_token', None)
            if request.json and not resquesttoken:
                resquesttoken = request.json.get('csrf_token')
            if not token or resquesttoken != token:
                abort(403)

    @app.teardown_appcontext
    def shutdown_session(exception=None):
        db.session.remove()

    # with app.app_context():
    #     app.cubes_workspace = Workspace()
        
    #     app.cubes_workspace.register_default_store('OpenSpendingStore')


    return app
Example #49
0
import json
import os

import boto
from boto.s3.key import Key as S3_Key
from flask import (render_template, request, flash, redirect, url_for, session
    , abort, escape, jsonify)
from flaskext.uploads import (UploadSet, configure_uploads, UploadNotAllowed)

from decorators import *
from models import *
import utilities
from ivrhub import app

uploaded_data = UploadSet('data', extensions=('mp3'))
configure_uploads(app, uploaded_data)

question_route = '/organizations/<org_label>/forms/<form_label>/questions'
@app.route(question_route, defaults={'question_label': None}
    , methods=['GET', 'POST'])
@app.route(question_route + '/<question_label>', methods=['GET', 'POST'])
@verification_required
@csrf_protect
def questions(org_label, form_label, question_label):
    ''' show the questions for a given form
    if there's a label included in the route, render that question alone
    '''
    user = User.objects(email=session['email'])[0]
    
    # find the relevant organization
    orgs = Organization.objects(label=org_label)
Example #50
0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.migrate import Migrate
from flaskext.markdown import Markdown
from flaskext.uploads import UploadSet, configure_uploads, IMAGES

app = Flask(__name__)
app.config.from_object('settings')
db = SQLAlchemy(app)

# migrations
migrate = Migrate(app, db)

# markdown
md = Markdown(app, extensions=['fenced_code', 'tables'])

# images
uploaded_images = UploadSet('images', IMAGES)
configure_uploads(app, uploaded_images)

from blog import views
from user import views
Example #51
0
import const

ROOT_PATH = os.path.dirname(__file__)
ABS_PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))

DEBUG = True
SECRET_KEY = 'ZL=_K8RJ:e{+6WwdlnX~tR6a|`BoYBi>'
UPLOADS_DEFAULT_DEST = ABS_PROJECT_ROOT + "/static"
UPLOADS_DEFAULT_URL = 'http://127.0.0.1:5000/static'

app = Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('YOUTHING_SETTINGS', silent=True)

uploads = UploadSet('uploads', IMAGES)
configure_uploads(app, uploads)


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

    entries = Entry().query(None, 0, const.PAGE_SIZE * 2)
    categories = Category().query(None, 0, const.MAX_CATEGORY_SIZE)

    return render_template("index.html",
                           entries=entries,
                           categories=categories,
                           page=2,
                           cat="")

Example #52
0
def init_upload(app):
    configure_uploads(app, up)
Example #53
0
def init_app(app):
    app.config.setdefault('UPLOADS_DEFAULT_DEST', join(app.instance_path, 'uploads'))
    configure_uploads(app, (resources_storage, avatars_storage, images_storage))
Example #54
0
from flask.ext.user import SQLAlchemyAdapter, UserManager
from flaskext.uploads import configure_uploads, UploadSet

from sponsortracker import model, model_events
from sponsortracker.app import app, preview_uploader


# Patch Flask Uploads lack of spport for Python 3
class PatchedDict(dict):
    def itervalues(self):
        return self.values()


app.upload_set_config = PatchedDict()

configure_uploads(app, (preview_uploader))

from . import views
Example #55
0
login_manager = LoginManager()
login_manager.init_app(app)

@login_manager.user_loader
def load_user(user_id):
    return User.get_user(user_id)


# Uploads
def test_path(app):
    return app.config['GRADER_UNITTEST']

UPLOADED_ARCHIVES_DEST = app.config['UPLOADED_ARCHIVES_DEST']

archives = UploadSet('archives', ARCHIVES)
tests = UploadSet('tests', ARCHIVES, default_dest=test_path)
configure_uploads(app, (archives, tests))
patch_request_class(app, 32 * 1024 * 1024)

# Import all our models and views
from codeta.views.user import *
from codeta.views.util import *
from codeta.views.main import *
from codeta.views.course import *
from codeta.views.assignment import *

from codeta.models.user import User

if __name__ == "__main__":
    app.run()
Example #56
0
from flask import Flask
from flaskext.sqlalchemy import SQLAlchemy
from flaskext.uploads import configure_uploads, UploadSet, IMAGES

app = Flask(__name__)

# Load default configuration values, override with whatever is specified
# in configuration file. This is, I think, the sanest approach.
app.config.from_object('kremlin.config_defaults')
app.config.from_envvar('KREMLIN_CONFIGURATION')

# Set database from configuration values
app.config['SQLALCHEMY_DATABASE_URI'] = app.config['DATABASE_URI']
db = SQLAlchemy(app)

uploaded_images = UploadSet("images", IMAGES)

# Create upload set
# and configure like a m**********r.
uploaded_images = UploadSet("images", IMAGES)
configure_uploads(app, uploaded_images)

# Import relevant modules
# this is done last to avoid touchy situations
import kremlin.dbmodel
import kremlin.core
import kremlin.forms

# Create all database tables
db.create_all()
Example #57
0
def init(app):
    app.register_blueprint(uploads)
    configure_uploads(app, media)
    app.signals.signal('pre-edit').connect(extra_actions)
    patch_request_class(app, 32 * 1024 * 1024)      # limit 32mb