#!/usr/bin/env python import aiocache import os import sys from sanic import Sanic from sanic.response import html, redirect from sanic_session import RedisSessionInterface sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from soulbook.views import admin_bp, api_bp, except_bp, md_bp, novels_bp, operate_bp from soulbook.database.redis import RedisSession from soulbook.config import LOGGER, CONFIG app = Sanic(__name__) app.blueprint(md_bp) app.blueprint(novels_bp) app.blueprint(operate_bp) app.blueprint(except_bp) app.blueprint(admin_bp) app.blueprint(api_bp) @app.listener('before_server_start') 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) @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("