Example #1
0
def create_app(init=False):
    app = Flask(__name__, static_url_path="/elegon/static", template_folder="templates")
    app.config.from_object("elegon.config")
    app.secret_key = "c534d51a57638e8a8a51c36d4a4128b89f8beb22"

    for ext in (db, openid2):
        ext.init_app(app)

    for bp in blueprints:
        import_name = "%s.ui.%s:bp" % (__package__, bp)
        app.register_blueprint(import_string(import_name))

    for fl in (max, min, paginator_kwargs, enumerate):
        app.add_template_global(fl)

    with app.app_context():
        db.create_all()

    @app.before_request
    def init_global_vars():
        user_dict = json.loads(request.cookies.get(app.config["OPENID2_PROFILE_COOKIE_NAME"], "{}"))
        g.user = user_dict and User.get_or_create(user_dict["username"], user_dict["email"]) or None
        g.start = request.args.get("start", type=int, default=0)
        g.limit = request.args.get("limit", type=int, default=20)

    init_logging()

    if init:
        init_scheduler()
        start_scheduler()
        signal.signal(signal.SIGTERM, stop_scheduler)
        signal.signal(signal.SIGHUP, stop_scheduler)

    return app
Example #2
0
def create_app():
    app = Flask(__name__, static_url_path='/huhuran/static')
    app.config.from_object('huhuran.config')
    app.config.setdefault('SQLALCHEMY_TRACK_MODIFICATIONS', True)
    app.secret_key = app.config['SECRET_KEY']

    logging.basicConfig(format='%(levelname)s:%(asctime)s:%(message)s',
                        level=logging.INFO)

    for ext in (db, ):
        ext.init_app(app)

    for bp in blueprints:
        import_name = '%s.views.%s:bp' % (__package__, bp)
        app.register_blueprint(import_string(import_name))

    for fl in (max, min):
        app.add_template_global(fl)

    @app.before_request
    def init_global_vars():
        g.user = 'sso' in session and get_user(sso.get('me').data) or None
        g.start = request.args.get('start', type=int, default=0)
        g.limit = request.args.get('limit', type=int, default=20)

    return app
Example #3
0
def create_app():
    app = Flask(__name__, static_url_path='/argonath/static')
    app.config.from_object('argonath.config')
    app.secret_key = 'wolegeca'

    logging.basicConfig(format='%(levelname)s:%(asctime)s:%(message)s',
                        level=logging.INFO)

    for ext in (db, openid2):
        ext.init_app(app)

    for bp in blueprints:
        import_name = '%s.views.%s:bp' % (__package__, bp)
        app.register_blueprint(import_string(import_name))

    for fl in (max, min, paginator_kwargs):
        app.add_template_global(fl)

    @app.before_request
    def init_global_vars():
        user_dict = json.loads(request.cookies.get(app.config['OPENID2_PROFILE_COOKIE_NAME'], '{}'))
        g.user = user_dict and User.get_or_create(user_dict['username'], user_dict['email']) or None
        g.start = request.args.get('start', type=int, default=0)
        g.limit = request.args.get('limit', type=int, default=20)

    return app
Example #4
0
File: app.py Project: CMGS/neptulon
def create_app():
    app = Flask(__name__, static_url_path='/neptulon/static')
    app.config.from_object('neptulon.config')
    app.secret_key = app.config['SECRET_KEY']

    logging.basicConfig(format='%(levelname)s:%(asctime)s:%(message)s', level=logging.INFO)

    db.init_app(app)
    mail.init_app(app)
    oauth.init_app(app)

    for bp in blueprints:
        import_name = '%s.views.%s:bp' % (__package__, bp)
        app.register_blueprint(import_string(import_name))

    for fl in (max, min, paginator_kwargs):
        app.add_template_global(fl)

    @app.before_request
    def init_global_vars():
        g.user = None
        if 'id' in session:
            g.user = User.get(session['id'])
        g.redir = request.args.get('redirect', '')
        g.start = request.args.get('start', type=int, default=0)
        g.limit = request.args.get('limit', type=int, default=20)

    return app
Example #5
0
File: app.py Project: CMGS/argonath
def create_app():
    app = Flask(__name__, static_url_path='/argonath/static')
    app.config.from_object('argonath.config')
    app.config.setdefault('SQLALCHEMY_TRACK_MODIFICATIONS', True)
    app.secret_key = 'wolegeca'

    logging.basicConfig(format='%(levelname)s:%(asctime)s:%(message)s',
                        level=logging.INFO)

    for ext in (db, ):
        ext.init_app(app)

    for bp in blueprints:
        import_name = '%s.views.%s:bp' % (__package__, bp)
        app.register_blueprint(import_string(import_name))

    for fl in (max, min, paginator_kwargs):
        app.add_template_global(fl)

    @app.before_request
    def init_global_vars():
        g.user = 'id' in session and User.get(session['id']) or None
        g.start = request.args.get('start', type=int, default=0)
        g.limit = request.args.get('limit', type=int, default=20)

    return app
Example #6
0
def app_factory(**kwargs):
    app = Flask(__name__)
    app.config.from_object(config_combined)
    db.init_app(app)

    DebugToolbarExtension(app)

    app.add_template_global(string_isinstance, name='string_isinstance')

    login_manager = LoginManager(app)

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

    @app.route('/')
    def index():
        return render_template('index.html')

    @app.route('/login/', methods=['GET', 'POST'])
    def login():
        form = LoginForm(request.form)
        if form.validate_on_submit():
            if (form.username.data == app.config['ADMIN_USERNAME'] and
                form.password.data == app.config['ADMIN_PASSWORD']):
                user = User()
                login_user(user)
                return redirect(url_for('index'))
            else:
                form.username.errors.append('Invalid Username...')
                form.password.errors.append('...or Password')
        return render_template('login.html', form=form)

    @app.route('/logout/')
    def logout():
        logout_user()
        return redirect(url_for('login'))

    @app.route('/content/')
    @login_required
    def content():
        return render_template('content.html')

    @app.errorhandler(404)
    def err404(e):
        return render_template('404.html'), 404

    @app.errorhandler(500)
    def err500(e):
        return render_template('500.html'), 500

    return app
Example #7
0
def create_app(config_name='development', p_db=db, p_bcrypt=bcrypt, p_login_manager=login_manager):
    new_app = Flask(__name__)
    config_app(config_name, new_app)

    p_db.init_app(new_app)
    p_bcrypt.init_app(new_app)
    p_login_manager.init_app(new_app)
    p_login_manager.login_view = 'register'
    db.init_app(new_app)
    init_models_module(db, p_bcrypt, new_app)

    # Add translator utilities.
    new_app.add_template_global(translator.translate)

    return new_app
Example #8
0
def create_app(config_file=None):
    app = Flask(__name__)
    app = change_jinja_templates(app)
    if config_file:
        app.config.from_pyfile(config_file)
    else:
        app.config.from_envvar("CLA_PUBLIC_CONFIG")

    if app.config.get("SENTRY_DSN"):
        app.sentry = Sentry(app, dsn=app.config.get("SENTRY_DSN"), logging=True, level=logging.ERROR)

    app.babel = Babel(app)
    app.babel.localeselector(get_locale)

    app.cache = Cache(app)

    app.mail = Mail(app)

    for extension in app.config["EXTENSIONS"]:
        extension.init_app(app)

    app.session_interface = CheckerSessionInterface()
    app.json_encoder = CustomJSONEncoder

    register_error_handlers(app)

    app.add_template_global(honeypot.FIELD_NAME, name="honeypot_field_name")

    app.register_blueprint(base)
    app.register_blueprint(geocoder)
    app.register_blueprint(contact)
    app.register_blueprint(scope)
    if not app.config.get("CONTACT_ONLY"):
        app.register_blueprint(checker)

    logging.config.dictConfig(app.config["LOGGING"])
    # quiet markdown module
    logging.getLogger("MARKDOWN").setLevel(logging.WARNING)

    if app.debug:
        from werkzeug.debug import DebuggedApplication

        app.wsgi_app = DebuggedApplication(app.wsgi_app, True)

    return app
Example #9
0
def create_app(config_file=None, config_object=None):
    """
    Application bootstrapper.
    """
    app = Flask(__name__, static_folder='public')
    app.config.from_object('eveauth.settings.BaseConfig')
    app.environment = os.getenv('eveauth_ENV', 'dev')

    if config_file:
        file_ext = os.path.splitext(config_file)[1]
        if file_ext == '.yml':
            with open(config_file) as f:
                config_yaml = yaml.load(f)
                app.config.update(**config_yaml)
        elif file_ext == '.py':
            app.config.from_pyfile(config_file)
        else:
            raise Exception('Unsupported config file format: {}, expecting Yaml or Python'.format(file_ext))

    if config_object:
        app.config.update(**config_object)

    if app.environment != 'test':
        csrf.init_app(app)

    from eveauth.api import api_manager
    api_manager.init_app(app)

    from eveauth.models import db, migrate, ma
    db.init_app(app)
    migrate.init_app(app, db)
    ma.init_app(app)

    from eveauth.controllers import MetaView
    MetaView.register(app)

    from eveauth.services import sso_service
    sso_service.init_app(app)

    app.add_template_global(app.config, 'config')

    return app
Example #10
0
def create_app():
    app = Flask('Ainur', static_url_path='/static')
    app.config.from_object('config')
    app.secret_key = app.config['SECRET']

    db.init_app(app)
    db.app = app
    db.create_all()
    rds.init_app(app)

    for bp in blueprints:
        import_name = '%s.%s:bp' % (__package__, bp)
        app.register_blueprint(import_string(import_name))

    for fl in (max, min, paginator_kwargs, login_url):
        app.add_template_global(fl)

    @app.before_request
    def init_global_vars():
        g.page = request.args.get('page', type=int, default=0)
        g.start = request.args.get('start', type=int, default=g.page * 20)
        g.limit = request.args.get('limit', type=int, default=20)

        if request.path == '/user/login_from_openid/' or request.path.startswith('/ajax'):
            return

        if 'uid' not in session:
            abort(401)
        g.user = User.get_by_uid(session['uid'])

    @app.errorhandler(403)
    @app.errorhandler(401)
    def error_handler(e):
        return render_template('errors/%s.html' % e.code), e.code

    return app
Example #11
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)
    moment.init_app(app)
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'
    db.init_app(app)
    from .main import main
    from .auth import auth
    from .manager import manager
    app.register_blueprint(main)
    app.register_blueprint(auth)
    app.register_blueprint(manager)
    configure_uploads(app, photos)
    patch_request_class(app)
    from .models import Message, User, Post, Praise, Comment, Collection
    app.add_template_global(Message, 'Message')
    app.add_template_global(User, 'User')
    app.add_template_global(Post, 'Post')
    app.add_template_global(Comment, 'Comment')
    return app
    if request.method == 'POST':
        newCategory = Category(
            name=request.form['name'], user_id=login_session['user_id'])
        session.add(newCategory)
        flash('New Category %s Successfully Created' % newCategory.name)
        session.commit()
        return redirect(url_for('showCatalog'))
    else:
        return render_template('newCategory.html')


def get_category(item):
    category = session.query(Category).filter_by(id=item.category_id).one()
    return category

app.add_template_global(get_category, name='get_category')


def is_logged_in():
    return 'username' in login_session

app.add_template_global(is_logged_in, name='is_logged_in')


def get_count(q):
    count_q = q.statement.with_only_columns([func.count()]).order_by(None)
    count = q.session.execute(count_q).scalar()
    return count


# Show a category
Example #13
0
def jsonify(*args, **kwargs):
    response = flask_jsonify(*args, **kwargs)
    if not response.data.endswith(b'\n'):
        response.data += b'\n'
    return response

# Prevent WSGI from correcting the casing of the Location header
BaseResponse.autocorrect_location_header = False

# Find the correct template folder when running from a different location
tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')

app = Flask(__name__, template_folder=tmpl_dir)
app.debug = bool(os.environ.get('DEBUG'))

app.add_template_global('HTTPBIN_TRACKING' in os.environ, name='tracking_enabled')

app.config['SWAGGER'] = {
    'title': 'httpbin.org',
    'uiversion': 3
}

template = {
  "swagger": "2.0",
  "info": {
    "title": "httpbin.org",
    "description": (
        "A simple HTTP Request & Response Service."
        "<br/> <br/> <b>Run locally: </b> <code>$ docker run -p 80:80 kennethreitz/httpbin</code>"
    ),
    "contact": {
Example #14
0
from flask import Flask, render_template, url_for, jsonify
import json

def fix_name(name):
    return name.replace(" ","_")

data = json.load(open('report.json'))
app = Flask(__name__)
app.add_template_global(fix_name)

@app.route("/")
def report():
    total_demand = data['demand']['Total Demand']
    disaggregation_results = data['disaggregate']
    reportdata = {k:v for k,v in data['demand'].iteritems() if k not in ["Demand Data", "Total Demand"]}
    return render_template("index.html", total_demand=total_demand, demand=reportdata, disaggregation_results=disaggregation_results, zones=data['zones'])

@app.route("/demanddata")
def demanddata():
    return jsonify({'data': [{'date': k,'value': v} for k,v in data['demand']['Demand Data'].iteritems()]})

@app.route("/zonedata/<key>/<zone>")
def zonedata(key, zone):
    """
    key: "Min Daily Avg Demand" from report.demand_report
    zone: zone name like "DOSA"
    """
    key = key.replace("_"," ")
    ret = {}
    for ts, dd in data['demand'][key]['Data'][zone].iteritems():
        ret[ts] = [{'date': k, 'value': v} for k,v in dd.iteritems()]
Example #15
0
@app.template_global()
def static_url(**values):
    """Return a static url with an mtime query string for cache busting."""
    filename = values.get('filename', None)
    if not filename:
        return url_for('static', **values)

    file_path = os.path.join(app.static_folder, filename)
    if os.path.exists(file_path):
        values['mtime'] = int(os.stat(file_path).st_mtime)

    return url_for('static', **values)


app.add_template_global(datetime.date.today, 'today')
CACHED_URL_FOR = functools.lru_cache(2048)(flask.url_for)


@app.template_global()
def url_for(endpoint, **values):
    """A wrapper around flask.url_for that uses a cache."""
    _inject_filters(endpoint, values)
    return CACHED_URL_FOR(endpoint, **values)


@app.template_global()
def url_for_current(**kwargs):
    """URL for current page with updated request args."""
    if not kwargs:
        return url_for(request.endpoint, **request.view_args)
Example #16
0
import inspect
import logging
from datetime import datetime

import ucam_webauth
import raven
import raven.demoserver
import raven.flask_glue

from flask import Flask, request, render_template, redirect, \
                  url_for, abort, session, flash
app = Flask(__name__)

app.config["SECRET_KEY"] = os.urandom(16)

app.add_template_global(repr, name="repr")
app.add_template_global(getattr, name="getattr")

modules = {"ucam_webauth": ucam_webauth,
           "raven": raven, "raven.demoserver": raven.demoserver}

auth_decorator = raven.flask_glue.AuthDecorator()

@app.route("/")
def home():
    return render_template("home.html")

@app.route("/decorated")
@auth_decorator
def decorated():
    return render_template("decorated.html", a=auth_decorator)
Example #17
0
def app_factory(**kwargs):
    app = Flask(__name__)
    app.config.from_object(config_combined)
    db.init_app(app)
    DebugToolbarExtension(app)
    app.add_template_global(string_isinstance, name='string_isinstance')
    login_manager = LoginManager(app)

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

    @app.route('/')
    def index():
        return render_template('index.html')

    @app.route('/login/', methods=['GET', 'POST'])
    def login():
        form = LoginForm(request.form)
        if form.validate_on_submit():
            if (form.username.data == app.config['ADMIN_USERNAME'] and
                    form.password.data == app.config['ADMIN_PASSWORD']):
                user = User()
                login_user(user)
                return redirect(url_for('index'))
            else:
                form.username.errors.append('Invalid Username...')
                form.password.errors.append('...or Password')
        return render_template('login.html', form=form)

    @app.route('/logout/')
    def logout():
        logout_user()
        return redirect(url_for('login'))

    @app.route('/content/')
    @login_required
    def content():
        return render_template('content.html')

    @app.errorhandler(404)
    def err404(e):
        return render_template('404.html'), 404

    @app.errorhandler(500)
    def err500(e):
        return render_template('500.html'), 500

    @app.route('/all-tables/')
    def all_tables():
        class TableTable(HTMLTable):
            name = LinkCol('Name', 'data_bp.view', attr='name',
                           url_kwargs=dict(table='name'))
            add_col = LinkCol('Add Col', 'table_bp.add_col',
                              url_kwargs=dict(table='name'))
        t = TableTable(get_all_tables(app.config['SQLALCHEMY_DATABASE_URI']))
        return render_template('all_tables.html', t=t)

    # use: http://docs.sqlalchemy.org/en/rel_0_9/orm/extensions/automap.html

    ## db manipulations
    @app.route('/create/')
    def create():
        from .data_types import str_data_factory
        from .sql import create

        col_options = [('name', 'string'), ('date', 'date'), ('description', 'string')]
        cols = [(name, str_data_factory(t)) for name, t in col_options]

        name = 'test2'
        sql = create(name, cols)

        run_sql(sql, app.config['SQLALCHEMY_DATABASE_URI'])

        return redirect(url_for('all_tables'))

    @app.route('/delete/')
    def delete():
        run_sql(
            'DROP TABLE %s;', app.config['SQLALCHEMY_DATABASE_URI'], ('test',))

        return redirect(url_for('all_tables'))

    from .data_bp import bp_factory as data_bp_factory
    app.register_blueprint(data_bp_factory(), url_prefix='/data')

    from .table_bp import bp_factory as table_bp_factory
    app.register_blueprint(table_bp_factory(), url_prefix='/table')

    return app
Example #18
0
## Flask-Bootstrap
Bootstrap(app)

## Flask-Assets
assets = Environment(app)
js = Bundle('js/selectize.min.js', 'js/main.js',
        output='assets/all.js')
css = Bundle('css/selectize.bootstrap3.css', 'css/style.css',
        output='assets/all.css')
assets.register('js', js)
assets.register('css', css)

def all_roles():
    return select(r for r in Role).order_by(Role.name)

app.add_template_global(all_roles, name='all_roles')
app.add_template_global(arrow.now, name='now')

@app.route('/')
@db_session
def index():
    return render_template('index.html')

@app.route('/roles.json', methods=['POST'])
@db_session
def roles_create():
    name = request.form['name']
    role = Role(name=name)
    commit()
    return jsonify(result=role.to_dict())
Example #19
0
app.wsgi_app = SassMiddleware(app.wsgi_app, {
    'soran.web': ('static/sass', 'static/css', '/static/css')
})


def import_python(module_name: str):
    modules = module_name.split(':')
    if len(modules) != 2:
        return None
    try:
        return getattr(__import__(modules[0]), modules[1])
    except (ImportError, AttributeError):
        return None


app.add_template_global(import_python, 'import_python')
app.add_template_global(isinstance, 'isinstance')


app.url_map.converters.update(
    youtube=YoutubeConverter
)


app.register_blueprint(user.bp)
app.register_blueprint(youtube.bp)


@app.route('/', methods=['GET'])
def hello():
    """메인 핸들러
Example #20
0
File: app.py Project: rclanan/radar
def create_app():
    app = Flask(__name__)
    app.config.from_object('radar.default_settings')
    app.config.from_object('radar.web.default_settings')
    app.config.from_envvar('RADAR_SETTINGS')

    db.init_app(app)

    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.user_loader(load_user)
    login_manager.login_view = 'auth.login'

    Markdown(app)

    mail.init_app(app)

    app.register_blueprint(radar_bp)
    app.register_blueprint(auth_bp)
    app.register_blueprint(disease_groups_bp, url_prefix='/disease-groups')
    app.register_blueprint(units_bp, url_prefix='/units')
    app.register_blueprint(users_bp, url_prefix='/users')
    app.register_blueprint(patients_bp, url_prefix='/patients')
    app.register_blueprint(recruit_bp, url_prefix='/patients')
    app.register_blueprint(news_bp, url_prefix='/news')
    app.register_blueprint(stats_bp, url_prefix='/stats')

    patient_blueprints = [
        (diagnosis_bp, '/diagnosis'),
        (dialysis_bp, '/dialysis'),
        (genetics_bp, '/genetics'),
        (hospitalisations_bp, '/hospitalisations'),
        (results_bp, '/results'),
        (medications_bp, '/medications'),
        (pathology_bp, '/pathology'),
        (plasmapheresis_bp, '/plasmapheresis'),
        (renal_imaging_bp, '/renal-imaging'),
        (salt_wasting_bp, '/salt-wasting'),
        (transplants_bp, '/transplants'),
    ]

    patient_base = '/patients/<int:patient_id>'

    for bp, url_prefix in patient_blueprints:
        app.register_blueprint(bp, url_prefix=patient_base + url_prefix)

    app.before_request(require_login)
    app.before_request(force_password_change)

    # Register template filters
    app.add_template_filter(strftime)
    app.add_template_filter(year_format)
    app.add_template_filter(date_format)
    app.add_template_filter(datetime_format)
    app.add_template_filter(nl2br)
    app.add_template_filter(missing)
    app.add_template_filter(yn)
    app.add_template_filter(number_format)

    # Register template globals/functions
    app.add_template_global(url_for_order_by)
    app.add_template_global(url_for_page)
    app.add_template_global(url_for_per_page)

    # Register context processors (data available in all templates)
    app.context_processor(inject_navigation)
    app.context_processor(inject_delete_form)

    # Register error handlers
    app.register_error_handler(403, forbidden)
    app.register_error_handler(404, page_not_found)
    app.register_error_handler(500, internal_server_error)

    # Automatically set the created_user and modified_user
    event.listen(SignallingSession, 'before_flush', before_flush_set_created_listener)
    event.listen(SignallingSession, 'before_flush', before_flush_set_modified_listener)

    return app
Example #21
0
flatpages = FlatPages(app)
freezer = Freezer(app)
moment = Moment(app)
app.config['SECRET_KEY'] = 'Hard to guess String'

def get_brow_info():
    getinfo={}
    user_agent = request.headers.get('User-Agent')
    referer = request.headers.get('Referer')
    ip,user = request.remote_addr,request.remote_user
    getinfo['user_agent'] = user_agent
    getinfo['referer'] = referer
    getinfo['ip'] = ip
    getinfo['user'] = user
    return  getinfo
app.add_template_global(get_brow_info,'visinfo')

@app.context_processor
def url():
    return dict(BASE_URL=BASE_URL)


class SecForm(Form):
    password = StringField('Input Code',validators=[DataRequired()])
    submit = SubmitField('Done')

#@app.route('/pygments.css')
#def py_css():
#    return pygments_style_defs('monokai'), 200, {'Content-Type': 'text/css'}

@app.route('/')
Example #22
0
def app_factory(**kwargs):
    app = Flask(__name__)
    ROOT_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
    config_combined.UPLOAD_DIR = os.path.join(
        ROOT_DIR, config_combined.UPLOAD_DIR)
    app.config.from_object(config_combined)

    db.init_app(app)
    Babel(app)

    DebugToolbarExtension(app)

    app.add_template_global(string_isinstance, name='string_isinstance')

    login_manager = LoginManager(app)

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

    @app.route('/')
    def index():
        recipes = Recipe.query.order_by(Recipe.posted_on.desc()).all()
        return render_template('index.html', recipes=recipes)

    @app.route('/photo/<int:recipe_id>/<string:tag>')
    def show_photo(recipe_id, tag):
        p = Photo.query.filter_by(recipe_id=recipe_id, tag=tag).first_or_404()
        return send_from_directory(app.config['UPLOAD_DIR'], p.saved_filename)

    @app.route('/login/', methods=['GET', 'POST'])
    def login():
        form = LoginForm(request.form)
        if form.validate_on_submit():
            if (form.username.data == app.config['ADMIN_USERNAME'] and
                form.password.data == app.config['ADMIN_PASSWORD']):
                user = User()
                login_user(user)
                return redirect(url_for('index'))
            else:
                form.username.errors.append('Invalid Username...')
                form.password.errors.append('...or Password')
        return render_template('login.html', form=form)

    @app.route('/logout/')
    def logout():
        logout_user()
        return redirect(url_for('index'))

    @app.errorhandler(404)
    def err404(e):
        return render_template('404.html'), 404

    @app.errorhandler(500)
    def err500(e):
        return render_template('500.html'), 500

    from .manage_bp import bp_factory as manage_factory
    app.register_blueprint(manage_factory())

    return app
Example #23
0
# s3 options
app.config['FLASKS3_ACTIVE'] = cfg.aws
app.config['FLASKS3_BUCKET_NAME'] = cfg.S3_BUCKET
app.config['FLASKS3_BUCKET_DOMAIN'] = cfg.S3_BUCKET_DOMAIN
# app.config['AWS_ACCESS_KEY_ID'] = cfg.S3_ACCESS_KEY
# app.config['AWS_SECRET_ACCESS_KEY'] = cfg.S3_SECRET_KEY
s3 = FlaskS3(app)

app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
app.jinja_env.line_statement_prefix = '#'  # enables jinja2 line mode
app.jinja_env.line_comment_prefix = '##'  # enables jinja2 line mode

app.secret_key = 'Bd\xf2\x14\xbbi\x01Gq\xc6\x87\x10BVc\x9c\xa4\x08\xdbk%\xfa*\xe3'  # os.urandom(24)

# makes our config available to all jinja templates
app.add_template_global(cfg, 'cfg')
# @app.before_first_request
# def load_tables():
#     """ collects all the metadata as soon as the app boots up
#     well, only acts when the first request comes in but whatever"""
#     db._fetch_metadata(database)


@app.before_request
def assign_session_params():
    """ Makes sure the user has basic needs satisfied
        password: password to sign off posts with
        myposts: list of pids posted by the user
        update-myposts: at min once every two days, replace myposts with a
            list of postids that still exist in the db.
    """
Example #24
0
File: app.py Project: gapato/glask
def create_app():

    basedir = getcwd()

    instance = split(split(abspath(__file__))[0])[0]
    app = Flask(__name__, instance_path=instance)
    app.config.from_object('glask.config')

    file_handler = FileHandler(app.config['LOGFILE'])
    app.logger.addHandler(file_handler)
    if not app.config['DEBUG']:
        file_handler.setLevel(logging.WARNING)
    else:
        file_handler.setLevel(logging.DEBUG)

    if not GEXIV_SUPPORT:
        app.logger.warn('GExiv2 is not available, metadata and automatic image rotation disabled')
    app.config['GEXIV_SUPPORT'] = GEXIV_SUPPORT

    app.config['FREEZER_DESTINATION'] = abspath(app.config['FREEZER_DESTINATION'])

    assert isdir(app.config['PICS_DIR']), 'Pictures directory not found'
    assert isdir(app.config['SUBS_DIR']), 'Subsamples directory not found'

    config.PICS_EXTENSIONS = app.config['PICS_EXTENSIONS']
    SUBSAMPLES_SIZES = app.config['SUBSAMPLES_GEOM'].keys()
    if app.config['LINK_ORIGINALS']:
        SUBSAMPLES_SIZES.append('original')

    app.add_template_global(join)

    @app.route('/')
    @app.route('/<path:path>/')
    def tree(path=u''):
        if is_picture(path):
            if app.config['USE_FANCYBOX']:
                return redirect(url_for('picture', size='hi', path=path))
            else:
                return redirect(url_for('view', path=path))
        fixed_path = _sanitize_path(path)
        fixed_path = join(app.config['PICS_DIR'], fixed_path)
        relative_path   = relpath(fixed_path, start=app.config['PICS_DIR'])
        if relative_path == '.': relative_path = ''
        app.logger.debug('relative_path: ' + relative_path)
        tree = walk(fixed_path)
        try:
            (cdir, dirs, files) = tree.next()
        except:
            abort(404)
        finally:
            tree.close()
        pics = filter_pics(files)
        pics.sort()
        pic_titles = _index_view_titles(relative_path, pics)
        dirs.sort(cmp=app.config['ALBUMS_SORT_FUNC'])
        samples = {}
        for d in dirs:
            s = _album_samples(relative_path, d, n=app.config['SAMPLES_COUNT'])
            if len(s) == 0:
                dirs.remove(d)
            else:
                samples[d] = s
        return render_template('index.html',
                dirs=dirs[::-1],
                pics=pics,
                pic_titles=pic_titles,
                samples=samples,
                prefix=relative_path)

    if not app.config['USE_FANCYBOX']:
        @app.route('/<path:path>/view/')
        def view(path):
            fixed_path = _sanitize_path(path)
            if not is_picture(fixed_path) or not isfile(join(app.config['PICS_DIR'], fixed_path)):
                abort(404)
            (prefix, pic) = split(fixed_path)
            prefix += '/'
            return _render_pic_view(prefix, pic)

    @app.route('/<path:path>/raw/<size>.jpg')
    def picture(size='hi', path=''):
        fixed_path = _sanitize_path(path)
        extension = splitext(fixed_path)[1]
        if not extension in app.config['PICS_EXTENSIONS'] or not size in SUBSAMPLES_SIZES:
            abort(404)
        (prefix, pic) = split(fixed_path)
        if not prefix == '':
            prefix += '/'
        if size == 'original':
            if app.config['USE_SENDFILE']:
                return send_from_directory(join(app.instance_path, app.config['PICS_DIR'], prefix),
                        pic, mimetype='image/jpeg')
            else:
                response = make_response()
                response.headers['Content-Type'] = 'image/jpeg'
                internal_url = quote(join(app.config['XACCEL_ORIGINAL'], prefix, pic).encode('utf-8'))
                response.headers['X-Accel-Redirect'] = internal_url
                return response
        else:
            return _serve_subsample(prefix, pic, size)

    if app.config['SERVE_ALBUMS_ARCHIVE']:
        @app.route('/download')
        @app.route('/<path:path>/download')
        def download(path=''):
            fixed_path = _sanitize_path(path)
            prefix, directory = split(join(app.config['PICS_DIR'], path))
            if directory == '':
                prefix = basedir
                directory = app.config['PICS_DIR']

            sent_filename = u'{0}.zip'.format(directory).encode('utf-8')
            archive_name = '{0}.zip'.format(punymd5(directory))
            archive_path = join(app.config['SUBS_DIR'], archive_name)
            if not isfile(archive_path):
                zip = zipfile.ZipFile(archive_path, 'w')
                try:
                    chdir(prefix)
                    for root, dirs, files in walk(path):
                        pics = filter_pics(files)
                        for p in pics:
                            zip.write(join(root, p))
                finally:
                    chdir(basedir)
                    zip.close()
            return send_from_directory(join(app.instance_path, app.config['SUBS_DIR']),
                    archive_name,
                    as_attachment=True,
                    attachment_filename=sent_filename)

    @app.route('/dynamic.css')
    def dynamic_css():
        response = make_response()
        response.headers['Content-Type'] = 'text/css'
        response.data = render_template('dynamic.css')
        return response

    @app.template_filter('tobc')
    def path_to_breadcrumbs(path):
        if path == '':
            return ''
        p = normpath(path)
        dirs = p.split('/')
        part_path = ''
        p = u''
        for d in dirs:
            part_path = join(part_path, d)
            p += u' &rsaquo; <a href="{0}">{1}</a>'.format(
                    escape(url_for('tree', path=part_path)),
                    escape(d))
        return Markup(p)

    def _sanitize_path(path):
        fixed_path = normpath(u'/'+path)[1:]
        if fixed_path != path:
            abort(403)
        return fixed_path

    def _index_view_titles(relative_path, pics):
        prefix = join(app.config['PICS_DIR'], relative_path)
        pic_titles = {}
        for p in pics:
            title = ""
            if GEXIV_SUPPORT:
                src_file = join(prefix, p)
                meta = extract_base_meta(src_file, as_dict=True, as_string=True)
                fnumber = meta.get('fnumber') and 'f/{0}'.format(meta['fnumber'])
                expo    = meta.get('expo')    and '  {0}s'.format(meta['expo'])
                focal   = meta.get('focal')   and '  {0}mm'.format(meta['focal'])
                time    = meta.get('time')    and '  @  {0}'.format(meta['time'])
                title = u'{0}{1}{2}{3}'.format(fnumber, expo, focal, time)
            pic_titles[p] = title
        return pic_titles

    def _album_samples(relative_path, dir, n=10):
        samples = []
        walk_root = join(app.config['PICS_DIR'], relative_path, dir)
        tree = walk(walk_root)
        try:
            while True:
                (cdir, dirs, files) = tree.next()
                if len(files) > 0:
                    pics = filter_pics(files)
                    shuffle(pics)
                    for i in range(len(pics)):
                        pics[i] = relpath(join(cdir, pics[i]), start=app.config['PICS_DIR'])
                    samples.extend(pics[:(n-len(samples))])
                    if len(samples) == n:
                        break
                shuffle(dirs)
        except Exception, e:
            pass
        finally:
Example #25
0
# Register modules
app.register_blueprint(content_blueprint, url_prefix='/content')
app.register_blueprint(contacts_blueprint, url_prefix='/contacts')
app.register_blueprint(feed_blueprint, url_prefix='/feed')
app.register_blueprint(posts_blueprint, url_prefix='/posts')
app.register_blueprint(roster_blueprint, url_prefix='/roster')
app.register_blueprint(tags_blueprint, url_prefix='/tags')
app.register_blueprint(users_blueprint, url_prefix='/users')
app.register_blueprint(diaspora_blueprint)  # Diaspora has certain fixed URLs

# Global template utility functions
try:
    app.add_template_filter(templates.nl2br, name='nl2br')
    app.add_template_filter(templates.since, name='since')
    app.add_template_global(
        templates.chunk_url_params,
        name='chunk_url_params'
    )
except:
    app.jinja_env.filters['nl2br'] = templates.nl2br
    app.jinja_env.filters['since'] = templates.since
    app.jinja_env.globals['chunk_url_params'] = templates.chunk_url_params


def init_db():
    db.create_all()


@app.route('/setup')
def setup():
    init_db()
    return "OK"
Example #26
0
def create_app(config=None, **kwargs):
    """Create the WSGI application that is this app.

    In addition to the arguments documented below, this function accepts as a
    keyword agument all agruments to :py:class:`flask.Flask` except
    `import_name`, which is set to 'evesrp'. Additionally, the value of
    `instance_relative_config` has a default value of `True`.

    If the `config` argument isn't specified, the app will attempt to use the
    file 'config.py' in the instance folder if it exists, and will then fall
    back to using the value of the EVESRP_SETTINGS environment variable as a
    path to a config file.

    :param config: The app configuration file. Can be a Python
        :py:class:`dict`, a path to a configuration file, or an importable
        module name containing the configuration.
    :type config: str, dict
    """
    # Default instance_relative_config to True to let the config fallback work
    kwargs.setdefault('instance_relative_config', True)
    app = Flask('evesrp', **kwargs)
    app.request_class = AcceptRequest
    app.config.from_object('evesrp.default_config')
    # Push the instance folder path onto sys.path to allow importing from there
    sys.path.insert(0, app.instance_path)
    # Check in config is a dict, python config file, or importable object name,
    # in that order. Finally, check the EVESRP_SETTINGS environment variable
    # as a last resort.
    if isinstance(config, dict):
        app.config.update(config)
    elif isinstance(config, six.string_types):
        if config.endswith(('.txt', '.py', '.cfg')):
            app.config.from_pyfile(config)
        else:
            app.config.from_object(config)
    elif config is None:
        try:
            app.config.from_pyfile('config.py')
        except OSError:
            app.config.from_envvar('EVESRP_SETTINGS')

    # Register SQLAlchemy monitoring before the DB is connected
    app.before_request(sqlalchemy_before)

    db.init_app(app)

    from .views.login import login_manager
    login_manager.init_app(app)

    before_csrf = list(app.before_request_funcs[None])
    csrf.init_app(app)
    # Remove the context processor that checks CSRF values. All it is used for
    # is the template function.
    app.before_request_funcs[None] = before_csrf

    # Hook up OAuth
    oauth.init_app(app)

    # Connect views
    from .views import index, error_page, update_navbar, divisions, login,\
            requests, api
    app.add_url_rule(rule=u'/', view_func=index)
    for error_code in (400, 403, 404, 500):
        app.register_error_handler(error_code, error_page)
    app.after_request(update_navbar)
    app.register_blueprint(divisions.blueprint, url_prefix='/division')
    app.register_blueprint(login.blueprint)
    app.register_blueprint(requests.blueprint, url_prefix='/request')
    app.register_blueprint(api.api, url_prefix='/api')
    app.register_blueprint(api.filters, url_prefix='/api/filter')

    from .views import request_count
    app.add_template_global(request_count)

    from .json import SRPEncoder
    app.json_encoder=SRPEncoder

    # Configure the Jinja context
    # Inject variables into the context
    from .auth import PermissionType
    @app.context_processor
    def inject_enums():
        return {
            'ActionType': models.ActionType,
            'PermissionType': PermissionType,
            'app_version': __version__,
            'site_name': app.config['SRP_SITE_NAME'],
            'url_for_page': requests.url_for_page,
        }
    # Auto-trim whitespace
    app.jinja_env.trim_blocks = True
    app.jinja_env.lstrip_blocks = True

    init_app(app)

    return app
Example #27
0
def create_app(config_name):
    """Create a Flask instance based on a Config subclass.

    Args:
        config_name (str): The config mode we want to load. Options for this
            are enumerated in the CONFIG dictionary in ``/config.py``.

    Returns:
        app (Flask): A Flask application instance with the config options
            specified by the Config subclass specified by
            ``CONFIG[config_name]``.
    """
    app = Flask(__name__)
    app.config.from_object(CONFIG[config_name])
    CONFIG[config_name].init_app(app)

    db.init_app(app)
    login_manager.init_app(app)
    mail.init_app(app)

    from .auth import auth as auth_blueprint
    from .seeds import seeds as seeds_blueprint
    from .shop import shop as shop_blueprint
    from .shop.models import Order

    app.register_blueprint(auth_blueprint, url_prefix='/auth')
    app.register_blueprint(seeds_blueprint)
    app.register_blueprint(shop_blueprint, url_prefix='/shop')

    stripe.api_key = app.config.get('STRIPE_SECRET_KEY')

    ship_date = format_ship_date(get_ship_date())

    # Add redirects
    rdf = RedirectsFile(app.config.get('REDIRECTS_FILE'))
    if rdf.exists():
        rdf.load()
        rdf.add_all_to_app(app)

    # Clear pending changes messages
    pending = Pending(app.config.get('PENDING_FILE'))
    if pending.has_content():  # pragma: no cover
        pending.clear()
        pending.save()

    def sum_cart_items():
        o = Order.load(current_user)
        try:
            return o.number_of_items
        except:
            return 0

    # Make things available to Jinja
    app.add_template_global(ship_date, 'ship_date')
    app.add_template_global(Permission, 'Permission')
    app.add_template_global(pluralize, 'pluralize')
    app.add_template_global(load_nav_data, 'load_nav_data')
    app.add_template_global(slugify, 'slugify')
    app.add_template_global(sum_cart_items, 'sum_cart_items')

    # Error pages
    @app.errorhandler(404)
    def page_not_found(e):
        # TODO: Change this to use a logger.
        print('404 not found: {}'.format(request.url))
        return render_template('errors/404.html'), 404

    return app
Example #28
0
import logging
import os

from flask import Flask, render_template
from flask_upstatic import Upstatic

logger = logging.getLogger('flask_upstatic')
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())


if __name__ == '__main__':
  app = Flask(__name__)
  app.config.update(
    UPSTATIC_S3_ACCESS_KEY_ID=os.environ.get('AWS_ACCESS_KEY_ID'),
    UPSTATIC_S3_SECRET_ACCESS_KEY=os.environ.get('AWS_SECRET_ACCESS_KEY'),
    UPSTATIC_S3_BUCKET_NAME='flask_upstatic_example',
  )
  upstatic = Upstatic(app)
  upstatic.upload()

  app.add_template_global(upstatic.url_for)

  @app.route('/')
  def index():
    return render_template('index.html')

  app.run(host='0.0.0.0')
def create_app(config={}):
    app = Flask(__name__, instance_relative_config=True)
    app.config.update(DEFAULT_CONFIG)
    app.config.from_pyfile('settings.py', silent=True)
    app.config.update(config)

    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        return getattr(g, 'language', 'en')

    assets_env.init_app(app)
    db.init_app(app)

    app.register_blueprint(admin)
    app.register_blueprint(auth)
    app.register_blueprint(meetings)

    app.add_template_filter(activity_map)
    app.add_template_filter(countries)
    app.add_template_filter(country_in)
    app.add_template_filter(region_in)
    app.add_template_filter(crop)
    app.add_template_filter(nl2br)
    app.add_template_filter(convert_to_dict, name='dict')
    app.add_template_filter(no_image_cache)
    app.add_template_filter(pluralize)
    app.add_template_filter(slugify)
    app.add_template_filter(sort_by_tuple_element)
    app.add_template_filter(clean_html)
    app.add_template_global(active)
    app.add_template_global(date_processor)
    app.add_template_global(inject_static_file)
    app.add_template_global(inject_badge_context)
    app.add_template_global(has_perm)
    app.add_template_global(Logo, name='get_logo')

    @app.context_processor
    def inject_context():
        return {
            'CustomField': {
                'TEXT': CustomField.TEXT,
                'IMAGE': CustomField.IMAGE,
                'EMAIL': CustomField.EMAIL,
                'CHECKBOX': CustomField.CHECKBOX,
                'SELECT': CustomField.SELECT,
                'COUNTRY': CustomField.COUNTRY,
                'LANGUAGE': CustomField.LANGUAGE,
                'CATEGORY': CustomField.CATEGORY,
                'EVENT': CustomField.EVENT,
            },
            'Participant': {
                'PARTICIPANT': Participant.PARTICIPANT,
                'MEDIA': Participant.MEDIA,
                'DEFAULT': Participant.DEFAULT,
                'DEFAULT_MEDIA': Participant.DEFAULT_MEDIA,
            },
        }

    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'
    login_manager.login_message_category = 'warning'

    mail.init_app(app)
    redis_store.init_app(app, strict=True)

    if app.config.get('SENTRY_DSN'):
        sentry.init_app(app)

    _configure_uploads(app)
    _configure_logging(app)

    app.config['REPRESENTING_TEMPLATES'] = (
        path('meetings/participant/representing'))

    _translations = app.config['TRANSLATIONS']
    if _DEFAULT_LANG not in _translations:
        _translations = [_DEFAULT_LANG] + _translations
    app.config['TRANSLATIONS'] = _translations

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

    @app.route('/')
    def index():
        return redirect(url_for('meetings.home'))

    @app.errorhandler(413)
    def file_too_large(error):
        mb = 1024 * 1024
        max_size = app.config.get('UPLOAD_SIZE', mb) / mb
        return render_template('_file_too_large.html',
                               max_size=max_size,
                               url=request.url), 413

    return app
Example #30
0
    response.headers['X-Frame-Options'] = 'SAMEORIGIN'
    response.headers['X-XSS-Protection'] = '1; mode=block'

    # Todo: activate Content-Security-Policy after removal of every inline CSS and JavaScript
    # response.headers['Content-Security-Policy'] = "default-src 'self'"
    return response


@app.teardown_request
def teardown_request(exception):
    if hasattr(g, 'db'):
        g.db.close()


@app.context_processor
def inject_search_form():
    return dict(search_form=GlobalSearchForm(prefix="global"))


app.register_blueprint(filters.blueprint)
app.add_template_global(debug_model, 'debug_model')


@app.context_processor
def inject_debug():
    return dict(debug=app.debug)


if __name__ == "__main__":  # pragma: no cover
    app.run()