def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) # Apply the SchemeProxyFix middleware app.wsgi_app = SchemeProxyFix(app.wsgi_app) # Add our cache if config_name == 'production': # pragma: no cover app.cache = FileSystemCache('recent_calls') else: app.cache = SimpleCache() bootstrap.init_app(app) db.init_app(app) from .setup import setup as setup_blueprint app.register_blueprint(setup_blueprint) from .voice import voice as voice_blueprint app.register_blueprint(voice_blueprint) # Register our custom template filter app.jinja_env.filters['national_format'] = convert_to_national_format return app
def create_app(config): app = Flask(__name__) app.config.from_pyfile(config) app.debug = app.config.get('DEBUG', False) # Setup semi-permanent cache stored in os temp directory try: app.cache_file = os.path.join( tempfile.gettempdir(), 'spectrometer-cache.p') app.cache = pickle.load(open(app.cache_file, "rb")) except IOError: app.cache = {} # Flask profiler is only active when in debug mode profiler = Profiler() profiler.init_app(app) if not app.debug: # Setup Logger logdir = app.config.get('LOG_DIR', '/var/log/spectrometer') logfile = os.path.join(logdir, 'spectrometer.log') logging.getLogger().setLevel(logging.NOTSET) formatter = logging.Formatter('%(asctime)s (%(levelname)8s) %(name)-40s: %(message)s') console_handler = logging.StreamHandler() console_handler.setFormatter(formatter) logging.getLogger().addHandler(console_handler) try: file_handler = RotatingFileHandler(logfile, maxBytes=20000000, backupCount=20) file_handler.setFormatter(formatter) logging.getLogger().addHandler(file_handler) log.info('File logger activated.') except IOError: log.warn('Unable to activate File logger. Please ensure that the ' 'log directory ({0}) is writable by the spectrometer user.'.format(logdir)) # Prep resource handlers app.gerrithandler = GerritHandler(app.config['GERRIT_URL']) app.githandlers = {} # Stop Flask debug mode from running the scheduler twice if not app.debug or os.environ.get('WERKZEUG_RUN_MAIN') == 'true': run_scheduler(app) app.route('/')(views.status) app.register_blueprint(gitapi, url_prefix='/git') app.register_blueprint(gerritapi, url_prefix='/gerrit') return app
def _make_app(): global CELERY_FLASK_APP if CELERY_FLASK_APP: return CELERY_FLASK_APP from app import init_blueprints, init_services app = Flask(__name__) if not isinstance(config, dict): app.config.update(config.settings) else: app.config.update(config) app.validator_context = ValidatorContext() app.rendering_context = RenderingContext() app.model_cache_context = ModelCacheContext() app.external_tools = external_tools load_filters(app.jinja_env, app.config) set_template_loader(app.jinja_env) init_blueprints(app) init_services(app) if not app.config['TEST']: init_sql_db(app) app.cache = external_tools.cache app.logger_name = "celery" # log_file_path = os.path.join(os.path.split(app.config['log_file_path'])[0], "celeryd.log") # file_handler = TimedRotatingFileHandler(log_file_path, backupCount=7, encoding='utf-8', when="midnight") # file_handler.setLevel() # file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')) app.logger.setLevel(app.config['CELERY_LOG_LEVEL']) CELERY_FLASK_APP = app return app
def create_app(config_file): app = Flask(__name__) # configuration settings are loaded from the `config.py` module # and (optionally) from a file `XSNIPPET_SETTINGS` env var points to app.config.from_pyfile(config_file) app.config.from_envvar('XSNIPPET_WEBUI_SETTINGS', silent=True) # set jinja2 global vars to be used in all templates app.jinja_env.globals.update( { "title": app.config["TITLE"], "abs_url_for": abs_url_for, "lang_by_short_name": lang_by_short_name } ) # set assets env assets.Environment(app) app.register_blueprint(webui) # register all needed hooks app.before_request(create_http_object) # create cache connection (it's thread-safe) app.cache = create_cache_connection(app, key_prefix="webui_") return app
def create_app(): """ Create the application and return it to the user :return: flask.Flask application """ app = Flask(__name__, static_folder=None) app.url_map.strict_slashes = False Consul(app) load_config(app) logging.config.dictConfig( app.config['OBJECTS_LOGGING'] ) app.cache = Cache(app) api = Api(app) api.add_resource(ObjectSearch, '/', '/<string:objects>', '/<string:objects>/<string:source>') api.add_resource(PositionSearch, '/pos/<string:pstring>') api.add_resource(QuerySearch, '/query') discoverer = Discoverer(app) return app
def create_application(config = None): global app # Flask! app = Flask(__name__) app.config.from_object('supysonic.config.DefaultConfig') if not config: # pragma: nocover config = IniConfig.from_common_locations() app.config.from_object(config) # Set loglevel logfile = app.config['WEBAPP']['log_file'] if logfile: # pragma: nocover from logging.handlers import TimedRotatingFileHandler handler = TimedRotatingFileHandler(logfile, when = 'midnight') handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")) logger.addHandler(handler) loglevel = app.config['WEBAPP']['log_level'] if loglevel: logger.setLevel(getattr(logging, loglevel.upper(), logging.NOTSET)) # Initialize database init_database(app.config['BASE']['database_uri']) app.wsgi_app = db_session(app.wsgi_app) # Insert unknown mimetypes for k, v in app.config['MIMETYPES'].items(): extension = '.' + k.lower() if extension not in mimetypes.types_map: mimetypes.add_type(v, extension, False) # Initialize Cache objects # Max size is MB in the config file but Cache expects bytes cache_dir = app.config['WEBAPP']['cache_dir'] max_size_cache = app.config['WEBAPP']['cache_size'] * 1024**2 max_size_transcodes = app.config['WEBAPP']['transcode_cache_size'] * 1024**2 app.cache = Cache(path.join(cache_dir, "cache"), max_size_cache) app.transcode_cache = Cache(path.join(cache_dir, "transcodes"), max_size_transcodes) # Test for the cache directory cache_path = app.config['WEBAPP']['cache_dir'] if not path.exists(cache_path): makedirs(cache_path) # pragma: nocover # Read or create secret key app.secret_key = get_secret_key('cookies_secret') # Import app sections if app.config['WEBAPP']['mount_webui']: from .frontend import frontend app.register_blueprint(frontend) if app.config['WEBAPP']['mount_api']: from .api import api app.register_blueprint(api, url_prefix = '/rest') return app
def create_app(queue, larigira): app = Flask('larigira') app.config.update(get_conf()) Bootstrap(app) app.register_blueprint(rpc) app.register_blueprint(viewui) app.register_blueprint(db) app.queue = queue app.larigira = larigira app.cache = SimpleCache() return app
def create_app(): app = Flask(__name__, static_folder=static_folder, template_folder=template_folder) app.debug = True # Configuration files app.config.from_pyfile(os.path.join( os.path.dirname(os.path.realpath(__file__)), '..', 'default_config.py' )) app.config.from_pyfile(os.path.join( os.path.dirname(os.path.realpath(__file__)), '..', 'config.py' ), silent=True) # Error handling import errors errors.init_error_handlers(app) # I18n import babel babel.init_app(app) # Caching from werkzeug.contrib.cache import SimpleCache app.cache = SimpleCache() # Template utilities app.jinja_env.add_extension('jinja2.ext.do') from website.expand import expand app.jinja_env.filters['expand'] = expand # Blueprints from views import frontend_bp from views.changelog import changelog_bp from views.humans import humans_bp from views.plugins import plugins_bp from views.docs import docs_bp from views.api import api_bp app.register_blueprint(frontend_bp) app.register_blueprint(changelog_bp, url_prefix='/changelog') app.register_blueprint(humans_bp) app.register_blueprint(plugins_bp, url_prefix='/plugins') app.register_blueprint(docs_bp, url_prefix='/docs') app.register_blueprint(api_bp, url_prefix='/api') return app
def create_app(name=None): app = Flask(name) if os.environ.get('PRODUCTION'): app.config.from_object(ProductionConfig) print "running with ProductionConfig" else: app.config.from_object(DefaultConfig) print "running with DefaultConfig" # sentry if app.config.get('SENTRY_DSN'): sentry = Sentry() sentry.init_app(app) app.sentry = sentry # assets assets = Environment(app) assets.url = app.static_url_path scss_bundle = Bundle('css/*.scss', 'css/*.css', filters=['scss', 'cssmin'], depends='css/*.scss', output='css/all.css') assets.register('scss_all', scss_bundle) js_bundle = Bundle('js/*.js', filters='rjsmin', output='js/all.js') assets.register('js_all', js_bundle) Compress(app) # cache if app.config['DEBUG']: cache_type = 'null' else: cache_type = 'simple' cache = Cache(config={'CACHE_TYPE': cache_type}) cache.init_app(app) app.cache = cache # CDN cdn = CDN() cdn.init_app(app) # workaround flask-assets / flask-cdn integration if app.config.get('CDN_HTTPS'): cdn_scheme = 'https' else: cdn_scheme = 'http' if app.config.get('FLASK_ASSETS_USE_CDN') and app.config.get('CDN_DOMAIN'): app.jinja_env.globals['FLASK_CDN'] = '%s://%s' % (cdn_scheme, app.config['CDN_DOMAIN']) return app
def create_app(): conf = Config( ) iggybase = Flask( __name__ ) iggybase.config.from_object( conf ) iggybase.cache = Cache() init_db( ) configure_blueprints(iggybase) security, user_datastore = configure_extensions( iggybase, db ) configure_error_handlers( iggybase ) configure_hook( iggybase ) add_base_routes( iggybase, conf, security, user_datastore ) return iggybase
def create_app(config_file): app = Flask(__name__) # configuration settings are loaded from the `config.py` module # and (optionally) from a file `XSNIPPET_API_SETTINGS` env var points to app.config.from_pyfile(config_file) app.config.from_envvar('XSNIPPET_API_SETTINGS', silent=True) app.register_blueprint(api) # create a database connection (it's thread-safe, so we can keep it global) app.db = create_db_connection(app) # create a cache connection (it's thread-safe too) app.cache = create_cache_connection(app, key_prefix="api_") return app
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
def create_app(config=None): app = Flask(__name__) app.config.from_object(settings) if isinstance(config, dict): app.config.update(config) elif config: app.config.from_pyfile(os.path.realpath(config)) redis_store.init_app(app) cache.init_app(app) app.cache = cache app.plugin_modules = plugin_modules slackbot = SlackBot(app) slackbot.set_handler(callback) slackbot.filter_outgoing(_filter) return app
def create_app(configuration_file = None): app = Flask(__name__) app.plugins = [] # cannot use namespace here, weak signals will disappear app.plugin_signals = { 'plugin-loaded': Signal(), 'page-loaded': Signal(), 'special-loaded': Signal(), 'page-preprocess': Signal(), 'page-postmarkdown': Signal(), 'page-treeprocess': Signal(), 'page-postprocess': Signal(), } # load a default config, and from configuration file app.config.from_object(defaults) if configuration_file: app.config.from_pyfile(configuration_file) app.db = WikiDb(app.config['REPOSITORY_PATH']) app.cache = Cache(app) app.register_module(frontend) # load plugins for plugin_name in app.config['PLUGINS']: import_name = 'qwappplugin.%s' % plugin_name qwappplugin = __import__('qwappplugin.%s' % plugin_name) plugin_module = getattr(qwappplugin, plugin_name) app.logger.debug('loading plugin %s' % plugin_module.plugin.version_string) plugin_module.plugin.register_app(app) return app
def make_app(cache=None, config=None): if config is None: config = Config() app = Flask(__name__) app.config.update(config) if cache is None: cache = Cache(config=config) app.cache = cache # Get the fallback server from shotgun_api3_registry. passthrough_server = app.config.setdefault('PASSTHROUGH_SERVER', get_shotgun_kwargs(config)['base_url'].strip('/')) app.config.setdefault('PASSTHROUGH_URL', passthrough_server + '/api3/json') # We use one HTTP session for everything. app.http_session = requests.Session() # Register the logic. app.register_blueprint(blueprint) return app
import oauth2 as oauth import config import urlparse from flask import Flask, redirect, url_for, session, render_template, request, flash, make_response from urllib import urlencode import time import json import twitter import redis app = Flask(__name__) app.secret_key = config.CKEY app.consumer = oauth.Consumer(key=config.CKEY, secret=config.CSEC) app.cache = redis.StrictRedis(host='localhost', port=6379, db=0) def verify_response(resp): if resp['status'] != '200': session.pop('request_token', None) flash('Bad response from Twitter: {0}'.format(resp)) return redirect(url_for('index')) else: return None def get_tweets(client): '''Queries Twitter API for user tweets until it gets 0 back. Concatenates and returns tweets.''' tweets = [] page = 1 while True: # repeat until tweet supply is exhausted url = config.API+'1/statuses/user_timeline.json?count=200&page={0}'.format(page) resp, content = client.request(url, 'GET', body=urlencode({
from flask import Flask, render_template, request from pymongo import MongoClient from flask.ext.cache import Cache #Korean Analyzer from konlpy.tag import Twitter import json from bson import json_util app = Flask(__name__) app.config['CACHE_TYPE'] = 'simple' app.cache = Cache(app, config={ 'CACHE_TYPE': 'filesystem', 'CACHE_DIR': 'cache-dir', 'CACHE_DEFAULT_TIMEOUT': 922337203685477580, 'CACHE_THRESHOLD': 922337203685477580 }) @app.route("/") def enter(): client = MongoClient('mongodb://localhost:27017/') db = client.reviews collection = db.app data = list() appids = collection.distinct('appid') apptitles = collection.distinct('apptitle') infos = list() for idx, appid in enumerate(appids): info = (appid,apptitles[idx],int(apptitles[idx].split('.')[0])) infos.append(info) for row in sorted(infos, key=lambda x: x[2]):
logger = logging.getLogger(__name__) formatter = logging.Formatter( "[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s") # handler = TimedRotatingFileHandler('logs/foo.log', when='midnight', interval=1) handler = RotatingFileHandler(app.config.get('LOG_FILENAME'), maxBytes=app.config.get('LOG_FILESIZE'), backupCount=1) # handler.setLevel(logging.INFO) handler.setLevel(logging.DEBUG) handler.setFormatter(formatter) app.logger.addHandler(handler) # log = logging.getLogger('werkzeug') # log.setLevel(logging.DEBUG) # log.addHandler(handler) app.cache = redis.StrictRedis(**app.config.get('REDIS_CONFIG')) app.cache.set("saDir", SA_DIR) app.cache.set("uid_track", 1) app.cache.set("session_data", {}) app.config['UPLOAD_FOLDER'] = os.path.dirname(os.path.abspath(__file__)) + SA_DIR app.config['STATIC_FOLDER'] = os.path.dirname(os.path.abspath(__file__)) + '/static' # app.session_interface = RedisSessionInterface(app.cache, key_prefix='SESSION') app.session_interface = RedisSessionInterface(app.cache, key_prefix='SESSION', use_signer=True, permanent=False) app.permanent_session_lifetime = datetime.timedelta(hours=1) try: os.mkdir(SA_DIR)
# -*- coding: utf-8 -*- __author__ = 'Glebov Boris' from flask import Flask, render_template, session from flask.ext.memcache_session import Session from werkzeug.contrib.cache import MemcachedCache import settings # Modules from modules import audio, vk_api # Setup application app = Flask(__name__) app.cache = MemcachedCache([settings.MEMCACHED['host'], settings.MEMCACHED['port']]) app.session_interface = Session() # Register modules app.register_blueprint(audio.blueprint) app.register_blueprint(vk_api.blueprint) # Define basek url-handlers @app.after_request def after_request(response): response.headers.add('Accept-Ranges', 'bytes') return response
def create_app_ext(flask_config_file=None, flask_config_dict=None, moin_config_class=None, warn_default=True, **kwargs): """ Factory for moin wsgi apps :param flask_config_file: a flask config file name (may have a MOINCFG class), if not given, a config pointed to by MOINCFG env var will be loaded (if possible). :param flask_config_dict: a dict used to update flask config (applied after flask_config_file was loaded [if given]) :param moin_config_class: if you give this, it'll be instantiated as app.cfg, otherwise it'll use MOINCFG from flask config. If that also is not there, it'll use the DefaultConfig built into MoinMoin. :param warn_default: emit a warning if moin falls back to its builtin default config (maybe user forgot to specify MOINCFG?) :param kwargs: if you give additional keyword args, the keys/values will get patched into the moin configuration class (before its instance is created) """ clock = Clock() clock.start('create_app total') app = Flask('MoinMoin') clock.start('create_app load config') if flask_config_file: app.config.from_pyfile(flask_config_file) else: if not app.config.from_envvar('MOINCFG', silent=True): # no MOINCFG env variable set, try stuff in cwd: from os import path flask_config_file = path.abspath('wikiconfig_local.py') if not path.exists(flask_config_file): flask_config_file = path.abspath('wikiconfig.py') if not path.exists(flask_config_file): flask_config_file = None if flask_config_file: app.config.from_pyfile(flask_config_file) if flask_config_dict: app.config.update(flask_config_dict) Config = moin_config_class if not Config: Config = app.config.get('MOINCFG') if not Config: if warn_default: logging.warning("using builtin default configuration") from MoinMoin.config.default import DefaultConfig as Config for key, value in kwargs.iteritems(): setattr(Config, key, value) if Config.secrets is None: # reuse the secret configured for flask (which is required for sessions) Config.secrets = app.config.get('SECRET_KEY') app.cfg = Config() clock.stop('create_app load config') clock.start('create_app register') # register converters from werkzeug.routing import BaseConverter class ItemNameConverter(BaseConverter): """Like the default :class:`UnicodeConverter`, but it also matches slashes (except at the beginning AND end). This is useful for wikis and similar applications:: Rule('/<itemname:wikipage>') Rule('/<itemname:wikipage>/edit') """ regex = '[^/]+?(/[^/]+?)*' weight = 200 app.url_map.converters['itemname'] = ItemNameConverter # register modules, before/after request functions from MoinMoin.apps.frontend import frontend frontend.before_request(before_wiki) frontend.teardown_request(teardown_wiki) app.register_blueprint(frontend) from MoinMoin.apps.admin import admin admin.before_request(before_wiki) admin.teardown_request(teardown_wiki) app.register_blueprint(admin, url_prefix='/+admin') from MoinMoin.apps.feed import feed feed.before_request(before_wiki) feed.teardown_request(teardown_wiki) app.register_blueprint(feed, url_prefix='/+feed') from MoinMoin.apps.misc import misc misc.before_request(before_wiki) misc.teardown_request(teardown_wiki) app.register_blueprint(misc, url_prefix='/+misc') from MoinMoin.apps.serve import serve app.register_blueprint(serve, url_prefix='/+serve') clock.stop('create_app register') clock.start('create_app flask-cache') cache = Cache() cache.init_app(app) app.cache = cache clock.stop('create_app flask-cache') # init storage clock.start('create_app init backends') init_backends(app) clock.stop('create_app init backends') clock.start('create_app flask-babel') i18n_init(app) clock.stop('create_app flask-babel') # configure templates clock.start('create_app flask-themes') setup_themes(app) if app.cfg.template_dirs: app.jinja_env.loader = ChoiceLoader([ FileSystemLoader(app.cfg.template_dirs), app.jinja_env.loader, ]) app.register_error_handler(403, themed_error) clock.stop('create_app flask-themes') clock.stop('create_app total') del clock return app
from flask import Flask, render_template, session, url_for, redirect, request, flash import heroku import oauth2 as oauth import redis import urlparse from urllib import urlencode import redis import json import random import os app = Flask(__name__) app.secret_key = heroku.consumer_key app.consumer = oauth.Consumer(key=heroku.consumer_key, secret=heroku.consumer_secret) app.cache = redis.from_url(os.getenv('REDISTOGO_URL', 'redis://localhost')) app.auth_url = heroku.auth_url app.site_url = heroku.site_url app.tweet_url = heroku.tweet_url app.client = oauth.Client(app.consumer) def verify_response(resp, content): if app.debug: with open(heroku.log_file, "a") as log: log.write(request.url+"\n") log.write("".join(["twitter response: ", str(resp), "\n"])) log.write("".join(["twitter content: ", content, "\n"])) if resp["status"] != "200": session.pop("access_token", None) session.pop("request_token", None) flash("Bad response from Twitter") return redirect(url_for("index"))
# Assets from flask.ext.assets import Environment assets = Environment(app) # Ensure output directory exists assets_output_dir = os.path.join(FLASK_APP_DIR, 'static', 'gen') if not os.path.exists(assets_output_dir): os.mkdir(assets_output_dir) # Email from flask.ext.mail import Mail mail = Mail(app) # Memcache from werkzeug.contrib.cache import MemcachedCache app.cache = MemcachedCache(app.config['MEMCACHED_SERVERS']) def cache_fetch(key, value_function, timeout=None): '''Mimicking Rails.cache.fetch''' global app self = app.cache data = self.get(key) if data is None: data = value_function() self.set(key, data, timeout) return data app.cache.fetch = cache_fetch # Helpers
) import memcache from flask_memcache_session import Session from werkzeug.contrib.fixers import ProxyFix # git clone https://github.com/dart-lang/py-gfm.git # cd py-gfm # python setup.py install from markdown import markdown import json, os, hashlib, tempfile, subprocess config = {} app = Flask(__name__, static_url_path='') app.cache = memcache.Client(['unix:/tmp/memcached.sock'], debug=0) app.session_interface = Session() app.session_cookie_name = "isucon_session" app.wsgi_app = ProxyFix(app.wsgi_app) # log import logging logging.basicConfig(filename='log.txt') #logging.basicConfig(filename='log.txt', level=logging.DEBUG) def load_config(): global config print("Loading configuration") env = os.environ.get('ISUCON_ENV') or 'local' with open('../config/' + env + '.json') as fp: config = json.load(fp)
do_tweets = app.config["TWITTER_ENABLED"] tweeter = twitter.Api( consumer_key=app.config["TWITTER_KEY"], consumer_secret=app.config["TWITTER_SECRET"], access_token_key=app.config["TWITTER_TOKEN"], access_token_secret=app.config["TWITTER_TOKEN_SECRET"], ) if not api.VerifyCredentials(): tweeter = False except: pass # Memcache from werkzeug.contrib.cache import MemcachedCache app.cache = MemcachedCache(app.config["MEMCACHED_SERVERS"]) def cache_fetch(key, value_function, timeout=None): """Mimicking Rails.cache.fetch""" global app self = app.cache data = self.get(key) if data is None: data = value_function() self.set(key, data, timeout) return data app.cache.fetch = cache_fetch
from flask import ( Flask, request, redirect, session, url_for, abort, render_template, _app_ctx_stack, Response, after_this_request, ) import memcache from flask_memcache_session import Session from werkzeug.contrib.fixers import ProxyFix import json, os, hashlib, tempfile, subprocess config = {} app = Flask(__name__, static_url_path='') app.cache = memcache.Client(['localhost:11211'], debug=0) app.session_interface = Session() app.session_cookie_name = "isucon_session_python" app.wsgi_app = ProxyFix(app.wsgi_app) def load_config(): global config print("Loading configuration") env = os.environ.get('ISUCON_ENV') or 'local' with open('../config/' + env + '.json') as fp: config = json.load(fp) def connect_db(): global config host = config['database']['host'] port = config['database']['port']
mail_handler.setFormatter(logging.Formatter(''' Message type: %(levelname)s Location: %(pathname)s:%(lineno)d Module: %(module)s Function: %(funcName)s Time: %(asctime)s Message: %(message)s ''')) app.logger.addHandler(mail_handler) if 'REDISTOGO_URL' in os.environ: redis_client = redis.from_url(os.environ['REDISTOGO_URL']) app.cache = RedisCache(redis_client) else: app.cache = SimpleCache() app.config['S3_BUCKET_NAME'] = 'radlibs-assets' app.config['S3_USE_CACHE_CONTROL'] = False app.config['S3_CDN_DOMAIN'] = 'd2hwb9ozcl9dk9.cloudfront.net' app.config['FLASK_ASSETS_USE_S3'] = True app.config['USE_S3_DEBUG'] = True if os.getenv('ASSETS_DEBUG'): app.config['ASSETS_DEBUG'] = True app.config['FLASK_ASSETS_USE_S3'] = False FlaskS3(app) assets = Environment(app) js = Bundle('js/jquery.min.js', 'js/bootstrap.min.js',
def create_retries_app(cache): retries_app = Flask(__name__) retries_app.PORT = 12 retries_app.cache = cache # we want the retries app to listen on all methods retries_app.url_map.add(Rule('/', endpoint='index')) @retries_app.endpoint("index") def check_retries(): json_hdr = {'Content-Type': 'application/json'} key = request.args.get('key', 'default') tries = request.args.get('tries', 3) try: tries = int(tries) except Exception: return Response(status=400, headers=json_hdr, response=json.dumps({ 'error': 'Please pass an integer number of tries', 'key': key, 'success': False, })) if key in retries_app.cache: retries_app.cache[key] -= 1 else: retries_app.cache[key] = int(tries) - 1 if retries_app.cache[key] <= 0: data = { 'key': key, 'tries_remaining': retries_app.cache[key], 'success': True } return Response(response=json.dumps(data), status=200, headers=json_hdr) else: msg = 'The server had an error. Try again {retry_times} more {time_p}' time_p = 'time' if retries_app.cache[key] == 1 else 'times' content = { 'error': msg.format(retry_times=retries_app.cache[key], time_p=time_p), 'tries_remaining': retries_app.cache[key], 'key': key, 'success': False, } return Response(response=json.dumps(content), status=500, headers=json_hdr) @retries_app.route("/counters", methods=['POST']) def reset(): key = request.values.get('key', 'default') tries = request.values.get('tries', 3) try: tries = int(tries) except Exception: return Response(status=400, headers=json_hdr, response=json.dumps({ 'error': 'Please pass an integer number of tries', 'key': key, 'success': False, })) retries_app.cache[key] = tries content = { 'key': key, 'tries_remaining': tries, 'success': True, } return Response(response=json.dumps(content), status=200, headers={'Content-Type': 'application/json'}) @retries_app.route("/counters", methods=['GET']) def counter(): content = {'counters': retries_app.cache, 'success': True} return Response(response=json.dumps(content), status=200, headers={'Content-Type': 'application/json'}) @retries_app.after_request def retries_header(resp): _log_flask(resp.status_code) resp.headers['Server'] = 'hamms' return resp return retries_app
Bootstrap(app) login_manager = LoginManager() login_manager.init_app(app) DEFAULT_CALLBACK_PATH = app.config['DEFAULT_CALLBACK_PATH'] HOST = app.config['HOST'] # This host's name CLIENT_SECRET = app.config['CLIENT_SECRET'] # Client Secret CLIENT_ID = app.config['CLIENT_ID'] # Client ID REALM = app.config['REALM'] # Keycloak realm OIDC_HOST = app.config['OIDC_HOST'] # Keycloak host OIDC_INFO_URL = '{:s}/auth/realms/{:s}/'.format(OIDC_HOST, REALM) OIDC_REDIRECT_URI = 'http://{:s}/{:s}'.format(HOST, DEFAULT_CALLBACK_PATH) # Initialize Cache app.cache = Cache(app, config={'CACHE_TYPE': 'simple'}) # initialize components from models import User db_adapter = SQLAlchemyAdapter(db, User) user_manager = UserManager(db_adapter=db_adapter, app=app, login_manager=login_manager) import views from um import um app.register_blueprint(um) from cm import cm
from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.cache import Cache from config import BaseConfig app = Flask(__name__) app.config.from_object(BaseConfig) #cache = Cache(app, config={ # 'CACHE_TYPE': 'redis', # 'CACHE_KEY_PREFIX': 'fcache', # 'CACHE_REDIS_HOST': 'redis', # 'CACHE_REDIS_PORT': '6379', # 'CACHE_REDIS_URL': 'redis://redis:6379' # }) app.cache = Cache(app) db = SQLAlchemy(app) CORS(app) class District(db.Model): __tablename__ = 'districts' id = db.Column(db.Integer, primary_key=True) statefp = db.Column(db.String) cd114fp = db.Column(db.String) geoid = db.Column(db.String) namelsad = db.Column(db.String) aland = db.Column(db.Float) awater = db.Column(db.Float) lat = db.Column(db.Float) lon = db.Column(db.Float)
from flask import render_template from flask import request from flask.ext.mobility import Mobility from werkzeug.contrib.cache import FileSystemCache from werkzeug.contrib.fixers import ProxyFix from discograph import api from discograph import ui from discograph import exceptions app = Flask(__name__) app.config.from_object('discograph.config.DevelopmentConfiguration') app.cache = FileSystemCache( app.config['FILE_CACHE_PATH'], default_timeout=app.config['FILE_CACHE_TIMEOUT'], threshold=app.config['FILE_CACHE_THRESHOLD'], ) if not os.path.exists(app.config['FILE_CACHE_PATH']): os.makedirs(app.config['FILE_CACHE_PATH']) app.register_blueprint(api.blueprint, url_prefix='/api') app.register_blueprint(ui.blueprint) app.wsgi_app = ProxyFix(app.wsgi_app) Mobility(app) @app.after_request def inject_rate_limit_headers(response): try: requests, remaining, reset = map(int, g.view_limits) except (AttributeError, ValueError):