def create_app(config=None): """Create an instance of the tentd flask application""" app = Flask("tentd") app.add_url_rule("/", "home", description) app.request_class = Request # Load the default configuration values import tentd.defaults as defaults app.config.from_object(defaults) # Load the user configuration values if isinstance(config, basestring): config = make_config(config) if not isinstance(config, dict): raise TypeError("Config argument must be a dict or string.") if config is not None: app.config.update(config) # Initialise the db for this app db.init_app(app) # Register the entity blueprints for blueprint in (entity, followers, posts): app.register_blueprint(blueprint, url_prefix=blueprint.prefix(app)) return app
def create_app(): from flask import Flask, Request, got_request_exception import rollbar.contrib.flask app = Flask(__name__) @app.route('/') def index(): return 'Index page' @app.route('/cause_error', methods=['GET', 'POST']) def cause_error(): raise Exception("Uh oh") @app.before_first_request def init_rollbar(): rollbar.init(TOKEN, 'flasktest', root=os.path.dirname(os.path.realpath(__file__)), allow_logging_basic_config=True) got_request_exception.connect(rollbar.contrib.flask.report_exception, app) class CustomRequest(Request): @property def rollbar_person(self): return {'id': '123', 'username': 'testuser', 'email': 'test@example.com'} app.request_class = CustomRequest return app
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) app.request_class = ProxiedRequest db.init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) login_manager.init_app(app) from .main import main as main_blueprint from .urls import urls as url_blueprint from .admin import admin as admin_blueprint from .auth import auth as auth_blueprint from .apartment import apartment as apartment_blueprint from .strava import strava as strava_blueprint app.register_blueprint(main_blueprint) app.register_blueprint(url_blueprint, url_prefix='/urls') app.register_blueprint(admin_blueprint, url_prefix='/admin') app.register_blueprint(auth_blueprint, url_prefix='/auth') app.register_blueprint(apartment_blueprint, url_prefix='/apartment') app.register_blueprint(strava_blueprint, url_prefix='/strava') if not app.config['SSL_DISABLE']: from flask.ext.sslify import SSLify sslify = SSLify(app) return app
def load_app(self, config): """ Called from the parent class, so we can provide the appropriate flask app for this test case. """ app = Flask('test.localhost') app.request_class = Request app.config.update(config) app.register_blueprint(test_views) app.central_userdb = UserDB(app.config['MONGO_URI'], 'eduid_am') app.session_interface = SessionFactory(app.config) return app
def create(static_url_path='', configuration=None, settings=settings, environment_variable="CRAIC_SETTINGS", blueprints=[]): """Create the Craic application. :param static_url_path: Default ``''``. Specify the URL path for static files. :param configuration: Default `None`. Python configuration file name. :param settings: Default :mod:`settings`. Default configuration settings - used only if `configuration` is not provided. :param environment_variable: Default ``'CRAIC_SETTINGS'``. The name of the environment variable that points to a configuration file - overrides any existing configuration setting. :param blueprints: Default `[]`. A list of application blueprints. """ ret_val = Flask(__name__, static_url_path=static_url_path) ret_val.request_class = Request if configuration: ret_val.config.from_pyfile(configuration) else: ret_val.config.from_object(settings) ret_val.config.from_envvar(environment_variable, silent=True) init_extensions(ret_val) init_blueprints(ret_val, *blueprints) init_middleware(ret_val) @ret_val.before_request def before_request(): g.is_local = is_local(request.environ) g.user_agent = UserAgent(request.environ) @ret_val.context_processor def context_processor(): if hasattr(g, "title"): title = gettext("Craic / %(title)s", title=g.title) else: title = gettext("Craic.") return dict(title=title) return ret_val
def create_app(configfilename=None): """Loads the configfilename in the app.config object as requested""" setup_logging() log.debug('creating application') app = Flask(__name__) setup_config(app, configfilename) setup_modules(app) setup_aux(app) # If we run behind nginx, fix the request vars if app.config['PROXYPASS']: log.debug("Loading proxy fix") app.wsgi_app = ProxyFix(app.wsgi_app) else: log.debug("Running without proxy fix") # bittorrent clients live in the stone age app.request_class = Latin1Request log.debug('setup request class') # Register the redis connect before every request app.before_request(redis_connect) log.debug('assigned before_request') return app
def create_app(): from flask import Flask, Request, got_request_exception import rollbar.contrib.flask app = Flask(__name__) @app.route('/') def index(): return 'Index page' @app.route('/cause_error', methods=['GET', 'POST']) def cause_error(): raise Exception("Uh oh") class CustomRequest(Request): @property def rollbar_person(self): return {'id': '123', 'username': 'testuser', 'email': 'test@example.com'} app.request_class = CustomRequest return app
import pymongo from urlparse import urlparse import datetime import logging logging.basicConfig(level=logging.DEBUG) HEADERS_TO_COPY = ['Content-Type'] class SimpleRequest(Request): want_form_data_parsed = False data = None app = Flask(__name__) app.request_class = SimpleRequest MONGO_URL = os.environ.get('MONGOHQ_URL') if MONGO_URL: conn = pymongo.MongoClient(MONGO_URL) db = conn[urlparse(MONGO_URL).path[1:]] else: conn = pymongo.MongoClient('localhost', 27017) db = conn[__name__] @app.route('/', defaults={'path': ''}, methods=['GET']) @app.route('/<path:path>', methods=['GET']) def catch_all_get(path): doc = db.state.find_one({'_id': path})
import os import json from flask import Flask, jsonify from sqlalchemy import create_engine from sqlalchemy.pool import StaticPool from sqlalchemy.orm import sessionmaker, scoped_session from .orm.mappings import metadata from .models import User, Blog, Entry, Client from .services import EntryService, BlogService, UserService, OAuthService from .oauth import OAuthRequest app = Flask('faust') app.request_class = OAuthRequest try: username = 'vagrant' password = 'vagrant' host = 'localhost' port = 5432 name = 'faust' connection_string = 'postgresql://%s:%s@%s:%d/%s' % (username, password, host, port, name) engine = create_engine(connection_string) except Exception: connection_string = 'sqlite:///:memory:' engine = create_engine(connection_string, connect_args={'check_same_thread':False}, poolclass=StaticPool, echo=False )
if len(get_ip_users( request.remote_addr )) >= NUM_USERS_REQUIRED: state = "unlocked" else: state = "locked" return render_template('index.html', **locals()) @app.route('/add') def cookie_insertion(): redirect_to_index = redirect('/') response = make_response(redirect_to_index) # Create random cookie id cookie = '%030x' % random.randrange(256**15) # Don't expire for a month expires = datetime.now() + timedelta(days=30) response.set_cookie('existing_user', cookie, expires=expires) return response @app.route('/critical_mass_reached') def critical_mass_reached(): num_users = len(get_ip_users( request.remote_addr )) percent = min(100 * num_users/NUM_USERS_REQUIRED,100) return Response("%s,%s" % (percent,num_users), mimetype='text/plain') if __name__ == '__main__': # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) # App debugging on app.debug = True # Workaround for Heroku Request IPs app.request_class = ProxiedRequest app.run(host='0.0.0.0', port=port)
from data_models import Quote, Tag, Vote from jsonify import jsonify import flask_override from db import db from sql import db_session # yuck, we shouldnt dep on this from basic_auth import FlaskRealmDigestDB from news import News from rest import build_link, add_loc_hdr, add_link_hdr # app config SECRET_KEY = '\xfb\x12\xdf\xa1@i\xd6>V\xc0\xbb\x8fp\x16#Z\x0b\x81\xeb\x16' DEBUG = True CACHE_TYPE = 'simple' app = Flask(__name__) app.request_class = flask_override.Request app.config.from_object(__name__) app.wsgi_app = ProxyFix(app.wsgi_app) cache = Cache(app) navs = [ build_link('/top', 'pyqdb/quotes', Quote.list_json_mimetype, title='Top'), build_link('/quotes', 'pyqdb/quotes', Quote.list_json_mimetype, title='Browse'), build_link('/random', 'pyqdb/quotes', Quote.list_json_mimetype, title='Random'), build_link('/tags', 'pyqdb/tags', Tag.list_json_mimetype, title='Tags'), build_link('/search', '', 'application/json', title='Search'), build_link('/quotes/new', 'pyqdb/quote/new', Quote.json_mimetype, title='Submit') ] authDB = FlaskRealmDigestDB('MyAuthRealm')
def create_app(config): app = Flask(__name__, template_folder=config.SOURCE_TEMPLATES_DIR, static_folder=path.join(config.SECUREDROP_ROOT, 'static')) app.request_class = RequestThatSecuresFileUploads app.config.from_object(config.SourceInterfaceFlaskConfig) # The default CSRF token expiration is 1 hour. Since large uploads can # take longer than an hour over Tor, we increase the valid window to 24h. app.config['WTF_CSRF_TIME_LIMIT'] = 60 * 60 * 24 CSRFProtect(app) @app.errorhandler(CSRFError) def handle_csrf_error(e): msg = render_template('session_timeout.html') session.clear() flash(Markup(msg), "important") return redirect(url_for('main.index')) assets = Environment(app) app.config['assets'] = assets i18n.setup_app(config, app) app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True app.jinja_env.globals['version'] = version.__version__ if getattr(config, 'CUSTOM_HEADER_IMAGE', None): app.jinja_env.globals['header_image'] = config.CUSTOM_HEADER_IMAGE app.jinja_env.globals['use_custom_header_image'] = True else: app.jinja_env.globals['header_image'] = 'logo.png' app.jinja_env.globals['use_custom_header_image'] = False app.jinja_env.filters['rel_datetime_format'] = \ template_filters.rel_datetime_format app.jinja_env.filters['nl2br'] = evalcontextfilter(template_filters.nl2br) app.jinja_env.filters['filesizeformat'] = template_filters.filesizeformat for module in [main, info, api]: app.register_blueprint(module.make_blueprint(config)) @app.before_request @ignore_static def check_tor2web(): # ignore_static here so we only flash a single message warning # about Tor2Web, corresponding to the initial page load. if 'X-tor2web' in request.headers: flash(Markup(gettext( '<strong>WARNING: </strong> ' 'You appear to be using Tor2Web. ' 'This <strong> does not </strong> ' 'provide anonymity. ' '<a href="{url}">Why is this dangerous?</a>') .format(url=url_for('info.tor2web_warning'))), "banner-warning") @app.before_request @ignore_static def setup_g(): """Store commonly used values in Flask's special g object""" g.locale = i18n.get_locale(config) g.text_direction = i18n.get_text_direction(g.locale) g.html_lang = i18n.locale_to_rfc_5646(g.locale) g.locales = i18n.get_locale2name() if 'expires' in session and datetime.utcnow() >= session['expires']: msg = render_template('session_timeout.html') # clear the session after we render the message so it's localized session.clear() flash(Markup(msg), "important") session['expires'] = datetime.utcnow() + \ timedelta(minutes=getattr(config, 'SESSION_EXPIRATION_MINUTES', 120)) # ignore_static here because `crypto_util.hash_codename` is scrypt # (very time consuming), and we don't need to waste time running if # we're just serving a static resource that won't need to access # these common values. if logged_in(): g.codename = session['codename'] g.filesystem_id = crypto_util.hash_codename(g.codename) try: g.source = Source.query \ .filter(Source.filesystem_id == g.filesystem_id) \ .one() except NoResultFound as e: app.logger.error( "Found no Sources when one was expected: %s" % (e,)) del session['logged_in'] del session['codename'] return redirect(url_for('main.index')) g.loc = store.path(g.filesystem_id) @app.teardown_appcontext def shutdown_session(exception=None): """Automatically remove database sessions at the end of the request, or when the application shuts down""" db_session.remove() @app.errorhandler(404) def page_not_found(error): return render_template('notfound.html'), 404 @app.errorhandler(500) def internal_error(error): return render_template('error.html'), 500 return app
#!/usr/bin/env python import socket from flask import Flask from flask import Request, request from functools import partial import json from werkzeug.datastructures import ImmutableOrderedMultiDict class OrderedRequest(Request): parameter_storage_class = ImmutableOrderedMultiDict app = Flask(__name__) app.request_class = OrderedRequest SOCKET_HOST = "lsnag.int.unavco.org" SOCKET_PORT = 8080 def standardize_json(result, headers = None): """ LiveService returns json with the headers first (if no columns are specified) and then each row of data, like a csv file. This function will turn this result into a more standard version of json """ json_result = json.loads(result) if headers is None: headers = json_result.pop(0) # Get a partial that we can pass to map
from flask import Flask from flask_restful import Api from flask.ext.login import LoginManager import skwele.views as views from skwele.request import Request from skwele.resources.user import user_loader, User, UserList from skwele.resources.org import Org, OrgList from skwele.resources.dataset import Dataset, DatasetList app = Flask(__name__) app.request_class = Request api = Api(app) app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' login_manager = LoginManager() login_manager.init_app(app) login_manager.user_loader(user_loader) # # Flask-RESTful routing # api.add_resource(UserList, '/users') api.add_resource(User, '/users/<id>', endpoint='user') api.add_resource(OrgList, '/orgs') api.add_resource(Org, '/orgs/<id>', endpoint='org') api.add_resource(DatasetList, '/datasets') api.add_resource(Dataset, '/datasets/<id>', endpoint='dataset')
class JSONRequest(Request): # from http://flask.pocoo.org/snippets/45/ def wants_json(self): mimes = json_mimetypes mimes.append('text/html') best = self.accept_mimetypes.best_match(mimes) return best in json_mimetypes and \ self.accept_mimetypes[best] > \ self.accept_mimetypes['text/html'] app = Flask(__name__) app.config.from_object(config) app.request_class = JSONRequest app.jinja_env.filters['datetime'] = format_datetime app.jinja_env.filters['isodatetime'] = lambda d: d.isoformat() + 'Z' app.jinja_env.filters['format_currency'] = format_currency app.static_folder = 'static' redis_conn = redis.from_url(app.config['REDIS_URL']) app.session_interface = session.RedisSessionInterface(redis_conn) csrf = SeaSurf(app) db = SQLAlchemy(app) migrate = Migrate(app, db) login_manager = LoginManager() login_manager.login_view = "auth.login" login_manager.init_app(app)
import config import lib from flask import Flask, Request from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_object(config) app.request_class = lib.Request db = SQLAlchemy(app) def format_datetime(value): return value.strftime("%Y-%m-%d %H:%M:%S %z") app.jinja_env.filters['datetime'] = format_datetime import foodforus.views if not app.debug: import logging from logging.handlers import SMTPHandler mail_handler = SMTPHandler('127.0.0.1', app.config['MAIL_FROM'], app.config['ADMINS'], "foodforus error") mail_handler.setFormatter(logging.Formatter('''\ Message type: %(levelname)s Time: %(asctime)s %(message)s ''')) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler)
def create_app(config_filename=None): app = Flask(__name__) app.request_class = Request app.url_map.converters['re'] = RegexConverter if config_filename is None: HerokuConfig(app) else: AppConfig(app, config_filename) from_envvars(app.config, prefix='') app.debug = app.config.get('DEBUG') # TODO: these variables probably aren't unjsonnable anymore # push all variables into the environment unjsonnable = (datetime, timedelta) data = {k: json.dumps(v) for k, v in app.config.items() if not isinstance(v, unjsonnable)} os.environ.update(data) # app.logger.info('App is running on port %s', os.environ.get('PORT')) if app.config['DEBUG'] is not True: log_level = app.config.get('LOG_LEVEL', 'DEBUG') app.logger.setLevel(getattr(logging, log_level.upper())) import bauble.db as db if 'LOG_SQL' in os.environ: logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO) db.init_app(app) # register flask extensionsa SSLify(app, permanent=True) app.login_manager = LoginManager(app) app.login_manager.login_view = "auth.login" app.mail = Mail(app) app.babel = Babel(app) from .assets import init_app init_app(app) # TODO: just import everything controllers for controller in ['auth', 'index', 'batch']: module = import_module('bauble.controllers.{}'.format(controller)) app.register_blueprint(module.blueprint) from bauble.resource import Resource controllers = ['search', 'family', 'genus', 'taxon', 'accession', 'plant', 'location', 'vernacular_name'] for controller in controllers: module = import_module('bauble.controllers.{}'.format(controller)) for attr_name in dir(module): attr = getattr(module, attr_name) # find all the blueprints in the files if isinstance(attr, Blueprint): app.register_blueprint(attr) # if isclass(attr) and issubclass(attr, Blueprint) and attr != Resource: # app.register_blueprint(attr()) from bauble.error import init_errorhandlers init_errorhandlers(app) app.json_encoder = JSONEncoder return app
from flask import json from flask import Flask from flask.ext import gae_tests from flask.ext import gae_blobstore from google.appengine.api import files from google.appengine.ext import ndb # test application.. class TestModel(ndb.Model): blob_key = ndb.BlobKeyProperty() app = Flask(__name__) app.debug = True app.request_class = gae_tests.FileUploadRequest @app.route('/test_upload', methods=['POST', 'OPTIONS', 'HEAD', 'PUT']) @gae_blobstore.upload_blobs() def test_upload(uploads): entities = [] try: for upload in uploads: entity = TestModel( blob_key=upload.blob_key) entities.append(entity) blob_info = upload.blob_info logging.info('upload.blob_info: %s', blob_info) ndb.put_multi(entities) except: # rollback the operation and delete the blobs,
app = Flask(__name__) app.config.from_object('clio.settings') try: app.config.from_envvar('CLIO_SETTINGS') except RuntimeError: if os.path.exists('/etc/clio/app.conf'): app.logger.debug("couldn't load settings from file in envvar. trying /etc/clio/app.conf") try: app.config.from_pyfile('/etc/clio/app.conf') except RuntimeError: app.logger.debug("unable to find any settings files. using defaults in local settings module.") else: app.logger.debug("unable to find any settings files. using defaults in local settings module.") from utils import ExtRequest app.request_class = ExtRequest mongo_conn = None def get_mongo_conn(): global mongo_conn if mongo_conn is None: mongo_conn = pymongo.Connection(app.config['MONGO_HOSTS'], app.config['MONGO_PORT']).clio return mongo_conn def validify_data(data): if not isinstance(data, dict): return data for key in data.iterkeys(): if isinstance(data[key], dict):
from raven import Client from raven.middleware import Sentry from yoi.account.user import bp as account from yoi.config import (secret, database_url, in_production, canonical_domain, always_secure) from yoi import dweeb from yoi.flask_genshi import Genshi, render_response from yoi import middleware from yoi.resources import static_url app = Flask(__name__) app.request_class = dweeb.Request app.genshi = Genshi(app) app.db = SQLAlchemy(app) app.register_blueprint(account) # FIXME - Use app.config.from_object app.config['DEBUG'] = True app.config['PROPAGATE_EXCEPTIONS'] = True app.config['SQLALCHEMY_DATABASE_URI'] = database_url app.config['SECRET_KEY'] = secret if canonical_domain: app.config['SESSION_COOKIE_DOMAIN'] = canonical_domain app.config['SESSION_COOKIE_HTTPONLY'] = True
from flask import Flask app = Flask(__name__) app.config.from_object('coinvibes.settings') import coinvibes.views import coinvibes.exchange_apis import coinvibes.utils import coinvibes.api_v1 import analytics analytics.init('5asae1e0a2gpb8uu0sx0') ## use HerokuRequest class so we get real IPs app.request_class = utils.ProxiedRequest
DEBUG_MODE = settings.DEBUG_MODE DIRNAME = os.path.dirname(__file__) if not DIRNAME: DIRNAME = '/home/ki/my_projects/dartz_spb_ru__shop/dartz_shop/src' DB_NAME = '%s/items.csv' % DIRNAME LOCKFILE = '%s/items.lock' % DIRNAME class CyrillicRequest(Request): url_charset = 'cp1251' app = Flask(__name__) if not DEBUG_MODE: app.request_class = CyrillicRequest # Turn of on production app.debug = DEBUG_MODE #============================= # UTILS #============================= def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs): # csv.py doesn't do Unicode; encode temporarily as UTF-8: csv_reader = csv.reader(unicode_csv_data, dialect=dialect, **kwargs) for row in csv_reader: # decode UTF-8 back to Unicode, cell by cell: yield [unicode(cell, 'utf-8') for cell in row]
# Allow login manager to load a user from the database @lm.user_loader def load_user(id): if id is not None: return User.query.get(int(id)) else: return None # Remember the current user @app.before_request def before_request(): g.user = current_user # Replace the remote_addr property so that it returns a non-proxy IP class HerokuRequest(Request): @property def remote_addr(self): forwarded_for = self.environ.get("HTTP_X_FORWARDED_FOR", None) if forwarded_for: # If the object contains multiple addresses, the actual IP is first if "," in forwarded_for: return fwd.split(",")[0] else: return forwarded_for # Otherwise, return the default value else: return self.environ.get("REMOTE_ADDR") # Use the HerokuRequest class so that the actual IPs are retrieved app.request_class = HerokuRequest
# -*- coding: UTF-8 -*- # vim: set ts=4 sw=4 expandtab : from flask import Flask, Response, jsonify, request, abort import complexform app = Flask(__name__) app.request_class = complexform.ComplexFormRequest @app.route("/", methods=["GET", "POST", "PATCH", "DELETE"]) def index(): print "REQUEST" import pdb; pdb.set_trace() return "OK" if __name__ == '__main__': app.run()
# postgres unicode psycopg2.extensions.register_type(psycopg2.extensions.UNICODE) psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY) from psycopg2.extras import NamedTupleCursor from itsdangerous import URLSafeSerializer from functools import wraps from pkg_resources import resource_string from datetime import datetime from pyuca import Collator collator = Collator() class MyRequest(Request): parameter_storage_class = OrderedMultiDict app.request_class = MyRequest from schema import Charakteristika if 'CHARAKTERISTIKA_DEBUG' in os.environ: app.debug = True from local_settings import active_config config = active_config(app) app.secret_key = config.secret deform_bp = Blueprint('deform', 'deform', static_folder='static', url_prefix='/deform') app.register_blueprint(deform_bp) form_deform_templates = resource_filename('deform', 'templates') form_my_templates = resource_filename(__name__, 'templates')
from backdrop import statsd from backdrop.core.data_set import DataSet from backdrop.core.flaskutils import DataSetConverter from backdrop.write.decompressing_request import DecompressingRequest from .validation import auth_header_is_valid, extract_bearer_token from ..core import log_handler, cache_control from ..core.errors import ParseError, ValidationError from ..core.flaskutils import generate_request_id from ..core.storage.storage_factory import create_storage_engine ENVIRONMENT = getenv("ENVIRONMENT", "development") app = Flask("backdrop.write.api") # We want to allow clients to compress large JSON documents. app.request_class = DecompressingRequest feature_flags = FeatureFlag(app) # Configuration app.config.from_object( "backdrop.write.config.{}".format(ENVIRONMENT)) storage = create_storage_engine(app.config) admin_api = client.AdminAPI( app.config['STAGECRAFT_URL'], app.config['SIGNON_API_USER_TOKEN'], dry_run=False, request_id_fn=generate_request_id, )
return self.readline() class FileShareRequest(Request): def __init__(self, environ, populate_request=True, shallow=False): environ = copy(environ) stream = ProgressWsgiInputWrapper(environ['wsgi.input'], get_content_length(environ)) environ['wsgi.input'] = stream super(FileShareRequest, self).__init__(environ, populate_request, shallow) progress_streams[self.path] = stream app.request_class = FileShareRequest @app.route('/') def index(): global upload_id upload_id += 1 return render_template('index.html', upload_id=upload_id) @app.route('/upload/<upload_id>', methods=["POST"]) def upload(upload_id): print request.files
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
setup_logger(cfg["logging"]["file"], cfg["logging"]["level"]) # Init Rollbar @app.before_first_request def init_rollbar(): rollbar.init( cfg["rollbar"]["token"], cfg["rollbar"]["environment"], root=os.path.dirname(os.path.realpath(__file__)), allow_logging_basic_config=False ) got_request_exception.connect(rollbar.contrib.flask.report_exception, app) class CustomRequest(Request): @property def rollbar_person(self): from flask import session return {'id': session['user_id'], 'username': session['user_name'], 'email': session['email']} app.request_class = CustomRequest # Create Views from flock import views # Run using flask development server # app.run(cfg["web_server"]["host"], cfg["web_server"]["port"]) # Run with Tornado http_server = HTTPServer(WSGIContainer(app)) http_server.listen(cfg["web_server"]["port"], address=cfg["web_server"]["host"]) IOLoop.instance().start()
"%(asctime)s - %(name)s - " + \ "%(levelname)s\n%(message)s") file_handler.setFormatter(formatter) app.logger.addHandler(file_handler) # initialize configured database connections for username, password, database, label, hidden in config.DEFAULT_DATABASES: models.add_database(username, password, database, label, hidden) class LimitedRequest(Request): """ extending Flask's request class to limit form uploads to 500 MB """ max_form_memory_size = 500 * 1024 * 1024 app.request_class = LimitedRequest app.config.update( SECRET_KEY=config.SECRET_KEY, PERMANENT_SESSION_LIFETIME=datetime.timedelta(days=14), CACHE_TYPE='filesystem', CACHE_DIR=config.TEMP_DIR, MAIL_SERVER=config.MAIL_SERVER, MAIL_PORT=config.MAIL_PORT, MAIL_USE_TLS=config.MAIL_USE_TLS, MAIL_USE_SSL=config.MAIL_USE_SSL, MAIL_USERNAME=config.MAIL_USERNAME, MAIL_PASSWORD=config.MAIL_PASSWORD, DEFAULT_MAIL_SENDER=config.DEFAULT_MAIL_SENDER ) cache.init_app(app) mail.init_app(app)