def test_init_app_wrong_url(self): self.app.extensions.pop('redis') self.app.config['REDIS_URL'] = 'redis://wrong-host:8080/9' redis = Redis() redis.init_app(self.app) self.assertRaises(ConnectionError, redis.ping)
def test_init_app(self): self.assertIn('redis', self.app.extensions) self.app.extensions.pop('redis') redis = Redis() self.assertFalse(hasattr(redis, 'ping')) redis.init_app(self.app) redis.ping()
def test_custom_behaviour_url_init_app(self): app.config['REDIS_URL'] = 'redis://wrong-host:8080/0' obj = Redis() self.assertRaises(AttributeError, obj.ping) obj.init_app(app) self.assertRaises(ConnectionError, obj.ping)
def test_default_behaviour_url(self): host = app.config.pop('REDIS_HOST') port = app.config.pop('REDIS_PORT') db = app.config.pop('REDIS_DB') app.config['REDIS_URL'] = 'redis://%s:%d/%d' % (host, port, db) obj = Redis(app) obj.ping()
def test_config_prefix_wrong_url(self): self.app.config['REDIS2_URL'] = 'redis://wrong-host:8080/9' redis = Redis(self.app, 'REDIS2') self.assertRaises(ConnectionError, redis.ping) self.app.config['REDIS3_URL'] = 'redis://wrong-host:8080/9' redis = Redis() redis.init_app(self.app, 'REDIS3') self.assertRaises(ConnectionError, redis.ping)
def test_custom_behaviour_init_app(self): app.config['REDIS_HOST'] = 'wrong-host' app.config['REDIS_PORT'] = 8080 app.config['REDIS_DB'] = 0 obj = Redis() self.assertRaises(AttributeError, obj.ping) obj.init_app(app) self.assertRaises(ConnectionError, obj.ping)
def test_init_app_wrong_config(self): self.app.extensions.pop('redis') self.app.config['REDIS_HOST'] = 'wrong-host' self.app.config['REDIS_PORT'] = 8080 self.app.config['REDIS_DB'] = 9 redis = Redis() redis.init_app(self.app) self.assertRaises(ConnectionError, redis.ping)
def test_init_app_url(self): self.app.extensions.pop('redis') self.app.config.pop('REDIS_HOST') self.app.config.pop('REDIS_PORT') self.app.config.pop('REDIS_DB') self.app.config['REDIS_URL'] = 'redis://localhost:6379/0' redis = Redis() redis.init_app(self.app) redis.ping()
def test_default_behaviour_url_init_app(self): host = app.config.pop('REDIS_HOST') port = app.config.pop('REDIS_PORT') db = app.config.pop('REDIS_DB') app.config['REDIS_URL'] = 'redis://%s:%d/%d' % (host, port, db) obj = Redis() self.assertRaises(AttributeError, obj.ping) obj.init_app(app) obj.ping()
def test_config_prefix_url(self): self.app.config['REDIS2_URL'] = 'redis://localhost:6379/0' redis = Redis(self.app, 'REDIS2') redis.ping() self.app.config['REDIS3_URL'] = 'redis://127.0.0.1:6379/0' redis = Redis() redis.init_app(self.app, 'REDIS3') redis.ping()
def test_config_prefix(self): redis = Redis(self.app, 'REDIS_BACKUP') self.assertIn('REDIS_BACKUP', self.app.extensions['redis']) redis.ping() self.assertRaises(ValueError, Redis, self.app, 'REDIS_BACKUP') redis = Redis() redis.init_app(self.app, 'REDIS_SLAVE') self.assertIn('REDIS_SLAVE', self.app.extensions['redis']) redis.ping() self.assertRaises(ValueError, redis.init_app, self.app, 'REDIS_SLAVE')
def generate_context(config): """Creates the Flask app context and initializes any extensions such as Celery, Redis, SQLAlchemy, etc. Positional arguments: config -- partial Flask config dict from generate_config(). Returns: The Flask app instance. """ flask_app = Flask(__name__) flask_app.config.update(config) flask_app.config["TESTING"] = True flask_app.config["CELERY_ACCEPT_CONTENT"] = ["pickle"] if "SQLALCHEMY_DATABASE_URI" in flask_app.config: db = SQLAlchemy(flask_app) db.engine.execute("DROP TABLE IF EXISTS celery_tasksetmeta;") elif "REDIS_URL" in flask_app.config: redis = Redis(flask_app) redis.flushdb() Celery(flask_app) return flask_app
def test_connection_class(self): self.app.config['REDIS_CUSTOM_CLASS'] = CustomRedis self.app.config['REDIS_CUSTOM_URL'] = 'redis://localhost:6379/0' redis = Redis(self.app, 'REDIS_CUSTOM') redis.ping() self.app.extensions['redis'].pop('REDIS_CUSTOM') self.app.config['REDIS_CUSTOM_CLASS'] = 'redis.Redis' redis = Redis(self.app, 'REDIS_CUSTOM') redis.ping()
def app_context(request): """Initializes the application and sets the app context to avoid needing 'with app.app_context():'. This needs to run first, so it has been placed in the top-level conftest.py and the function starts with the letter 'a'. """ app = Flask(__name__) app.config['CELERY_ALWAYS_EAGER'] = True app.config['TESTING'] = True app.config['REDIS_URL'] = 'redis://localhost/1' app.config['CELERY_BROKER_URL'] = 'redis://localhost/1' app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost/1' Celery(app) Redis(app) context = app.app_context() context.push() request.addfinalizer(lambda: context.pop())
# yapf: enable bootstrap = Bootstrap() assets = Environment() db = SQLAlchemy() login_manager = LoginManager() login_manager.session_protection = "basic" login_manager.login_view = "auth.login" limiter = Limiter( global_limits=["300 per minute"], key_func=lambda: request.headers.get("CF-Connecting-IP", request. remote_addr), ) cache = Redis() # Asset Packages js_default_req = loader.default() js_vendor_single_page_req = loader.vendor_single_page() js_shared_single_page_req = loader.shared_single_page() js_euler_app_req = loader.euler_app() js_manager_app_req = loader.manager_app() js_myschedules_app_req = loader.myschedules_app() css_default = stylesheets.css_default() css_blog = stylesheets.css_blog() def create_celery_app(app=None): """Return a celery app in app context""" app = app or create_app(os.environ.get("ENV", "prod"),
from flask.ext.migrate import Migrate from flask.ext.themes2 import Themes from flask.ext.plugins import PluginManager # Database db = SQLAlchemy() # Login login_manager = LoginManager() # Mail mail = Mail() # Caching cache = Cache() # Redis redis = Redis() # Debugtoolbar debugtoolbar = DebugToolbarExtension() # Migrations migrate = Migrate() # Themes themes = Themes() # PluginManager plugin_manager = PluginManager()
import os from flask import Flask from flask.ext.pymongo import PyMongo from flask_debugtoolbar import DebugToolbarExtension, DebugToolbar from flask.ext.redis import Redis app = Flask('findyouflowers') app.config['MONGO_URI'] = os.environ.get('MONGOHQ_URL', 'mongodb://localhost/flowers') app.config['DEBUG'] = False if os.environ.get('HEROKU') else True app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'secret_key') app.config['DEBUG_TB_PANELS'] = DebugToolbar.config['DEBUG_TB_PANELS'] + ( 'flask_debugtoolbar_mongo.panel.MongoDebugPanel', ) app.config['REDIS_URL'] = os.environ.get('REDISCLOUD_URL', 'redis://:@localhost:6379/') redis = Redis(app) mongo = PyMongo(app) toolbar = DebugToolbarExtension(app)
from flask.ext.script import Manager import settings from scenarios.default import SCENARIO, convert_scenario from scenarios.run import run_scenario # Initialize simple Flask application app = Flask(__name__) app.config.from_object(settings) # Initialize script extension manager = Manager(app) # Setup Redis conection or connections with multiple services redis = Redis(app) redis_backup = Redis() redis_slave = Redis() @app.before_first_request def init_multiple_redis(): """ Initialize multiple redis instances if necessary. """ if app.config['MULTIPLE_REDIS_SERVERS']: redis_backup.init_app(app, 'REDIS_BACKUP') redis_slave.init_app(app, 'REDIS_SLAVE') @app.route('/')
def test_multiple(): assert 'redis' in current_app.extensions with pytest.raises(ValueError): Redis(current_app)
def test_url_default_port(self): self.app.extensions.pop('redis') self.app.config['REDIS_URL'] = 'redis://localhost/0' redis = Redis(self.app) redis.ping()
def test_one_dumb_line(): app = FakeApp() Redis(app) assert 'redis' in app.extensions
def test_unix_socket_path(self): self.app.config['REDIS_CUSTOM_HOST'] = '/does/not/exist/redis.sock' redis = Redis(self.app, 'REDIS_CUSTOM') self.assertRaisesRegexp(ConnectionError, 'unix socket', redis.ping)
# Setup logging for production if not app.config['DEBUG']: import logging from logging.handlers import RotatingFileHandler file_handler = RotatingFileHandler(os.path.join(os.path.split(os.path.abspath(__file__))[0], 'log', 'flask.log'), maxBytes=1024 * 1024, backupCount=5, encoding="UTF-8") file_handler.setLevel(logging.WARNING) app.logger.addHandler(file_handler) # Register template filters app.jinja_env.filters['datetime_to_seconds'] = datetime_to_seconds app.jinja_env.filters['seconds_to_datetime'] = seconds_to_datetime # Setup Redis connection redis = Redis() redis.init_app(app) @app.route('/', methods=['GET']) def handle_list_events(): """ Display frontpage form """ upcoming_events = get_upcoming_events() ongoing_events = get_ongoing_events() # Setup Are You A Human check ayah.configure(app.config['ARE_YOU_HUMAN_PUBLISHER_KEY'], app.config['ARE_YOU_HUMAN_SCORING_KEY']) ayah_html = ayah.get_publisher_html()
def test_url(self): self.app.extensions.pop('redis') self.app.config['REDIS_URL'] = 'redis://localhost:6379/0' redis = Redis(self.app) redis.ping()
from collections import OrderedDict import socket import os from flask import request from flask import Flask import json from flask.ext.redis import Redis app = Flask(__name__) app.config['REDIS_HOST'] = 'redis' app.config['REDIS_PORT'] = 6379 app.config['REDIS_DB'] = 0 redis1 = Redis(app) def get_environment(): ret = OrderedDict() for key in sorted(os.environ): ret[key] = os.environ[key] return ret def get_headers(): ret = OrderedDict() for key in sorted(request.headers): key = key[0] ret[key] = request.headers[key] return ret
import time import types from flask.ext.redis import Redis from sandbox import Sandbox, proxy __all__ = ('run_scenario', ) proxy.SAFE_TYPES = tuple(list(proxy.SAFE_TYPES) + [type(Redis()), set]) def run_scenario(redis, scenario): """ Run Python scenario with ``redis`` instance. """ data = {'redis': redis} results = [] sandbox = Sandbox() start = time.time() for raw in scenario.splitlines(): line = 'result = {0}'.format(raw) if not '=' in raw else raw sandbox.execute(line, {}, data) results.append((raw, data['result'] if 'result' in data else None)) return {'results': results, 'time': time.time() - start}
#!/usr/bin/env python # -*- coding: utf-8 -*- from dulwich.repo import Repo import os from flask import Flask, render_template, request, redirect, url_for, abort from flask.ext.redis import Redis import subprocess import shutil app = Flask(__name__) redis = Redis(app) redis.delete("teams") redis.delete("servers") redis.delete("dhcp") redis.delete("roles") redis.delete("envs") redis.delete("steps") redis.lpush("roles", "Application", "SGBDR", "Web", "NoSQL") redis.lpush("envs", "Blue", "Green") redis.hmset("steps", {"1": "application"}) redis.hmset("steps", {"2": "application"}) redis.hmset("steps", {"3": "application:web"}) redis.hmset("steps", {"4": "application:web:sgbdr"}) redis.hmset("steps", {"5": "application:web:sgbdr:nosql"}) redis.hmset("steps", {"6": "application:web:nosql"}) if os.path.exists("/home/pchaussalet/projects/mepc/filer/deploy"): shutil.rmtree("/home/pchaussalet/projects/mepc/filer/deploy") os.mkdir("/home/pchaussalet/projects/mepc/filer/deploy")
def test_default_behaviour_string_port(self): app.config['REDIS_PORT'] = str(app.config['REDIS_PORT']) obj = Redis(app) obj.ping()
def test_wrong_url(self): self.app.extensions.pop('redis') self.app.config['REDIS_URL'] = 'redis://wrong-host:8080/9' redis = Redis(self.app) self.assertRaises(ConnectionError, redis.ping)
from flask.ext.rq import RQ from flask.ext.mail import Mail from flask.ext.redis import Redis from flask.ext.lastuser import Lastuser from flask.ext.lastuser.sqlalchemy import UserManager from baseframe import baseframe, assets, Version import coaster.app from ._version import __version__ # First, make an app and config it app = Flask(__name__, instance_relative_config=True, static_folder=None) app.static_folder = 'static' mail = Mail() lastuser = Lastuser() redis_store = Redis() # Second, setup assets version = Version(__version__) assets['hasjob.js'][version] = 'js/app.js' assets['hasjob.css'][version] = 'css/app.css' # Third, after config, import the models and views from . import models, views # NOQA from .models import db # NOQA # Configure the app def init_for(env): coaster.app.init_app(app, env)
def redis(self): from flask.ext.redis import Redis return Redis()