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()
def get_app(name) -> Sanic: config: Config = get_config("discord_web_panel/config.json") app: Sanic = Sanic(name) app.static('/static', './static') app.blueprint(oauth_blueprint) app.session_interface = InMemorySessionInterface() app.config.OAUTH_REDIRECT_URI = "http://127.0.0.1:5000/oauth" app.config.OAUTH_PROVIDER = 'sanic_oauth.providers.DiscordClient' app.config.OAUTH_SCOPE = "identify guilds" app.config.OAUTH_CLIENT_ID = config.app_id app.config.OAUTH_CLIENT_SECRET = config.app_secret async def init_aiohttp_session(sanic_app: Sanic, _loop) -> None: sanic_app.async_session = aiohttp.ClientSession() async def close_aiohttp_session(sanic_app: Sanic, _loop) -> None: await sanic_app.async_session.close() async def add_session_to_request(request: Request) -> None: await request.app.session_interface.open(request) async def save_session(request: Request, response: HTTPResponse) -> None: await request.app.session_interface.save(request, response) app.listener("before_server_start")(init_aiohttp_session) app.listener("after_server_stop")(close_aiohttp_session) app.middleware("request")(add_session_to_request) app.middleware("response")(save_session) return app
def setUp(self): app = Sanic(__name__) app.config["SECRET_KEY"] = "my secret" app.config["CORS_AUTOMATIC_OPTIONS"] = True CORS(app) Session(app, interface=InMemorySessionInterface(cookie_name="test_session")) digest_auth = HTTPDigestAuth(qop="auth") @digest_auth.get_password def get_digest_password_2(username): if username == "susan": return "hello" elif username == "john": return "bye" else: return None @app.route("/") def index(request): return text("index") @app.route("/digest") @digest_auth.login_required def digest_auth_route(request): return text(f"digest_auth:{digest_auth.username(request)}") self.app = app self.digest_auth = digest_auth self.client = app.test_client
def setUp(self): app = Sanic(__name__) app.config["SECRET_KEY"] = "my secret" Session(app, interface=InMemorySessionInterface(cookie_name="test_session")) digest_auth_ha1_pw = HTTPDigestAuth(use_ha1_pw=True) @digest_auth_ha1_pw.get_password def get_digest_password(username): if username == "susan": return get_ha1(username, "hello", digest_auth_ha1_pw.realm) elif username == "john": return get_ha1(username, "bye", digest_auth_ha1_pw.realm) else: return None @app.route("/") def index(request): return "index" @app.route("/digest_ha1_pw") @digest_auth_ha1_pw.login_required def digest_auth_ha1_pw_route(request): return text( f"digest_auth_ha1_pw:{digest_auth_ha1_pw.username(request)}") self.app = app self.client = app.test_client
def init_app(cls, app, context, *args, interface=None, **kwargs): log = context.log if interface is None: interface = InMemorySessionInterface() context.interface = interface real_session = RealSanicSession() real_session.interface = interface # Emulate old sanic-session method of attaching to app if not hasattr(app, 'extensions'): app.extensions = {} # session_name defaults to 'session' app.extensions[interface.session_name] = real_session log(logging.DEBUG, "Created Session named: {} on app." .format(interface.session_name))
def createApp(cls, appName): app = Sanic(appName) #判断session if config('SESSION_ENABLE') == 'true': # 启用session Session(app, interface=InMemorySessionInterface( expiry=int(config('SESSION_EXPIRE')))) #加载路由 for uri, action in router.routers.items(): app.add_route(action.as_view(), uri) #设置静态目录 app.static('/static', './static') return app
def create_app(config=Config): app.update_config(config) app.ctx.env = Environment(loader=PackageLoader('app', 'templates'), enable_async=True) Session(app, interface=InMemorySessionInterface()) app.static('/static', './app/static') app.static('/favicon.ico', './app/static/files/favicon.ico?', name='favicon') app.blueprint(root) app.blueprint(opho) app.blueprint(listeners) return app
def create_app(): app = Sanic(__name__) # ------------------------------------------------------------------------ # CONFIGURATION # ------------------------------------------------------------------------ init(dsn=config('SENTRY_DSN'), integrations=[SanicIntegration()]) app.blueprint(initdb_blueprint) app.blueprint(oauth_blueprint) app.blueprint(auth_blueprint) app.blueprint(form_blueprint) app.blueprint(api_retrieve_blueprint) app.blueprint(api_create_blueprint) app.blueprint(api_update_blueprint) app.blueprint(api_delete_blueprint) app.blueprint(api_switch_blueprint) app.blueprint(api_redirect_blueprint) app.blueprint(view_blueprint) app.blueprint(extra_blueprint) app.static('/links/', './static/') app.config.WTF_CSRF_SECRET_KEY = config('WTF_CSRF_SECRET_KEY') # ------------------------------------------------------------------------ # AUTHENTICATION # ------------------------------------------------------------------------ app.session_interface = InMemorySessionInterface() app.config.OAUTH_PROVIDER = config('OAUTH_PROVIDER') app.config.OAUTH_SCOPE = config('OAUTH_SCOPE') app.config.OAUTH_CLIENT_ID = config('OAUTH_CLIENT_ID') app.config.OAUTH_CLIENT_SECRET = config('OAUTH_CLIENT_SECRET') if config('PRODUCTION', default=False, cast=bool): domain = config('DOMAIN_NAME') else: domain = config('LOCAL_HOST') app.config.OAUTH_REDIRECT_URI = domain + config('OAUTH_REDIRECT_ENDPOINT') app.register_middleware(add_session_to_request, 'request') app.register_middleware(save_session, 'response') return app
def create_app(config=Config): app = Sanic(__name__) app.config.from_object(config) app.env = Environment(loader=PackageLoader('app', 'templates'), enable_async=True) Session(app, interface=InMemorySessionInterface()) app.static('/static', './app/static') print(root.host) app.blueprint(root) app.blueprint(opho) app.blueprint(listeners) for handler, (rule, router) in app.router.routes_names.items(): print(rule) return app
async def start(self): """Start sanic web server.""" self.app = Sanic('sanic_server') # GZip support # Compress(self.app) # self.app.config['COMPRESS_MIMETYPES'] = {'text/html', # 'application/json'} # self.app.config['COMPRESS_LEVEL'] = 4 # self.app.config['COMPRESS_MIN_SIZE'] = 300 # Session support self.session_interface = InMemorySessionInterface() self.app.response_middleware.appendleft(self.save_session) self.app.request_middleware.append(self.add_session_to_request) self.add_routes() return await self.app.create_server(loop=self.loop, host='0.0.0.0', port=self.port, debug=False)
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 setUp(self): app = Sanic(__name__) app.config["SECRET_KEY"] = "my secret" self.nonce = None self.opaque = None Session(app, interface=InMemorySessionInterface(cookie_name="test_session")) digest_auth_ha1_pw = HTTPDigestAuth(use_ha1_pw=True, qop=None) digest_auth_ha1_pw._generate_random = MagicMock(side_effect=[ "9549bf6d4fd6206e2945e8501481ddd5", "47c67cc7bedf6bc754f044f77f32b99e" ]) @digest_auth_ha1_pw.get_password def get_digest_password(username): if username == "susan": return get_ha1(username, "hello", digest_auth_ha1_pw.realm) elif username == "john": return get_ha1(username, "bye", digest_auth_ha1_pw.realm) else: return None @app.route("/") def index(request): return "index" @app.route("/digest_ha1_pw") @digest_auth_ha1_pw.login_required def digest_auth_ha1_pw_route(request): return text( f"digest_auth_ha1_pw:{digest_auth_ha1_pw.username(request)}") self.app = app self.client = app.test_client
from sanic import Sanic from sanic_session import InMemorySessionInterface from sanic_jinja2 import SanicJinja2 import logging logger = logging.getLogger(__name__) formatter = "[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s - %(message)s" logging.basicConfig(level=logging.INFO, format=formatter) app = Sanic(__name__) jinja = SanicJinja2(app) session = InMemorySessionInterface(cookie_name=app.name, prefix=app.name) @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)
def generator(size=36, chars=string.ascii_uppercase + string.digits + string.ascii_lowercase): return ''.join(random.choice(chars) for _ in range(size)) def clear_sting(string): reg = re.compile('[^a-zA-Z ]') return ((reg.sub('', string).strip()).lower()).replace(' ', '-') app = Sanic() app.static('/resources', './resources') si = InMemorySessionInterface() @app.middleware('request') async def add_session_to_request(request): await si.open(request) @app.middleware('response') async def save_session(request, response): await si.save(request, response) @app.route("/") async def test(request): response = file(join(dirname(__file__), 'websocket.html'))
def init_session(app): session.init_app(app, interface=InMemorySessionInterface(expiry=2592000))
from sanic import Sanic from my_blueprint import bp from sanic.response import json from api import api import database from sanic_cors import CORS, cross_origin from sanic_session import Session, InMemorySessionInterface from http import cookies app = Sanic(__name__) CORS(app) app.blueprint(api) app.blueprint(bp) Session(app, interface=InMemorySessionInterface(domain='localhost')) @app.route("/") async def test(request): return json({"hello": 'hello'}) for handler, (rule, router) in app.router.routes_names.items(): print(rule) @app.route("/login") async def login(request): request['session']['foo'] = 1 return json({"hello": request['session']['foo']}) @app.route("/is_guest")
def __init__(self, app, interface=InMemorySessionInterface()): self.session_interface = interface self.app = app app.middleware('request')(self.on_request_start) app.middleware('response')(self.on_response_complete)
from motor.motor_asyncio import AsyncIOMotorClient from jinja2 import Environment, PackageLoader from sanic import Sanic, response from sanic.exceptions import SanicException from sanic_session import Session, InMemorySessionInterface import aiohttp import dhooks from core import config import core app = Sanic(__name__) app.cfg = config Session(app, interface=InMemorySessionInterface(domain=config.DOMAIN)) app.blueprint(core.api) app.blueprint(core.rd) app.static('/static', './static') app.static('/favicon.ico', './static/favicon.ico') jinja_env = Environment(loader=PackageLoader('app', 'templates')) def render_template(name, *args, **kwargs): template = jinja_env.get_template(name + '.html') request = core.get_stack_variable('request') kwargs['request'] = request
from sanic_session.session import SessionDict, lock_keeper, LockKeeper from sanic_session import Session, InMemorySessionInterface class MockInterface: store = {} async def _get_value(self, sid): return self.store.get(sid) async def _set_value(self, sid, data): self.store[sid] = data mock_interface = MockInterface() inmemory_session_interface = InMemorySessionInterface() @pytest.mark.asyncio @pytest.mark.parametrize('interface', [mock_interface, inmemory_session_interface]) async def test_session_dict_locked_by_sid(interface): SID = 'an_sid' session_dict = SessionDict(sid=SID, interface=interface) async with session_dict as sess: assert lock_keeper.acquired_locks[SID].locked() is True sess['foo'] = 'bar' assert sess['foo'] == 'bar' assert ujson.loads(await interface._get_value(SID))['foo'] == 'bar'
import aiohttp from collections import defaultdict from sanic import Sanic from sanic.request import Request from sanic.response import text, HTTPResponse, html from sanic_session import InMemorySessionInterface from sanic_oauth.blueprint import oauth_blueprint, login_required app = Sanic('example-oauth') app.blueprint(oauth_blueprint) app.session_interface = InMemorySessionInterface() app.config.OAUTH_REDIRECT_URI = 'http://127.0.0.1:8888/oauth' app.config.OAUTH_SCOPE = 'email' app.config.OAUTH_PROVIDERS = defaultdict(dict) DISCORD_PROVIDER = app.config.OAUTH_PROVIDERS['discord'] DISCORD_PROVIDER['PROVIDER_CLASS'] = 'sanic_oauth.providers.DiscordClient' DISCORD_PROVIDER['SCOPE'] = "identify email" DISCORD_PROVIDER['CLIENT_ID'] = 'insert-you-credentials' DISCORD_PROVIDER['CLIENT_SECRET'] = 'insert-you-credentials' GITLAB_PROVIDER = app.config.OAUTH_PROVIDERS['gitlab'] GITLAB_PROVIDER['PROVIDER_CLASS'] = 'sanic_oauth.providers.GitlabClient' GITLAB_PROVIDER['SCOPE'] = "read_user" GITLAB_PROVIDER['CLIENT_ID'] = 'insert-you-credentials' GITLAB_PROVIDER['CLIENT_SECRET'] = 'insert-you-credentials' app.config.OAUTH_PROVIDERS['default'] = DISCORD_PROVIDER @app.listener('before_server_start') async def init_aiohttp_session(sanic_app, _loop) -> None: sanic_app.async_session = aiohttp.ClientSession()
from sanic_session import InMemorySessionInterface from sanic_useragent import SanicUserAgent from sanic_auth import Auth, User # local imports from app import app from app.forms import WelcomeForm, DatabaseForm, LoginForm from app.models import sql_master # initialize imports Compress(app) SanicUserAgent.init_app(app, default_locale='en_US') jinja = SanicJinja2(app) config = app.config jrender = jinja.render session = InMemorySessionInterface(expiry=600) config['AUTH_LOGIN_ENDPOINT'] = 'login' @app.listener('before_server_start') async def setup_cfg(app, loop): config['SECRET_KEY'] = urandom(24) config['DEMO_CONTENT'] = True if path.isfile('*.db'): config['SETUP_DB'] = False config['SETUP_BLOG'] = False else: config['SETUP_DB'] = True config['SETUP_BLOG'] = True try: cfg = config.from_pyfile('config.py')
if "URL_PREFIX" in os.environ: print( "Using the legacy config var `URL_PREFIX`, rename it to `LOG_URL_PREFIX`" ) prefix = os.environ["URL_PREFIX"] else: prefix = os.getenv("LOG_URL_PREFIX", "/logs") if prefix == "NONE": prefix = "" app = Sanic(__name__) app.using_oauth = False Session(app, interface=InMemorySessionInterface()) app.static("/static", "./static") jinja_env = Environment(loader=PackageLoader("app", "templates")) def render_template(name, *args, **kwargs): template = jinja_env.get_template(name + ".html") request = get_stack_variable("request") if request: kwargs["request"] = request kwargs["session"] = request["session"] kwargs["user"] = request["session"].get("user") kwargs.update(globals()) return response.html(template.render(*args, **kwargs))
user = None if request['session'].get('logged_in'): user = get_user(request) kwargs['request'] = request kwargs['session'] = request['session'] kwargs['user'] = user kwargs.update(globals()) return html(template.render(*args, **kwargs)) #################################### # Server backed session middleware # #################################### session_interface = InMemorySessionInterface(domain=None if dev_mode else domain) @app.middleware('request') async def add_session_to_request(request): await session_interface.open(request) @app.middleware('response') async def save_session(request, response): await session_interface.save(request, response) async def validate_token(request): exists = await app.db.admin.find_one({'token': request.token}) return exists is not None ############################# # Authentication decorators #
# from mqtt_server_V0.mqtt_server import * from produce_server.produce_server import prod_bp, produce_websocket_loop from purchase_server.purchase_server import purchase_bp from operation_server.operation_server import operation_bp from websocket_server.websocket_server import * from conf import * app = Sanic() app.blueprint(wx_bp) #wx端接口 # app.blueprint(mqtt_bp)#mqtt服务 app.blueprint(prod_bp) #生产场景 app.blueprint(purchase_bp) #购买场景 app.blueprint(operation_bp) app.blueprint(websocket_bp) session = Session(app, interface=InMemorySessionInterface(expiry=3600, sessioncookie=True)) #sessioncookie=True后端的session会自动过期,会话保持1小时 # ========================== 中间件 ========================== # # 用于验证用户的登录状态 @app.middleware('request') async def handle_request(request): #print(session.interface.session_store) if request.url.split( '/')[3] == 'operation' and not request['session'].get('user_id'): print('会话超时') return response.json({'status': 'timeout'}) # 会话过时, 重定向到登录界面 @app.middleware('response') #用于处理跨域的问题,只要是响应,都会经过此中间件,加上用于跨域的头
# -*- coding: utf-8 -*- from sanic import Sanic app = Sanic() from sanic_auth import Auth from sanic_cors import CORS, cross_origin from sanic_session import Session, InMemorySessionInterface session = Session(app, interface=InMemorySessionInterface(expiry=14400)) app.config.AUTH_LOGIN_ENDPOINT = 'login' app.config['CORS_AUTOMATIC_OPTIONS'] = True auth = Auth(app) CORS(app, supports_credentials=True) from modules import authorized from modules import views from modules import login from modules import exceptions from modules import front_setting from modules import setting from modules import flow from modules import analysis