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 test_upload(self): class FileObj(StringIO): def close(self): global RESULT RESULT = True class MyRequest(Request): def _get_file_stream(self, *args, **kwargs): return FileObj() app = Flask(__name__) app.debug = True app.request_class = MyRequest @app.route("/upload", methods=['POST']) def upload(): client = app.test_client() resp = client.post('/upload', data={ 'file': (BytesIO(b'my file contents'), 'hello world.jpg'), }) self.assertEqual( 'ok', resp.data, ) global RESULT self.assertTrue(RESULT)
def test_1(self): class FileObj(StringIO): def close(self): print 'in file close' global RESULT RESULT = True class MyRequest(Request): def _get_file_stream(*args, **kwargs): return FileObj() app = Flask(__name__) app.debug = True app.request_class = MyRequest # Test uploaded file @app.route("/uploader", methods=['POST']) def upload_file(): f = request.files['file'] print 'in upload handler' self.assertIsInstance( f.stream, FileObj, ) f.close() return 'ok' client = app.test_client() resp = client.post( '/uploader', data = {'file': (StringIO('my file contents'), 'test.jpg'),}) self.assertEqual('ok', resp.data,) global RESULT self.assertTrue(RESULT)
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': '******', 'email': '*****@*****.**'} app.request_class = CustomRequest return app
def test_1(self): class FileObj(StringIO): # Close file & remove from file system def tearDown(self): global RESULT RESULT = True class MyRequest(Request): # Get file def _get_file_stream(*args, **kwargs): return FileObj() # Initialize app app = Flask(__name__) app.debug = True app.request_class = MyRequest @app.route("/", methods=['POST']) # Test file upload def upload(): f = request.files['file'] self.assertIsInstance(f.stream, FileObj,) f.tearDown() return 'OK' # Post image client = app.test_client() response = client.post('/', data = {'file': (StringIO('content'), 'test.jpg'),}) self.assertEqual('OK', response.data,) global RESULT self.assertTrue(RESULT)
def create_app() -> Flask: my_app = Flask(__name__) # Configure sessions my_app.session_interface = MySessionInterface() my_app.request_class = MyRequest # Configure Jinja configure_jinja.configure(my_app) # Configure db my_app.config['SQLALCHEMY_DATABASE_URI'] = my_site.config.database[ 'location'] db.init_app(my_app) with my_app.app_context(): db_wrapper.build_if_needed(db) # Configure routing & controllers # import and register all controllers here from .controllers import (auth_controller) my_app.register_blueprint(auth_controller.auth_blueprint) # Configure error handling for error in list(range(400, 420)) + list(range(500, 506)): my_app.error_handler_spec[None][error] = json_error_description return my_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': '******', 'email': '*****@*****.**' } app.request_class = CustomRequest 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': '******', 'email': '*****@*****.**' } 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 create_app(): app = Flask(__name__) app.request_class = CustomRequest load_config(app) register_blueprints(app) register_extensions(app) return app
def create_app(): app = Flask(__name__) app.json_encoder = JSONEncoder app.request_class = Request app.config.from_object(DefaltSettig) register(app) CORS(app, supports_credentials=True) request_first_handler(app) register_ext(app) error_handler(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_app(config_object=None): """ FLASK_ENV=development FLASK_APP=apis.document.app flask run --port=5003 """ if config_object is None: config_object = Config app = Flask(__name__) app.request_class = BigMemoryRequest app.config.from_object(config_object) app.register_blueprint(index.blueprint) app.register_blueprint(documents.blueprint) handlers.register(app) return app
def create_app(): app = Flask(__name__) app.request_class = Request app.config.from_object(config) db.init_app(app) auth.init_app(app) if sentry is not None: sentry.init_app(app, dsn=config.SENTRY_DSN) register_blueprint('app.views', app) setup_jinja2_environment(app) return app
def patch_request_class(app: Flask, size: int = 64 * 1024 * 1024 ) -> None: # pragma: no cover """Attention! This function is deprecated and due to removal in `Flask-Reuploaded 1.0`. It was necessary to restrict the max upload size, back in the days of Flask 0.6 and earlier. By default, Flask will accept uploads to an arbitrary size. While Werkzeug switches uploads from memory to a temporary file when they hit 500 KiB, it's still possible for someone to overload your disk space with a gigantic file. This patches the app's request class's `~werkzeug.BaseRequest.max_content_length` attribute so that any upload larger than the given size is rejected with an HTTP error. .. note:: In Flask 0.6, you can do this by setting the `MAX_CONTENT_LENGTH` setting, without patching the request class. To emulate this behavior, you can pass `None` as the size (you must pass it explicitly). That is the best way to call this function, as it won't break the Flask 0.6 functionality if it exists. .. versionchanged:: 0.1.1 :param app: The app to patch the request class of. :param size: The maximum size to accept, in bytes. The default is 64 MiB. If it is `None`, the app's `MAX_CONTENT_LENGTH` configuration setting will be used to patch. """ warnings.warn( "`patch_request_class` is deprecated " "and due for removal in `Flask-Reuploaded 1.0. " "Please use `MAX_CONTENT_LENGTH` instead. " "For further help please see the documentation.", DeprecationWarning) if size is None: if isinstance(app.request_class.__dict__['max_content_length'], property): return size = app.config.get('MAX_CONTENT_LENGTH') reqclass = app.request_class patched = type(reqclass.__name__, (reqclass, ), {'max_content_length': size}) app.request_class = patched
def load_conf(app: Flask): app.debug = True app.config['ROOT_DIR'] = '.' app.config['BASE_DIR'] = '.' app.config['TZ'] = 'Asia/Shanghai' app.config["JWT_ACCESS_TOKEN_EXPIRES"] = 60 * 60 * 24 app.config["JWT_REFRESH_TOKEN_EXPIRES"] = 30 app.config["SSO_LOGIGN"] = True # 是否支持单点登录 app.config[ "SECRET_KEY"] = "secret$%^&*key!@#$%^774ST$%^&*(you#!!@%never!@#$%^&guess" app.config[ "JWT_SECRET_KEY"] = "secret$%^&*key!@#$%^774@@$%^&*(you#!!@%never!@#$%^&guess" app.request_class = RequestMid app.response_class = ResponseMid CORS(app) return app
def create_app(config=None): flask_app = Flask(__name__, template_folder='templates', static_url_path='/static') flask_app.request_class = AppRequest flask_app.secret_key = 'some_secret' flask_app.register_blueprint(index_view) flask_app.register_blueprint(client_view) flask_app.register_blueprint(item_view) flask_app.register_blueprint(receipt_view) @flask_app.teardown_appcontext def shutdown_session(exception=None): if exception is None: Session.commit() Session.remove() return flask_app
def test_1(self): class FileObj(StringIO): def close(self): print 'in file close' global RESULT RESULT = True class MyRequest(Request): def _get_file_stream(self, *args, **kwargs): return FileObj() app = Flask(__name__) app.debug = True app.request_class = MyRequest @app.route("/upload", methods=['POST']) def upload(): f = request.files['file'] print 'in upload handler' self.assertIsInstance( f.stream, FileObj, ) # Note I've monkeypatched werkzeug.datastructures.FileStorage # so it wont squash exceptions f.close() #f.stream.close() return 'ok' client = app.test_client() resp = client.post( '/upload', data = { 'file': (StringIO('my file contents'), 'hello world.txt'), } ) self.assertEqual( 'ok', resp.data, ) global RESULT self.assertTrue(RESULT)
def create_app(config_object=None): """ FLASK_ENV=development FLASK_APP=apis.document.app flask run --port=5003 """ if config_object is None: config_object = Config app = Flask(__name__) app.request_class = BigMemoryRequest app.config.from_object(config_object) SENTRY_DSN = app.config.get("SENTRY_DSN") if SENTRY_DSN: import sentry_sdk from sentry_sdk.integrations.flask import FlaskIntegration from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration sentry_sdk.init(SENTRY_DSN, integrations=[FlaskIntegration(), AwsLambdaIntegration()]) app.register_blueprint(index.blueprint) app.register_blueprint(documents.blueprint) handlers.register(app) 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(): 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': '******', 'email': '*****@*****.**'} app.request_class = CustomRequest return app
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(config=None, **kwargs): load_dotenv() api = Api() app = Flask(__name__, static_folder=None, **kwargs) app.request_class = Request app.url_map.strict_slashes = False app.config.from_pyfile("../config.py") if config: app.config.update(config) db.init_app(app) register_blueprints(app) # Health check app.health_check_path = "/health-check" @app.before_request def health_check(): if request.path == app.health_check_path: return jsonify(dict(status="healthy")) @app.after_request def headers(response): response.headers["Server"] = "Test API" response.headers["Keep-Alive"] = "timeout=5, max=100" return response @app.after_request def commit_db_session(response): session.commit() return response bootstrap_app(app) init_cli(app) print(app.url_map) api.init_app(app) return app
def test_1_uploading(self): class FileObj(StringIO): def close(self): print('in file close') global RESULT RESULT = True class MyRequest(Request): def _get_file_stream(self, *args, **kwargs): return FileObj() app = Flask(__name__) app.debug = True app.request_class = MyRequest @app.route("/upload_gps", methods=['POST']) def upload(): f = request.files['file'] self.assertIsInstance( f.stream, FileObj, ) f.close() return 'ok' client = app.test_client() resp = client.post('/upload', data={ 'file': (StringIO('my file contents, texting'), 'hello world.csv'), }) self.assertEqual( 'ok', resp.data, ) global RESULT self.assertTrue(RESULT)
def test_1(self): class FileObj(BytesIO): def close(self): print('in file close') global RESULT RESULT = True class MyRequest(Request): def _get_file_stream(*args, **kwargs): return FileObj() app = Flask(__name__) app.debug = True app.request_class = MyRequest @app.route("/upload", methods=['POST']) def upload(): f = request.files['file'] print('in upload handler') self.assertIsInstance( f.stream, FileObj, ) f.close() return 'ok' client = app.test_client() resp = client.post('/upload', data={ 'file': (BytesIO(f.filename)), }) self.assertEqual( 'ok', resp.data, ) global RESULT self.assertTrue(RESULT)
def create_app(test_config=None): # Create the app object and import some config app = Flask(__name__, instance_relative_config=True) app.config.from_mapping(DATABASE=os.path.join(app.instance_path, 'db.sqlite'), ) app.config.from_pyfile("config.py") if test_config is None: app.config.from_pyfile("config.py", silent=True) else: app.config.from_mapping(test_config) # Make sure that the instance directory exists try: os.makedirs(app.instance_path) except OSError: pass # Load middleware and commands from flask_wtf.csrf import CSRFProtect csrf = CSRFProtect() csrf.init_app(app) from . import db db.init_app(app) from . import user user.init_app(app) from . import mail mail.init_app(app) from . import allocations allocations.init_app(app) from . import review review.init_app(app) from . import survey survey.init_app(app) # Raven authentication # Request class boilerplate adapted from python-ucam-webauth # documentation, required so that we can make a hostname # whitelist class R(flask.Request): trusted_hosts = app.config["TRUSTED_HOSTS"] app.request_class = R auth_decorator = AuthDecorator(desc="Downing JCR Room Ballot Survey") # Create the routes from roomsurvey.syndicate import get_syndicate_for_user, get_syndicate_invitations, update_invitation, create_syndicate from roomsurvey.user import get_user, get_year, is_syndicatable from roomsurvey.survey import get_survey_data, import_survey_data, log_survey_data from roomsurvey.allocations import get_allocation_for_user from roomsurvey.review import has_reviewed, check_review, write_review @app.before_request def before_request_handler(): g.crsid = auth_decorator.principal # fullname is ONLY set if the user is both authenticated AND in the database g.fullname = None if g.crsid: g.fullname = get_user(g.crsid) g.user_year = get_year(g.crsid) if (g.crsid and request.path != "/logout" and not request.path.startswith("/static") and not g.fullname): return render_template("unauthorised.html") g.current_time = int(time.time()) @app.route("/dashboard") @auth_decorator def dashboard(): return render_template("dashboard.html", syndicate=get_syndicate_for_user(g.crsid), invites=get_syndicate_invitations(g.crsid), survey_data=get_survey_data(g.crsid)) @app.route("/syndicate") @auth_decorator def syndicate(): return render_template( "syndicate.html", syndicate=get_syndicate_for_user(g.crsid), max_size=app.config["SYNDICATE_MAXSIZE"][g.user_year]) @app.route("/syndicate/create", methods=["POST"]) @auth_decorator def syndicate_create(): invitees = json.loads(request.form['invitees-json']) for i in invitees: resp = is_syndicatable(i, g.user_year) if not resp["ok"]: return abort(400) if len(invitees) > app.config["SYNDICATE_MAXSIZE"][g.user_year] or len( invitees) < 0: return abort(400) if len(set(invitees)) != len(invitees): return abort(400) if g.crsid not in invitees: return abort(400) if g.current_time > app.config["CLOSE_SYNDICATES"]: return abort(400) log(g.crsid, "created syndicate and invited " + ",".join(invitees)) create_syndicate(g.crsid, invitees, g.user_year) return redirect("/dashboard", 302) @app.route("/invite") @auth_decorator def invite(): return render_template("invite.html", invites=get_syndicate_invitations(g.crsid)) @app.route("/invite/accept", methods=["POST"]) @auth_decorator def invite_accept(): log(g.crsid, "has accepted a syndicate invitation") update_invitation(g.crsid, True) return redirect("/dashboard", 302) @app.route("/invite/reject", methods=["POST"]) @auth_decorator def invite_reject(): log(g.crsid, "has rejected a syndicate invitation (WARN)") update_invitation(g.crsid, False) return redirect("/dashboard", 302) @app.route("/api/is_syndicatable/<year>/<crsid>") @auth_decorator def api_is_syndicatable(year, crsid): try: year = int(year) except ValueError: return abort(400) resp = is_syndicatable(crsid, int(year)) return json.dumps(resp) @app.route("/api/survey_data/" + app.config["COGNITOFORMS_KEY"], methods=["POST"]) @csrf.exempt def api_survey_data(): if request.content_length > 65536: return abort(413) log_survey_data(request.get_data()) return import_survey_data(request.get_json()) @app.route("/survey") @auth_decorator def survey(): if g.current_time < app.config["SHOW_SURVEY"]: return abort(403) return render_template("survey.html", survey_data=get_survey_data(g.crsid)) @app.route("/") def landing(): try: session["_ucam_webauth"]["state"]["principal"] return redirect("/dashboard", 302) except KeyError: return render_template("landing.html") @app.route("/about") @auth_decorator def about(): return render_template("about.html") @app.route("/logout", methods=["POST"]) def logout(): session.clear() return redirect("/", code=302) @app.route("/allocations") @auth_decorator def allocations(): if g.current_time < app.config["SHOW_ALLOCATIONS"]: return abort(403) return render_template("allocations.html") @app.route("/review") @auth_decorator def review(): if not app.config["ROOM_REVIEWS"]: return render_template("review_no.html") room = get_allocation_for_user(g.crsid) if room is None: return abort(403) if has_reviewed(g.crsid): return render_template("review_thanks.html") return render_template("review.html", room=room) @app.route("/review", methods=["POST"]) @auth_decorator def leave_review(): if not app.config["ROOM_REVIEWS"]: return abort(403) room = get_allocation_for_user(g.crsid) if room is None: return abort(403) if has_reviewed(g.crsid): return abort(403) if not check_review(request.form): return abort(400) write_review(g.crsid, room, request.form) return render_template("review_thanks.html") # cheeky jinja function override so that we can make database calls from the templates # this is a bit of a hack but it makes the python code a lot cleaner app.jinja_env.globals.update(get_user=get_user) # The app is complete and ready to accept requests 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,
def create_app(config): # type: (SDConfig) -> Flask 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) # type: ignore app.sdconfig = config # 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) if config.DATABASE_ENGINE == "sqlite": db_uri = (config.DATABASE_ENGINE + ":///" + config.DATABASE_FILE) else: db_uri = (config.DATABASE_ENGINE + '://' + config.DATABASE_USERNAME + ':' + config.DATABASE_PASSWORD + '@' + config.DATABASE_HOST + '/' + config.DATABASE_NAME) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = db_uri db.init_app(app) app.storage = Storage(config.STORE_DIR, config.TEMP_DIR, config.JOURNALIST_KEY) app.crypto_util = CryptoUtil( scrypt_params=config.SCRYPT_PARAMS, scrypt_id_pepper=config.SCRYPT_ID_PEPPER, scrypt_gpg_pepper=config.SCRYPT_GPG_PEPPER, securedrop_root=config.SECUREDROP_ROOT, word_list=config.WORD_LIST, nouns_file=config.NOUNS, adjectives_file=config.ADJECTIVES, gpg_key_dir=config.GPG_KEY_DIR, ) @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 # type: ignore 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)) # type: ignore @app.before_request @ignore_static def setup_i18n(): """Store i18n-related 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() @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 load_instance_config(): app.instance_config = InstanceConfig.get_current() @app.before_request @ignore_static def setup_g(): """Store commonly used values in Flask's special g object""" 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() # Redirect to index with flashed message flash(Markup(msg), "important") return redirect(url_for('main.index')) 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 = app.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 = app.storage.path(g.filesystem_id) @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
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
def __init__(self, environ, populate_request=True, shallow=False): super(Request, self).__init__(environ, populate_request, shallow) if self.headers.get('X-Forwarded-Proto') == 'https': environ['wsgi.url_scheme'] = 'https' # app setup + static files app = Flask(__name__, static_url_path='', static_folder='static') socketio = SocketIO(app) # csrf_token protect csrf = SeaSurf(app) # apply SSL termination handling app.request_class = ProxiedRequest # configuration file if os.path.isfile('./DEV'): app.config.from_object('config.DebugConfiguration') else: app.config.from_object('config.BaseConfiguration') # other app'ish things login_manager = LoginManager(app) # login manager manager = Manager(app) # shell actions manager db = SQLAlchemy(app) # database connection bcrypt = Bcrypt(app) # hashing function # load our name
# -*- 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()
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
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)
# 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 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')
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
# 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
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, )
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]
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):
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
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
import json import version import crypto_util import store import template_filters from db import db_session, Source, Submission, Reply, get_one_or_else from request_that_secures_file_uploads import RequestThatSecuresFileUploads from jinja2 import evalcontextfilter import logging # This module's logger is explicitly labeled so the correct logger is used, # even when this is run from the command line (e.g. during development) log = logging.getLogger('source') app = Flask(__name__, template_folder=config.SOURCE_TEMPLATES_DIR) app.request_class = RequestThatSecuresFileUploads app.config.from_object(config.SourceInterfaceFlaskConfig) assets = Environment(app) # 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.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'
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')
# -*- 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()
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
import os from flask import Flask, got_request_exception from flask_restful import Api from flask.ext.cache import Cache from flask.ext.cors import CORS import sys from jormungandr.exceptions import log_exception from jormungandr.helper import ReverseProxied, NavitiaRequest from jormungandr import compat, utils app = Flask(__name__) app.config.from_object('jormungandr.default_settings') if 'JORMUNGANDR_CONFIG_FILE' in os.environ: app.config.from_envvar('JORMUNGANDR_CONFIG_FILE') app.request_class = NavitiaRequest CORS(app, vary_headers=True, allow_credentials=True, send_wildcard=False, headers=['Access-Control-Request-Headers', 'Authorization']) app.config['CORS_HEADERS'] = 'Content-Type' if 'LOGGER' in app.config: logging.config.dictConfig(app.config['LOGGER']) else: # Default is std out handler = logging.StreamHandler(stream=sys.stdout) app.logger.addHandler(handler) app.logger.setLevel('INFO') app.wsgi_app = ReverseProxied(app.wsgi_app) got_request_exception.connect(log_exception, app) #we want the old behavior for reqparse
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
# this enable us to use gevent for launching background task from gevent import monkey monkey.patch_all(thread=False, subprocess=False, os=False, signal=False) from flask import Flask, got_request_exception from flask_sqlalchemy import SQLAlchemy import logging.config import sys from chaos.utils import Request from chaos.publisher import Publisher from flask_cache import Cache app = Flask(__name__) app.config.from_object('chaos.default_settings') app.config.from_envvar('CHAOS_CONFIG_FILE') app.request_class = Request from chaos import new_relic new_relic.init(app.config.get(str('NEW_RELIC_CONFIG_FILE'), None)) from chaos.exceptions import log_exception got_request_exception.connect(log_exception, app) if 'LOGGER' in app.config: logging.config.dictConfig(app.config['LOGGER']) else: # Default is std out handler = logging.StreamHandler(stream=sys.stdout) app.logger.addHandler(handler) app.logger.setLevel('INFO') db = SQLAlchemy(app)
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)
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 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 = '******' password = '******' 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 )
#!/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
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)