def test_class_custom_init(self): app = self.create_app(REDIS_CLASS=CustomInitStrictRedis, REDIS_URL='redis://127.0.0.1:6379/1') redis = Redis(app) redis.ping() self.assertEqual(redis.connection.foo, "bar") self.assertEqual( redis.connection.connection_pool.connection_kwargs['db'], '1')
def test_class_custom_init(self): app = self.create_app(REDIS_CLASS=CustomInitStrictRedis, REDIS_URL='redis://127.0.0.1:6379/1') redis = Redis(app) redis.ping() self.assertEqual(redis.connection.foo, "bar") self.assertEqual( redis.connection.connection_pool.connection_kwargs['db'], '1' )
class FlaskRedisTestCase(unittest.TestCase): def setUp(self): """ Create a sample Flask Application """ self.redis = Redis() self.app = flask.Flask('test-flask-redis') def test_init_app(self): """ Test the initation of our Redis extension """ self.redis.init_app(self.app) assert self.redis.get('potato') is None
def test_custom_prefix(app): """Test that config prefixes enable distinct connections.""" app.config['REDIS_URL'] = 'redis://localhost:6379/1' redis_a = Redis(app) app.config['REDIS_URL'] = 'redis://localhost:6379/2' redis_b = Redis(app) assert redis_a.connection_pool.connection_kwargs['db'] == 1 assert redis_b.connection_pool.connection_kwargs['db'] == 2
class FlaskRedisTestCase(unittest.TestCase): def setUp(self): """ Create a sample Flask Application """ self.redis = Redis() self.app = flask.Flask(__name__) def test_init_app(self): """ Test the initation of our Redis extension """ self.redis.init_app(self.app) assert self.redis.get("potato") is None def test_custom_prefix(self): """ Test the use of custom config prefixes """ self.db1_redis = Redis(config_prefix="DB1") self.app.config["DB1_URL"] = "redis://localhost" self.app.config["DB1_DATABASE"] = 0 self.db1_redis.init_app(self.app) self.db2_redis = Redis(config_prefix="DB2") self.app.config["DB2_URL"] = "redis://localhost" self.app.config["DB2_DATABASE"] = 1 self.db2_redis.init_app(self.app) assert self.db1_redis.get("potato") is None assert self.db2_redis.get("potato") is None
def test_custom_connection_class_using_string(app): """Test that Redis can be instructed to use a different Redis client using a class reference""" app.config['REDIS_CONNECTION_CLASS'] = 'redis.StrictRedis' redis = Redis() assert redis.client is None redis.init_app(app) assert redis.client is not None assert isinstance(redis.client, rd.StrictRedis)
def test_custom_prefix(self): """ Test the use of custom config prefixes """ self.db1_redis = Redis(config_prefix="DB1") self.app.config["DB1_URL"] = "redis://localhost" self.app.config["DB1_DATABASE"] = 0 self.db1_redis.init_app(self.app) self.db2_redis = Redis(config_prefix="DB2") self.app.config["DB2_URL"] = "redis://localhost" self.app.config["DB2_DATABASE"] = 1 self.db2_redis.init_app(self.app) assert self.db1_redis.get("potato") is None assert self.db2_redis.get("potato") is None
def create_app(**options): r"""Factory function to create test application. :param \*\*options: Override default settings from given options. :type \*\*options: dict """ # Initialize application and configure it from settings and given options app = Flask('testapp') app.config.from_object(settings) app.config.update(options) # Put necessary filter & globals to Jinja environment app.jinja_env.filters['format'] = format app.jinja_env.globals['constants'] = constants app.jinja_env.globals.update({ 'constants': constants, 'float': float, 'fromtimestamp': datetime.datetime.fromtimestamp, 'iteritems': iteritems, 'len': len, }) # Register Redis databases Redis(app, 'REDIS_LINKS') Redis(app, 'REDIS_CONTENT') # Setup all available routes views = LazyViews(app, 'views') views.add('/', 'index', methods=('GET', 'POST')) views.add('/comments/<thread_uid>', 'comment', methods=('POST', )) views.add('/comments/<thread_uid>', 'comments') views.add('/quit', 'quit') views.add('/threads', 'start_thread', methods=('POST', )) views.add('/threads', 'threads') views.add('/threads/<thread_uid>/delete', 'delete_thread', methods=('GET', 'POST')) views.add_error(400, 'error') views.add_error(403, 'error') views.add_error(404, 'error') views.add_error(Exception, 'error') # Put username from session to globals before each request @app.before_request def global_username(): key = constants.USERNAME_KEY.format(app.config['KEY_PREFIX']) g.username = session.get(key) or '' return app
def test_init_app_behaviour(self): redis = Redis() self.assertRaises(AttributeError, getattr, redis, 'ping') app = self.create_app(REDIS_HOST=TEST_REDIS_HOST, REDIS_PORT=TEST_REDIS_PORT, REDIS_DB=TEST_REDIS_DB) redis.init_app(app) # Extensions initialized by init_app are not bound to any app # So you need an application context to access it self.assertRaises(RuntimeError, redis.ping) with get_context(app): redis.ping()
def test_constructor(app): """Test that a constructor with app instance will initialize the connection. """ redis = Redis(app) assert redis.client is not None assert hasattr(redis.client, 'connection_pool')
def test_custom_connection_class_using_class(app): """Test that Redis can be instructed to use a different Redis client using a class reference""" class FakeProvider(object): @classmethod def from_url(cls, *args, **kwargs): return cls() app.config['REDIS_CONNECTION_CLASS'] = FakeProvider redis = Redis() assert redis.client is None redis.init_app(app) assert redis.client is not None assert isinstance(redis.client, FakeProvider)
def test_init_app(app): """Test that a constructor without app instance will not initialize the connection. After Redis.init_app(app) is called, the connection will be initialized. """ redis = Redis() assert redis.client is None redis.init_app(app) assert redis.client is not None assert hasattr(redis.client, 'connection_pool') if hasattr(app, 'extensions'): assert 'redis' in app.extensions assert app.extensions['redis'] == redis
def test_config_prefix(self): redis_url = TEST_REDIS_URL.replace('/0', '/1') app = self.create_app(REDIS_URL=TEST_REDIS_URL, REDIS1_URL=redis_url) redis = Redis(app) redis.ping() redis1 = Redis(app, 'REDIS1') redis1.ping()
def test_constructor_app(mocker): """Test that the constructor passes the app to Redis.init_app""" mocker.patch.object(Redis, 'init_app', autospec=True) app_stub = mocker.stub(name='app_stub') Redis(app_stub) Redis.init_app.assert_called_once_with(mocker.ANY, app_stub)
def create_app(object_name): # config app.config.from_object(object_name) # app.config.update( # DEBUG=True, # SECRET_KEY='secret_xxx' # ) # Redis Configs redis_instance = Redis() app.register_blueprint(login_app) app.register_blueprint(dashboard_app) app.register_blueprint(task_app) redis_instance.init_app(app) login_manager.init_app(app) return app
def setUp(self): self.redis = redis = Redis() self.app_a = self.create_app(REDIS_URL='redis://127.0.0.1:6379/0', REDIS_DECODE_RESPONSES=True) self.app_b = self.create_app(REDIS_URL='redis://127.0.0.1:6379/1', REDIS_DECODE_RESPONSES=True) redis.init_app(self.app_a) redis.init_app(self.app_b)
def test_default_class_redis_3(self): app = self.create_app(REDIS_URL=TEST_REDIS_URL) redis = Redis(app) real_redis = app.extensions['redis']['REDIS'] self.assertIsInstance( real_redis, redis_py.Redis if flask_redis.IS_REDIS3 else StrictRedis)
def test_socket_path_in_host(self, host=None): host = host or '/var/lib/redis/run.sock' app = self.create_app(REDIS_HOST=host) redis = Redis(app) self.assertFalse(hasattr(redis, 'connection_pool')) real_redis = app.extensions['redis']['REDIS'] self.assertEqual(real_redis.connection_pool.connection_class, UnixDomainSocketConnection)
def generate_context(config): """Create the Flask app context and initializes any extensions such as Celery, Redis, SQLAlchemy, etc. :param dict config: Partial Flask config dict from generate_config(). :return: 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
class RedisClient(): def __init__(self, channel=None): self.channel = channel or 'coati' self.redis_instance = Redis(current_app) self.pubsub = self.redis_instance.connection.pubsub() self.pubsub.subscribe(self.channel) def get(self, key): return self.redis_instance.get(key) def store(self, message_type, author_id): data = json.dumps({'type': message_type, 'user_id': author_id}) self.redis_instance.connection.publish(self.channel, data)
def test_custom_prefix(self): """ Test the use of custom config prefixes """ self.db1_redis = Redis(config_prefix='DB1') self.app.config['DB1_URL'] = "redis://localhost:6379" self.app.config['DB1_DATABASE'] = 0 self.db1_redis.init_app(self.app) self.db2_redis = Redis(config_prefix='DB2') self.app.config['DB2_URL'] = "redis://localhost:6379" self.app.config['DB2_DATABASE'] = 1 self.db2_redis.init_app(self.app) self.db3_redis = Redis(config_prefix='DB3') self.app.config['DB3_URL'] = "redis://localhost:6379" self.db3_redis.init_app(self.app) self.db4_redis = Redis(config_prefix='DB4') self.app.config['DB4_URL'] = "redis://localhost:6379/5" self.db4_redis.init_app(self.app) assert self.db1_redis.get('potato') is None assert self.db2_redis.get('potato') is None assert self.db3_redis.get('potato') is None assert self.db4_redis.get('potato') is None
def test_init_app_behaviour(self): redis = Redis() self.assertRaises(AttributeError, getattr, redis, 'ping') app = self.create_app(REDIS_HOST=TEST_REDIS_HOST, REDIS_PORT=TEST_REDIS_PORT, REDIS_DB=TEST_REDIS_DB) redis.init_app(app) redis.ping()
def create_app(): global app, redisdb, sqldb app = Flask(__name__) def generate_config_from_env(): return { "sql": { "dbms": os.environ['SHORTIFY_SQL_DBMS'], "host": os.environ['SHORTIFY_SQL_HOST'], "port": os.environ['SHORTIFY_SQL_PORT'], "username": os.environ['SHORTIFY_SQL_USERNAME'], "password": os.environ['SHORTIFY_SQL_PASSWORD'], "database": os.environ['SHORTIFY_SQL_DATABASE'] }, "redis": { "host": os.environ['SHORTIFY_REDIS_HOST'], "port": os.environ['SHORTIFY_REDIS_PORT'], "db": os.environ['SHORTIFY_REDIS_DB'], } } config = generate_config_from_env() def configure_appinstance(app, config): sql = config['sql'] redis = config['redis'] app.config['SQLALCHEMY_DATABASE_URI'] = r'%s://%s:%s@%s:%s/%s' % ( sql['dbms'], sql['username'], sql['password'], sql['host'], sql['port'], sql['database']) app.config['REDIS_HOST'] = redis['host'] app.config['REDIS_PORT'] = redis['port'] app.config['REDIS_DB'] = redis['db'] configure_appinstance(app, config) sqldb = SQLAlchemy(app) redisdb = Redis(app) from app import models from app import views return app
def setUp(self): """ Create a sample Flask Application """ self.redis = Redis() self.app = flask.Flask(__name__)
app = Flask(__name__) app.config['MONGODB_SETTINGS'] = { 'db': 'flask-test', 'host': 'ds027741.mongolab.com', 'port': 27741, 'username': '******', 'password': '******' } app.config[ 'REDIS_URL'] = "redis://:[email protected]:17784/0" app.config['SECRET_KEY'] = 'flask is cool' db = MongoEngine(app) redis_store = Redis(app) bcrypt = Bcrypt(app) api = Api(app) class User(db.Document): # email = db.EmailField(unique=True) username = db.StringField(unique=True) password_hash = db.StringField() def hash_password(self, password): self.password_hash = bcrypt.generate_password_hash(password) def verify_password(self, password): return bcrypt.check_password_hash(self.password_hash, password)
def test_url(self): app = self.create_app(REDIS_URL='redis://127.0.0.1:6379/0') redis = Redis(app) redis.ping()
from flask_restful import reqparse, abort, Api, Resource import os from flask_restful import Api import pickle import json import yaml import gzip from datetime import timedelta app = Flask(__name__) api = Api(app) app.config['REDIS_URL'] = 'redis://:redis123@localhost:6379/0' r = Redis(app) # # r.set("msg:hello", "Hello Redis!!!") # # # step 5: Retrieve the hello message from Redis # msg = r.get("msg:hello") #uri = r.set("uri","https://devapi.appkeelaa.com/api/processpayments") # dict_obj = {"name":"bhanu","last":"sheeram"} # r.set("uri", str(dict_obj)) # # @app.route('/api/postcall') class Getcreateredis(Resource):
class FlaskRedisTestCase(unittest.TestCase): def setUp(self): """ Create a sample Flask Application """ self.redis = Redis() self.app = flask.Flask(__name__) def test_init_app(self): """ Test the initation of our Redis extension """ self.redis.init_app(self.app) assert self.redis.get('potato') is None def test_custom_prefix(self): """ Test the use of custom config prefixes """ self.db1_redis = Redis(config_prefix='DB1') self.app.config['DB1_URL'] = "redis://localhost:6379" self.app.config['DB1_DATABASE'] = 0 self.db1_redis.init_app(self.app) self.db2_redis = Redis(config_prefix='DB2') self.app.config['DB2_URL'] = "redis://localhost:6379" self.app.config['DB2_DATABASE'] = 1 self.db2_redis.init_app(self.app) self.db3_redis = Redis(config_prefix='DB3') self.app.config['DB3_URL'] = "redis://localhost:6379" self.db3_redis.init_app(self.app) self.db4_redis = Redis(config_prefix='DB4') self.app.config['DB4_URL'] = "redis://localhost:6379/5" self.db4_redis.init_app(self.app) assert self.db1_redis.get('potato') is None assert self.db2_redis.get('potato') is None assert self.db3_redis.get('potato') is None assert self.db4_redis.get('potato') is None
def setUp(self): """ Create a sample Flask Application """ self.redis = Redis() self.app = flask.Flask('test-flask-redis')
import json import stripe import flask from flask import g from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager, current_user from flask.ext.cdn import CDN from flask_redis import Redis from flask_limiter import Limiter from flask_limiter.util import get_ipaddr import settings from helpers import ssl_redirect DB = SQLAlchemy() redis_store = Redis() stripe.api_key = settings.STRIPE_SECRET_KEY cdn = CDN() import routes from users.models import User def configure_login(app): login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'register' @login_manager.user_loader def load_user(id): return User.query.get(int(id))
def test_class_from_string(self): app = self.create_app(REDIS_CLASS='redis.Redis', REDIS_URL=TEST_REDIS_URL) redis = Redis(app) redis.ping()
def test_class(self): app = self.create_app(REDIS_CLASS=InheritFromStrictRedis, REDIS_URL=TEST_REDIS_URL) redis = Redis(app) redis.ping()
from flask import Flask, render_template from flask_redis import Redis import json, pickle import time app = Flask(__name__) app.config['REDIS_HOST'] = '35.170.1.59' app.config['REDIS_PORT'] = 6379 redis = Redis(app) @app.route('/', methods=['GET']) def homepage(): return render_template('home.html', lines=enumerate(fill_table(), 1)) def fill_table(): lines = [] for line in redis.zrange('tweets', 0, 9): # line = line.strip('[]') one_row = list(line.split(",")) tag = one_row[0] pos = one_row[1] neg = one_row[2] neu = one_row[3] row = [tag[3:-1], pos, neg, neu[:-1]] # one_row = one_row[0].strip('[\'') # one_row = one_row[3].strip(']') # lines.append(one_row) lines.append(row) return lines
def test_non_string_port(self): app = self.create_app(REDIS_HOST=TEST_REDIS_HOST, REDIS_PORT=str(TEST_REDIS_PORT), REDIS_DB=str(TEST_REDIS_DB)) redis = Redis(app) redis.ping()
def make_auctions_app(global_conf, redis_url='redis://localhost:7777/0', external_couch_url='http://localhost:5000/auction', internal_couch_url='http://localhost:9000/', proxy_internal_couch_url='http://localhost:9000/', auctions_db='auctions', hash_secret_key='', timezone='Europe/Kiev', preferred_url_scheme='http', debug=False, auto_build=False, event_source_connection_limit=1000): """ [app:main] use = egg:openprocurement.auction#auctions_server redis_url = redis://:passwod@localhost:1111/0 external_couch_url = http://localhost:1111/auction internal_couch_url = http://localhost:9011/ auctions_db = auction timezone = Europe/Kiev """ auctions_server.proxy_connection_pool = ConnectionPool(factory=Connection, max_size=20, backend="gevent") auctions_server.proxy_mappings = Memoizer({}) auctions_server.event_sources_pool = deque([]) auctions_server.config['PREFERRED_URL_SCHEME'] = preferred_url_scheme auctions_server.config['REDIS_URL'] = redis_url auctions_server.config['event_source_connection_limit'] = int( event_source_connection_limit) auctions_server.config['EXT_COUCH_DB'] = urljoin(external_couch_url, auctions_db) auctions_server.add_url_rule('/' + auctions_db + '/<path:path>', 'couch_server_proxy', couch_server_proxy, methods=['GET']) auctions_server.add_url_rule('/' + auctions_db + '/', 'couch_server_proxy', couch_server_proxy, methods=['GET'], defaults={'path': ''}) auctions_server.add_url_rule('/' + auctions_db + '_secured/<path:path>', 'auth_couch_server_proxy', auth_couch_server_proxy, methods=['GET']) auctions_server.add_url_rule('/' + auctions_db + '_secured/', 'auth_couch_server_proxy', auth_couch_server_proxy, methods=['GET'], defaults={'path': ''}) auctions_server.config['INT_COUCH_URL'] = internal_couch_url auctions_server.config['PROXY_COUCH_URL'] = proxy_internal_couch_url auctions_server.config['COUCH_DB'] = auctions_db auctions_server.config['TIMEZONE'] = tz(timezone) auctions_server.redis = Redis(auctions_server) auctions_server.couch_server = Server( auctions_server.config.get('INT_COUCH_URL'), session=Session(retry_delays=range(10))) if auctions_server.config['COUCH_DB'] not in auctions_server.couch_server: auctions_server.couch_server.create(auctions_server.config['COUCH_DB']) auctions_server.db = auctions_server.couch_server[ auctions_server.config['COUCH_DB']] auctions_server.config['HASH_SECRET_KEY'] = hash_secret_key sync_design(auctions_server.db) auctions_server.config['ASSETS_DEBUG'] = True if debug else False assets.auto_build = True if auto_build else False return auctions_server
def test_default_behaviour(self): app = self.create_app(REDIS_HOST=TEST_REDIS_HOST, REDIS_PORT=TEST_REDIS_PORT, REDIS_DB=TEST_REDIS_DB) redis = Redis(app) redis.ping()
# App Config app = Flask(__name__) socketio = SocketIO(app, async_mode=async_mode) app.config.from_object(app_config[FLASK_CONFIG]) app.config.from_pyfile('config.py') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True app.config['SQLALCHEMY_ECHO'] = False app.config['SQLALCHEMY_POOL_SIZE'] = 100 app.config['CDN_DOMAIN'] = 'd30bzjua38r0w8.cloudfront.net' app.config['CDN_HTTPS'] = True app.config['CDN_DEBUG'] = True # DB Config db.init_app(app) redis = Redis() redis.init_app(app) # Migration Config migration = Migrate(app, db) # Session Config app.secret_key = THE_SECRET_KEY app.config['SESSION_TYPE'] = 'filesystem' Session(app) # CDN Config cdn.init_app(app) # flask-compress config compress.init_app(app)
# !/usr/local/python/bin/python # -*- coding: utf-8 -*- # (C) Wu Dong, 2020 # All rights reserved # @Author: 'Wu Dong <*****@*****.**>' # @Time: '2020-06-28 17:00' from flask import Flask from flask_redis import Redis, K_RDS_DEFAULT_BIND redis = Redis() app = Flask(__name__) app.config[K_RDS_DEFAULT_BIND] = "default" app.config["REDIS_BINDS"] = { "default": { "REDIS_PREFIX": "DEFAULT:", "REDIS_URL": "redis://:[email protected]:16379/12", }, "DB12": { "REDIS_PREFIX": "EG12:", "REDIS_URL": "redis://:[email protected]:16379/12", }, "DB13": { "REDIS_PREFIX": "EG13:", "REDIS_URL": "redis://:[email protected]:16379/13", } } redis.init_app(app) if __name__ == "__main__":
from flask_redis import Redis from flask_sqlalchemy import SQLAlchemy # Create database connection object db = SQLAlchemy() # Create Redis connection object redis = Redis()
# monkey patching is necessary because this application uses a background # thread if async_mode == 'eventlet': import eventlet eventlet.monkey_patch() elif async_mode == 'gevent': from gevent import monkey monkey.patch_all() app = Flask(__name__) login_manager = LoginManager() db = SQLAlchemy() socketio = SocketIO() oauth = OAuth(app) redis = Redis() moment = Moment() with app.app_context(): config_name = os.getenv('FLASK_CONFIG') or 'development' app.config.from_object(config[config_name]) config[config_name].init_app(app) db.app = app db.init_app(app) login_manager.init_app(app) login_manager.session_protection = 'strong' login_manager.login_view = 'login' login_manager.login_message = u'请先登陆系统,若遗忘密码,请联系管理员'