def create_session(): redis_url = os.getenv('REDIS_URL') if redis_url: redis = Redis.from_url(redis_url) return RedisSessionInterface(redis.get_redis_pool) else: return InMemorySessionInterface()
async def before_server_start(app, loop): app.redis = await asyncio_redis.Pool.create(host='localhost', port=6379, poolsize=10) async def pool_getter(): return app.redis app.session_interface = RedisSessionInterface(pool_getter)
def createApp(): app = Sanic(name="main") config = settingsManager.getSetting("REDIS_SESSION") # setup sanic session Session(app, interface=RedisSessionInterface(redis.get_redis_pool_func(), **config)) [app.blueprint(bp) for bp in blueprints] app.config.update(settingsManager.settings) return app
def init_cache(sanic, loop): LOGGER.info("Starting aiocache") aiocache.settings.set_defaults( class_="aiocache.RedisCache", endpoint=REDIS_DICT.get('REDIS_ENDPOINT', None), port=REDIS_DICT.get('REDIS_PORT', None), db=REDIS_DICT.get('CACHE_DB', None), password=REDIS_DICT.get('PASSWORD', None), loop=loop, ) LOGGER.info("Starting redis pool") redis = RedisSession() # redis instance for app app.get_redis_pool = redis.get_redis_pool # pass the getter method for the connection pool into the session app.session_interface = RedisSessionInterface(app.get_redis_pool, expiry=86400)
def configure_session(app: Sanic): redis = app.config["REDIS"] session_interface = RedisSessionInterface(redis.get_redis_pool) @app.middleware('request') async def add_session_to_request(request): # before each request initialize a session # using the client's request await session_interface.open(request) @app.middleware('response') async def save_session(request, response): # after each request save the session, # pass the response to set client cookies await session_interface.save(request, response)
def init_cache(app, loop): LOGGER.info("Start aiocahe") app.config.from_object(CONFIG) REDIS_DICT = CONFIG.REDIS_DICT aiocache.settings.set_defaults( class_="aiocache.RedisCache", endpoint=REDIS_DICT.get('REDIS_ENDPOINT', 'localhost'), port=REDIS_DICT.get('REDIS_PORT', 6379), db=REDIS_DICT.get('CACHE_DB', 0), password=REDIS_DICT.get('REDIS_PASSWORD', None), loop=loop, ) LOGGER.info("Start reids pool") redis_session = RedisSession() app.get_redis_pool = redis_session.get_redis_pool app.session_interface = RedisSessionInterface(app.get_redis_pool, cookie_name="novel_sid", expiry=30 * 24 * 60 * 60)
def init_cache(app, loop): LOGGER.info("Starting aiocache") app.config.from_object(CONFIG) REDIS_DICT = CONFIG.REDIS_DICT aiocache.settings.set_defaults( class_="aiocache.RedisCache", endpoint=REDIS_DICT.get('REDIS_ENDPOINT', 'localhost'), port=REDIS_DICT.get('REDIS_PORT', 6379), db=REDIS_DICT.get('CACHE_DB', 0), password=REDIS_DICT.get('REDIS_PASSWORD', None), loop=loop, ) LOGGER.info("Starting redis pool") redis_session = RedisSession() # redis instance for app app.get_redis_pool = redis_session.get_redis_pool # pass the getter method for the connection pool into the session app.session_interface = RedisSessionInterface( app.get_redis_pool, cookie_name="owl_sid", expiry=30 * 24 * 60 * 60)
def init_session(self): """Initialize the session connection pool, using either in memory interface or redis.""" interface_type = settings.SESSION.pop('interface') if self.testing: # Set the session to in memory for unit tests. # TODO: Revisit this! interface_type = 'memory' if interface_type == 'memory': self._session_interface = InMemorySessionInterface() elif interface_type == 'redis': self._session_interface = RedisSessionInterface( self.get_session_pool()) else: raise Exception('Unexpected session type "%s".' % interface) @self.server.middleware('request') async def add_session_to_request(request): await self._session_interface.open(request) @self.server.middleware('response') async def save_session(request, response): await self._session_interface.save(request, response)
def init_session(self): """Initialize the session connection pool, using either in memory interface or redis.""" if 'SESSION' not in settings: return interface_type = settings.SESSION.pop('interface') if interface_type == 'memory': self._session_interface = InMemorySessionInterface() elif interface_type == 'redis': self._session_interface = RedisSessionInterface( self.get_session_pool) else: raise ServerError(f'Unexpected session type "{interface_type}".') @self.server.middleware('request') async def add_session_to_request(request): await self._session_interface.open(request) request['session']['csrf_token'] = 'test_token' if self.testing \ else generate_csrf_token() @self.server.middleware('response') async def save_session(request, response): await self._session_interface.save(request, response)
def init_cache(app, loop): LOGGER.info("Starting Aiocache : Asyncio Cache Manager For Redis") app.config.from_object(CONFIG) REDIS_DICT = CONFIG.REDIS_DICT # configuration: use aiocache to asyncio manager redis(the port) # reference https://github.com/argaen/aiocache aiocache.settings.set_defaults( class_="aiocache.RedisCache", endpoint=REDIS_DICT.get('REDIS_ENDPOINT', 'localhost'), port=REDIS_DICT.get('REDIS_PORT', 6379), db=REDIS_DICT.get('CACHE_DB', 0), password=REDIS_DICT.get('REDIS_PASSWORD', None), loop=loop, ) LOGGER.info("Starting Redis") # start redis redis_session = RedisSession() # redis instance for this app app.get_redis_pool = redis_session.get_redis_pool # pass the getter method for the connection pool into the session app.session_interface = RedisSessionInterface( app.get_redis_pool, cookie_name="quickReading_cookie", expiry=30 * 24 * 60 * 60)
config = configparser.ConfigParser() config.read('config.ini') app = Sanic() app.config.REQUEST_MAX_SIZE = 100 * 1024 * 1024 # 100MB app.static('/r', './resources') app.static('/static', './static') jinja = SanicJinja2(app) redis_connection = Redis() q = Queue(connection=redis_connection) dynamodb = boto3.resource('dynamodb') redis = Redis_pool() # pass the getter method for the connection pool into the session session_interface = RedisSessionInterface(redis.get_redis_pool) es = Elasticsearch([config['ELASTICSEARCH']['HOST']], use_ssl=True, ca_certs=certifi.where()) @app.middleware('request') async def add_session_to_request(request): # before each request initialize a session # using the client's request await session_interface.open(request) @app.middleware('response') async def save_session(request, response):
@app.listener('before_server_start') def init_cache(sanic, loop): aiocache.settings.set_defaults( class_="aiocache.RedisCache", endpoint=REDIS_DICT.get('REDIS_ENDPOINT', None), port=REDIS_DICT.get('REDIS_PORT', None), db=REDIS_DICT.get('CACHE_DB', None), loop=loop, ) redis = RedisSession() # pass the getter method for the connection pool into the session session_interface = RedisSessionInterface(redis.get_redis_pool, expiry=604800) @app.middleware('request') async def add_session_to_request(request): # before each request initialize a session # using the client's request if WEBSITE['IS_RUNNING']: await session_interface.open(request) else: return html("<h3>网站正在维护...</h3>") @app.middleware('response') async def save_session(request, response): # after each request save the session,
_pool = None async def get_redis_pool(self): if not self._pool: self._pool = await asyncio_redis.Pool.create(host='localhost', port=6379, poolsize=10) return self._pool redis = Redis() # pass the getter method for the connection pool into the session # https://pythonhosted.org/sanic_session/using_the_interfaces.html session = RedisSessionInterface(redis.get_redis_pool, cookie_name="session") @app.middleware('request') async def add_session_to_request(request): await session.open(request) @app.middleware('response') async def save_session(request, response): await session.save(request, response) from app.models import User
def init_session_interface(host, port, password, db_name): global redis, session_interface redis = Redis(host, port, password, db_name) session_interface = RedisSessionInterface(redis.get_redis_pool)
"""系统停止后关闭相关数据库连接""" await app.pg_pool.close() app.redis_pool.close() app.redis_cache_pool.close() ######################################## # 设置请求和返回的中间件 ######################################## async def redis_cache_pool_getter(): """辅助函数""" return app.redis_cache_pool session_interface = RedisSessionInterface(redis_cache_pool_getter) @app.middleware('request') async def add_session_to_request(request): """给请求添加session""" await session_interface.open(request) @app.middleware('response') async def add_log(request, response): """给请求的返回结果添加log""" logger.info('REQUEST,{},{},{},{},RESPONSE,{},{}'.format( request.path, request.method, request.args, request.body.decode(), response.status, response.body.decode()))
bp.redis = _redis_pool return _redis_pool @app.middleware('request') async def add_session_to_request(request): # before each request initialize a session # using the client's request await session.open(request) @app.middleware('response') async def save_session(request, response): # after each request save the session, # pass the response to set client cookies await session.save(request, response) if __name__ == "__main__": ''' sanic 启动时创建数据库连接池,服务正常结束时关闭连接池 ''' session = RedisSessionInterface(redis_getter=startup_redis_pool) app.run(host="0.0.0.0", port=settings.PORT, workers=settings.workers, debug=settings.DEBUG, after_start=start_connection, after_stop=close_connection)
pool across your application. """ _pool = None async def get_redis_pool(self): if not self._pool: self._pool = await asyncio_redis.Pool.create(host='localhost', port=6379, poolsize=10) return self._pool redis = Redis() Session(app, interface=RedisSessionInterface(redis.get_redis_pool)) @app.route("/") async def test(request): # interact with the session like a normal dict if not request['session'].get('foo'): request['session']['foo'] = 0 request['session']['foo'] += 1 response = text(request['session']['foo']) return response
# aiocache.settings.set_defaults( # class_="aiocache.RedisCache", # endpoint=REDIS_DICT.get('REDIS_ENDPOINT', 'localhost'), # port=REDIS_DICT.get('REDIS_PORT', 6379), # db=REDIS_DICT.get('CACHE_DB', 0), # password=REDIS_DICT.get('REDIS_PASSWORD', None), # loop=loop, # ) LOGGER.info("Starting redis pool") redis_session = RedisSession() # redis instance for app app.get_redis_pool = redis_session.get_redis_pool # pass the getter method for the connection pool into the session app.session_interface = RedisSessionInterface(app.get_redis_pool, cookie_name="owl_sid", expiry=30 * 24 * 60 * 60) @app.middleware('request') async def add_session_to_request(request): # before each request initialize a session # using the client's request host = request.headers.get('host', None) user_agent = request.headers.get('user-agent', None) if user_agent: user_ip = request.headers.get('X-Forwarded-For') LOGGER.info('user ip is: {}'.format(user_ip)) if user_ip in CONFIG.FORBIDDEN: return html("<h3>网站正在维护...</h3>") if CONFIG.VAL_HOST == 'true':