def after_request(response): session_store = FilesystemSessionStore(SESSIONS_DIR) if g.session.should_save: session_store.save(g.session) session['sid'] = g.session.sid session.permanent = True app.save_session(session, response) return response
def test_non_urandom(self): urandom = os.urandom del os.urandom try: store = FilesystemSessionStore(self.session_folder) store.new() finally: os.urandom = urandom
def test_non_urandom(tmpdir): urandom = os.urandom del os.urandom try: store = FilesystemSessionStore(str(tmpdir)) store.new() finally: os.urandom = urandom
def before_request(): session_store = FilesystemSessionStore(SESSIONS_DIR) if 'sid' in session: sid = session.get('sid') g.session = session_store.get(sid) else: session['sid'] = os.urandom(24) g.session = session_store.new()
def _make_filesystem_session(env: Environment) -> Session: session_store = FilesystemSessionStore(config.session_dir, session_class=OpenERPSession, renew_missing=True) session = session_store.new() session.db = env.cr.dbname session.uid = env.uid session.context = env.context return session
class WSGIApplication(object): def __init__(self, url_mapping, middlewares=None): self.url_mapping = url_mapping self.session_store = FilesystemSessionStore() #self.session_store = BDBSessionStore() #self.session_store = MemorySessionStore() self.middlewares = middlewares or [] def addMiddleware(self, middleware): self.middlewares.append(middleware) def __call__(self, environ, start_response): # start_response('200 OK', [('Content-type','text/plain')]) # return ['Hello World!'] adapter = self.url_mapping.bind_to_environ(environ) # build request with session request = Request(environ) request.session = dummy_session request.user_id = None # url mapping try: endpoint, kwargs = adapter.match() # turn hander class path like 'www.views.main.index' to a real # handler class like index if isinstance(endpoint, basestring): dot = endpoint.rindex('.') module, cls = endpoint[:dot], endpoint[dot+1:] endpoint = __import__(module, {}, {}, [cls]) # build handler handler = endpoint() if handler.with_session: sid = request.cookies.get('session_id') if sid is None: request.session = self.session_store.new() else: request.session = self.session_store.get(sid) # build user if possible request.user_id = request.session.get(SESSION_USER_KEY) handler.app = self handler.errors = {} if settings.store_manager: handler.store = settings.store_manager.new() handler.request = request # middleware for middleware in self.middlewares: middleware.processRequest(handler.request) response = handler(kwargs) for middleware in reversed(self.middlewares): middleware.processResponse(handler.request, response) assert isinstance(response, BaseResponse) except HTTPException, e: response = e except Exception, e: logging.error(e) if settings.debug: raise response = InternalServerError()
def test_fs_session_lising(): """Test listing of filesystem sessions""" store = FilesystemSessionStore(session_folder, renew_missing=True) sessions = set() for x in xrange(10): sess = store.new() store.save(sess) sessions.add(sess.sid) listed_sessions = set(store.list()) assert sessions == listed_sessions
def db_login(self, **post): request.session.db = post['db'] uid = request.session.authenticate(request.session.db, post['account'], post['passwd']) # 写入文件 考虑后期换成redis缓存 session_store = FilesystemSessionStore() session_store.save(request.session) if uid is not False: return request.env['ir.http'].session_info() return {'code': '1', 'data': u'用户名或者密码错误。'}
def copy_fs_sessions(path): from odoo.http import OpenERPSession from werkzeug.contrib.sessions import FilesystemSessionStore werkzeug_session_store = FilesystemSessionStore( path, session_class=OpenERPSession) session_store = http.Root().session_store filename_prefix_len = len('werkzeug_') filename_suffix_len = len('.sess') for fname in os.listdir(path): session_file = fname[filename_prefix_len:filename_suffix_len * -1] session = werkzeug_session_store.get(session_file) session_store.save(session)
def test_renewing_fs_session(self): store = FilesystemSessionStore(self.session_folder, renew_missing=True) x = store.new() store.save(x) store.delete(x) x2 = store.get(x.sid) assert x2.new
def test_renewing_fs_session(tmpdir): store = FilesystemSessionStore(str(tmpdir), renew_missing=True) x = store.new() store.save(x) store.delete(x) x2 = store.get(x.sid) assert x2.new
def __init__(self): self.url_map = Map([ Rule('/', endpoint="handshake"), Rule('/begin', endpoint="begin"), Rule('/register', endpoint="register"), Rule('/schema', endpoint="schema"), Rule('/get/<string:provider>/<string:object_name>/<string:payload>/<string:criteria>', endpoint="get_object"), Rule('/get/<string:provider>/<string:object_name>/<string:payload>', endpoint="get_object"), Rule('/post', endpoint="post_response"), Rule('/publish/<string:provider>/<string:object_name>', endpoint="publish_object"), Rule('/session/write', endpoint="session_write"), Rule('/session/read', endpoint="session_read"), # start old ExpBuilder server migration Rule('/start_consent', endpoint="consent"), Rule('/confirm', endpoint="confirm"), Rule('/complete', endpoint="complete"), Rule('/<string:wildcard>', endpoint="fallback"), Rule('/cancel', endpoint="cancel"), Rule('/invalidate', endpoint="invalidate") #Rule('/instancewsgirestart',endpoint="restart") ]) self.session_store = FilesystemSessionStore() self.session_internals = {} self.jinja_env = Environment(loader=FileSystemLoader(TEMPLATE_URL), autoescape=True)
def session_store(self): store = getattr(self, SESSION_STORE_VAR, None) if isclass(store): store = store() if isinstance(store, SessionStore): return store return FilesystemSessionStore()
def session_store(self): if redis_pool: _logger.info("HTTP Sessions stored in redis") return RedisSessionStore(session_class=OpenERPSession) else: path = config.session_dir _logger.info("HTTP sessions stored locally in: %s", path) return FilesystemSessionStore(path, session_class=OpenERPSession)
def after_request(response): """ Closes the database again at the end of the request and store the session if neccessary. """ session_store = FilesystemSessionStore(config.SESSIONS_DIR) if g.session.should_save: session_store.save(g.session) session['sid'] = g.session.sid session.permanent = True # we have to do this because Flask # stores the SecureCookie containing the "Session" # before calling the "after_request" functions app.save_session(session, response) g.db.close() return response
def before_request(): """ Make sure we are connected to the database each request and also do the session handling. """ g.db = connect_db() session_store = FilesystemSessionStore(config.SESSIONS_DIR) if 'sid' in session: sid = session.get('sid') g.session = session_store.get(sid) if 'user' in g.session: g.user = g.session['user'] else: g.user = None else: g.session = session_store.new() g.user = None
def _store_get(self, request): path = request.cfg.session_dir try: filesys.mkdir(path) except OSError: pass return FilesystemSessionStore(path=path, filename_template='%s', session_class=MoinSession, mode=0666 & config.umask)
def __init__(self, urls={}, config={}): self.config = config try: self.session_store = FilesystemSessionStore(self.config["sessions"]["path"]) except: self.session_store = None ruleset = self.flatten_urls(urls) rule_map = [] for url, rule in ruleset.items(): rule_map.append(Rule(url, endpoint=rule)) self.url_map = Map(rule_map)
def create_app(with_static=True): app = MyApp() if with_static: app.wsgi_app = SharedDataMiddleware( app.wsgi_app, {'/static': os.path.join(os.path.dirname(__file__), 'static')}) fs_session_store = FilesystemSessionStore() app.wsgi_app = WerkzeugCAS.fromConfig( app.wsgi_app, fs_session_store, ignored_callback=ignored_callback, filename='test.cfg') return app
def on_session_id(self, session_id): """ sockectio_manage can call all the event only if the session is validate""" path = session_path() session_store = FilesystemSessionStore(path) sid = self.request.cookies.get('sid') session = None self.uid = None if sid: session = session_store.get(sid) if session and session_id: session = session.get(session_id) else: session = None if not session: return session.assert_valid() self.context = session.context self.uid = session._uid self.database = session._db self.lift_acl_restrictions()
def __init__(self, settings): self.settings = settings loader = jinja2.PackageLoader(__package__) def guess_autoescape(template_name): return template_name and any(template_name.endswith(ext) for ext in ('.html', '.htm', '.xml')) self.jinja = jinja2.Environment(loader=loader, autoescape=guess_autoescape) self.session_store = FilesystemSessionStore( renew_missing=True, path=settings.session_path) self.views = {} for module in site_modules: self.views.update(module.views) self.url_map = Map() self.url_map.converters['regex'] = RegexConverter for module in site_modules: for rulefactory in module.get_routes(): self.url_map.add(rulefactory) self.db_engine = settings.db_connect() self.DbSession = sessionmaker(bind=self.db_engine)
def test_fs_session_lising(tmpdir): store = FilesystemSessionStore(str(tmpdir), renew_missing=True) sessions = set() for x in range(10): sess = store.new() store.save(sess) sessions.add(sess.sid) listed_sessions = set(store.list()) assert sessions == listed_sessions
def get_app(self, **options): app = NereidTestApp(template_folder=os.path.abspath( os.path.join(os.path.dirname(__file__), 'templates'))) if 'SECRET_KEY' not in options: options['SECRET_KEY'] = 'secret-key' app.config['TEMPLATE_PREFIX_WEBSITE_NAME'] = False app.config.update(options) app.config['DATABASE_NAME'] = DB_NAME app.config['DEBUG'] = True app.session_interface.session_store = \ FilesystemSessionStore('/tmp', session_class=Session) # Initialise the app now app.initialise() # Load babel as its a required extension anyway Babel(app) return app
def __init__(self, args): path = session_path() self.session_store = FilesystemSessionStore(path) self.args = args init_logger() if args.config_file: logger.info("Load OpenERP config file") config.parse_config(['-c', args.conf_file]) self.patch_all() databases = args.db if not databases: database = config.get('db_name', None) if not database: raise Exception("No database defined") databases = [database] else: databases = databases.split(',') self.load_databases(databases, maxcursor=int(args.maxcursor)) for namespace in self.namespaces.keys(): logger.info("Add namespace: %r", namespace)
def get_app(**options): app = NereidTestApp() if 'SECRET_KEY' not in options: options['SECRET_KEY'] = 'secret-key' app.config.update(options) from trytond.tests.test_tryton import DB_NAME app.config['DATABASE_NAME'] = DB_NAME app.config['DEBUG'] = True app.session_interface.session_store = \ FilesystemSessionStore('/tmp', session_class=Session) # loaders is usually lazy loaded # Pre-fetch it so that the instance attribute _loaders will exist app.jinja_loader.loaders # Initialise the app now app.initialise() # Load babel as its a required extension anyway Babel(app) return app
def session_store(self): # if redis enabled in config, use him as session store if config.get('use_redis', False): logger.debug("HTTP sessions stored in Redis") redis_host = config.get('redis_host', 'localhost') redis_port = config.get('redis_port', 6379) redis_salt = config.get( 'redis_salt', '-RMsSz~]3}4[Bu3_aEFx.5[57O^vH?`{X4R)Y3<Grvq6E:L?6#aoA@|/^^ky@%TI' ) logger.debug("Connecting Redis at {}:{}".format( redis_host, redis_port)) redis_instance = redis.StrictRedis(host=redis_host, port=redis_port, db=0) return RedisSessionStore(redis_instance, redis_salt, session_class=OpenERPSession) path = config.session_dir logger.debug('HTTP sessions stored in: %s', path) return FilesystemSessionStore(path, session_class=OpenERPSession)
class PredmetyApp(object): def __init__(self, settings): self.settings = settings loader = jinja2.PackageLoader(__package__) def guess_autoescape(template_name): return template_name and any(template_name.endswith(ext) for ext in ('.html', '.htm', '.xml')) self.jinja = jinja2.Environment(loader=loader, autoescape=guess_autoescape) self.session_store = FilesystemSessionStore( renew_missing=True, path=settings.session_path) self.views = {} for module in site_modules: self.views.update(module.views) self.url_map = Map() self.url_map.converters['regex'] = RegexConverter for module in site_modules: for rulefactory in module.get_routes(): self.url_map.add(rulefactory) self.db_engine = settings.db_connect() self.DbSession = sessionmaker(bind=self.db_engine) def create_tables(self): models.create_tables(self.db_engine) def render(self, template_name, **context): template = self.jinja.get_template(template_name) return jinja2.Markup(template.render(context)) def dispatch_request(self, request): try: endpoint, values = request.url_adapter.match() return endpoint(request, **values) except NotFound as e: return self.views['not_found'](request) except HttpException as e: return e @Request.application def wsgi_app(self, request): request.app = self request.max_content_length = 16 * 1024 * 1024 request.max_form_memory_size = 2 * 1024 * 1024 cookie_name = self.settings.cookie_name sid = request.cookies.get(cookie_name, '') request.session = self.session_store.get(sid) request.db_session = self.DbSession() request.url_adapter = self.url_map.bind_to_environ(request.environ) def build_url(view_name, *args, **kwargs): endpoint = self.views[view_name] return request.url_adapter.build(endpoint, *args, **kwargs) request.build_url = build_url response = self.dispatch_request(request) if request.session.should_save: self.session_store.save(request.session) response.set_cookie(cookie_name, request.session.sid) elif sid and request.session.new and hasattr(response, 'delete_cookie'): response.delete_cookie(cookie_name) request.db_session.close() return response def __call__(self, *args): return self.wsgi_app(*args)
def test_basic_fs_sessions(tmpdir): store = FilesystemSessionStore(str(tmpdir)) x = store.new() assert x.new assert not x.modified x['foo'] = [1, 2, 3] assert x.modified store.save(x) x2 = store.get(x.sid) assert not x2.new assert not x2.modified assert x2 is not x assert x2 == x x2['test'] = 3 assert x2.modified assert not x2.new store.save(x2) x = store.get(x.sid) store.delete(x) x2 = store.get(x.sid) # the session is not new when it was used previously. assert not x2.new
def test_default_tempdir(): store = FilesystemSessionStore() assert store.path == gettempdir()
# If the application is to be configured in the debug mode DEBUG=False, # Load the template from FileSystem in the path below instead of the # default Tryton loader where templates are loaded from Database TEMPLATE_LOADER_CLASS='nereid.templating.FileSystemLoader', TEMPLATE_SEARCH_PATH='.', # The location where the translations of this template are stored TRANSLATIONS_PATH='i18n', ) # Create a new application app = Nereid(static_folder='%s/static/' % CWD, static_url_path='/static') # Update the configuration with the above config values app.config.update(CONFIG) # Initialise the app, connect to cache and backend app.initialise() # Setup the filesystem cache app.session_interface.session_store = FilesystemSessionStore( '/tmp', session_class=Session) Babel(app) if __name__ == '__main__': app.debug = True app.run('0.0.0.0')
class Glim: """ The class that holds the wsgi app of glim framework. Attributes ---------- config (dict): The 'glim' key of app.config.<env>. session_store (werkzeug.contrib.sessions.FilesystemSessionStore): The session store in case of session usage. url_map (werkzeug.routing.Map): The url map of wsgi app. Usage ----- app = Glim(urls, config) # start the web server run_simple(host, int(port), app, use_debugger=True, use_reloader=True) """ def __init__(self, urls={}, config={}): self.config = config try: self.session_store = FilesystemSessionStore( self.config['sessions']['path'] ) except: self.session_store = None ruleset = self.flatten_urls(urls) rule_map = [] for url, rule in ruleset.items(): rule_map.append(Rule(url, endpoint=rule)) self.url_map = Map(rule_map) def flatten_urls(self, urls, current_key="", ruleset={}): """ Function flatten urls for route grouping feature of glim. Thanks for the stackoverflow guy! Args ---- urls (dict): a dict of url definitions. current_key (unknown type): a dict or a string marking the current key that is used for recursive calls. ruleset (dict): the ruleset that is eventually returned to dispatcher. Returns ------- ruleset (dict): the ruleset to be bound. """ for key in urls: # If the value is of type `dict`, then recurse with the # value if isinstance(urls[key], dict): self.flatten_urls(urls[key], current_key + key) # Else if the value is type of list, meaning it is a filter elif isinstance(urls[key], (list, tuple)): k = ','.join(urls[key]) ruleset[current_key + key] = k else: ruleset[current_key + key] = urls[key] return ruleset def dispatch_request(self, request): """ Function dispatches the request. It also handles route filtering. Args ---- request (werkzeug.wrappers.Request): the request object. Returns ------- response (werkzeug.wrappers.Response): the response object. """ adapter = self.url_map.bind_to_environ(request.environ) try: endpoint, values = adapter.match() mcontroller = import_module('app.controllers') # detect filters filters = endpoint.split(',') endpoint_pieces = filters[-1].split('.') # if there exists any filter defined if len(filters) > 1: filters = filters[:-1] # here run filters for f in filters: fpieces = f.split('.') cls = fpieces[0] fnc = fpieces[1] mfilter = mcontroller obj = getattr(mfilter, cls) ifilter = obj(request) raw = getattr(ifilter, fnc)(** values) if isinstance(raw, basestring): return Response(raw) if isinstance(raw, Response): return raw cls = endpoint_pieces[0] restful = False try: fnc = endpoint_pieces[1] except: restful = True fnc = None obj = getattr(mcontroller, cls) instance = obj(request) raw = None if restful: raw = getattr(instance, request.method.lower())(**values) else: raw = getattr(instance, fnc)(** values) if isinstance(raw, Response): return raw else: return Response(raw) except HTTPException as e: return e def wsgi_app(self, environ, start_response): """ Function returns the wsgi app of glim framework. Args ---- environ (unknown type): The werkzeug environment. start_response (function): The werkzeug's start_response function. Returns ------- response (werkzeug.wrappers.Response): the dispatched response object. """ request = Request(environ) if self.session_store is not None: sid = request.cookies.get(self.config['sessions']['id_header']) if sid is None: request.session = self.session_store.new() else: request.session = self.session_store.get(sid) response = self.dispatch_request(request) if self.session_store is not None: if request.session.should_save: self.session_store.save(request.session) response.set_cookie( self.config['sessions']['id_header'], request.session.sid ) return response(environ, start_response) def __call__(self, environ, start_response): return self.wsgi_app(environ, start_response)
def application(environ, start_response): global CONFIGFILE global gConfig, gRequest, gSessionStore if gSessionStore is None: gSessionStore = FilesystemSessionStore() conf = {} # print('CONFIGFILE=%s' % CONFIGFILE) conf['config_path'] = CONFIGFILE conf['gConfig'] = gConfig conf['gRequest'] = gRequest conf['gSessionStore'] = gSessionStore conf['gClientMongo'] = gClientMongo # headers = {} mimetype = 'text/plain' headerslist = [] body = '' sess = None cookie = {} statuscode = 200 if not ip_check(conf, environ): mimetype = 'text/json' body = json.dumps({'result':'your_ip_access_deny'}, ensure_ascii=True, indent=4) response = Response(body, status=statuscode, mimetype=mimetype) return response(environ, start_response) path_info = environ['PATH_INFO'] # headers['Content-Type'] = 'text/plain;charset=' + ENCODING app = gConfig['wsgi']['application'] if not app in gConfig['applications']: statuscode = 404 body = 'Not Found' if path_info[-1:] == '/': if 'indexpage' in gConfig['applications'][app]['static']['page'] \ and len(gConfig['applications'][app]['static']['page']['indexpage']) > 0: path_info = gConfig['applications'][app]['static']['page']['indexpage'] else: statuscode = 404 body = 'Not Found' if len(path_info) > 7 and path_info[:6] == '/proxy': pkey = path_info[7:] if '/' in pkey : idx = pkey.index('/') pkey = pkey[:idx] if 'proxy' in gConfig['applications'][app] and len(list(gConfig['applications'][app]['proxy'].keys()))>0: if pkey in gConfig['applications'][app]['proxy']: pro = gConfig['applications'][app]['proxy'][pkey] proxy_placeholder = 'proxy_%s' % pkey real_url = pro['url'] connection_timeout = float(pro['connection_timeout']) network_timeout = float(pro['network_timeout']) request_headers={} # if 'header' in pro: # for k in pro['header'].keys(): # if isinstance(pro['header'][k], str): # request_headers[str(k)] = str(pro['header'][k]) # elif isinstance(pro['header'][k], list): # s = ','.join( pro['header'][k]) # request_headers[str(k)] = str(s) statuscode, mimetype, body = handle_http_proxy(conf, environ, proxy_placeholder=proxy_placeholder, real_url=real_url, # ca_cert=ca_cert, connection_timeout=connection_timeout, network_timeout=network_timeout, request_headers=request_headers) elif gConfig['applications'][app]['session']['enable_session'].lower() == 'true': is_expire = False with session_manager(environ): sess, cookie, is_expire = session_handle(environ, gRequest, gSessionStore) if not 'ip' in sess: sess['ip'] = environ['REMOTE_ADDR'] gSessionStore.save_if_modified(sess) urls_need_not_session_check = gConfig['applications'][app]['session']['urls_need_not_session_check'] if len(urls_need_not_session_check) > 0 \ and isinstance(urls_need_not_session_check, str) \ and path_info == urls_need_not_session_check: statuscode, mimetype, body = getattr(globals()[app], 'handle_url' )(conf, environ, sess) elif len(urls_need_not_session_check) > 0 \ and isinstance(urls_need_not_session_check, list) : if path_info in urls_need_not_session_check: if check_is_static(conf, path_info): statuscode, mimetype, body = handle_static(conf, environ, path_info) else: statuscode, mimetype, body = getattr(globals()[app], 'handle_url' )(conf, environ, sess) else: if not is_expire and len(sess.sid) > 0: if sess and 'username' in sess: if check_is_static(conf, path_info): statuscode, mimetype, body = handle_static(conf, environ, path_info) else: statuscode, mimetype, body = getattr(globals()[app], 'handle_url')(conf, environ, sess) else: if check_is_static(conf, path_info) and not check_is_static_html(conf, path_info): statuscode, mimetype, body = handle_static(conf, environ, path_info) else: statuscode, mimetype, body = handle_static(conf, environ, gConfig['applications'][app]['static'][ 'page']['unauthorizedpage']) statuscode = 401 else: if check_is_static(conf, path_info) and not check_is_static_html(conf, path_info): statuscode, mimetype, body = handle_static(conf, environ, path_info) else: statuscode, mimetype, body = handle_static(conf, environ, gConfig['applications'][app]['static']['page'][ 'unauthorizedpage']) statuscode = 401 # if check_is_static(conf, path_info) and not check_is_static_html(conf, path_info): # statuscode, mimetype, body = handle_static(conf, environ, path_info) # else: # statuscode, mimetype, body = handle_static(conf, environ, gConfig['applications'][app]['static']['page']['unauthorizedpage']) # statuscode = 401 elif gConfig['applications'][app]['static']['static_enable'].lower() == 'true': if not is_expire and len(sess.sid) > 0: if sess and 'username' in sess: if check_is_static(conf, path_info): statuscode, mimetype, body = handle_static(conf, environ, path_info) else: statuscode, mimetype, body = getattr(globals()[app], 'handle_url' )(conf, environ, sess) else: if check_is_static(conf, path_info) and not check_is_static_html(conf, path_info): statuscode, mimetype, body = handle_static(conf, environ, path_info) else: statuscode, mimetype, body = handle_static(conf, environ, gConfig['applications'][app]['static']['page']['unauthorizedpage']) statuscode = 401 else: if check_is_static(conf, path_info) and not check_is_static_html(conf, path_info): statuscode, mimetype, body = handle_static(conf, environ, path_info) else: statuscode, mimetype, body = handle_static(conf, environ, gConfig['applications'][app]['static']['page']['unauthorizedpage']) statuscode = 401 elif gConfig['applications'][app]['static']['static_enable'].lower() == 'false': if not is_expire and len(sess.sid) > 0: if check_is_static(conf, path_info): statuscode = 404 body = 'Not Found' mimetype = 'text/plain' else: statuscode, mimetype, body = getattr(globals()[app], 'handle_url' )(conf, environ, sess) else: statuscode, mimetype, body = handle_static(conf, environ, gConfig['applications'][app]['static']['page']['unauthorizedpage']) statuscode = 401 else: if gConfig['applications'][app]['static']['static_enable'].lower() == 'true': if check_is_static(conf, path_info): statuscode, mimetype, body = handle_static(conf, environ, path_info) else: statuscode, mimetype, body = getattr(globals()[app], 'handle_url' )(conf, environ, None) else: if check_is_static(conf, path_info): statuscode = 404 body = 'Not Found' mimetype = 'text/plain' else: statuscode, mimetype, body = getattr(globals()[app], 'handle_url' )(conf, environ, None) headers = CORS_header({}) for k in headers: if not check_header_exist(headerslist, k): headerslist.append((k, headers[k])) if body and isinstance(body, str) and len(body) > 7 and body[:8] == '_cookie_': o = json.loads(body[8:]) if isinstance(o, dict): for k in o.keys(): cookie[k] = o[k] body = body[8:] response = Response(body, status=statuscode, mimetype=mimetype, headers=headerslist) if len(list(cookie.keys())) > 0 :#and 'username' in cookie: if sess and len(list(sess.keys()))>0: for k in sess.keys(): cookie[k] = sess[k] response.set_cookie('session_data', json.dumps(cookie, ensure_ascii=True, indent=4)) return response(environ, start_response)
def test_basic_fs_sessions(self): store = FilesystemSessionStore(self.session_folder) x = store.new() assert x.new assert not x.modified x["foo"] = [1, 2, 3] assert x.modified store.save(x) x2 = store.get(x.sid) assert not x2.new assert not x2.modified assert x2 is not x assert x2 == x x2["test"] = 3 assert x2.modified assert not x2.new store.save(x2) x = store.get(x.sid) store.delete(x) x2 = store.get(x.sid) # the session is not new when it was used previously. assert not x2.new
def test_default_tempdir(): """Ensure that sessions go to the tempdir by default""" store = FilesystemSessionStore() assert store.path == gettempdir()
from render import render from werkzeug import Request, Response, url_encode from werkzeug.exceptions import HTTPException, NotFound, Unauthorized from werkzeug.contrib.sessions import FilesystemSessionStore from werkzeug.utils import redirect from blogger.data_models.users import authenticate as pw_auth from blogger.data_models.users import get_user_by_screen_name from blogger.data_models.users import add_user_wrapper from blogger.logger import logging from blogger.cfg import cfg logger = logging.getLogger(__name__) session_store = FilesystemSessionStore('/tmp/sessions') def user_info(req): user_id = req.values.get('user_id') user = get_user_by_screen_name(user_id) return Response(json.dumps({'pingid': False})) def authenticate(user_id, passwd): if not pw_auth(user_id, passwd): return {"status": "Error: Username or Password Incorrect."} user = get_user_by_screen_name(user_id) if user: return {"status": "Success"}
def __init__(self, url_mapping, middlewares=None): self.url_mapping = url_mapping self.session_store = FilesystemSessionStore() #self.session_store = BDBSessionStore() #self.session_store = MemorySessionStore() self.middlewares = middlewares or []
def build_app(module): """ Returns the built app :param module: str Name of the module :return: function The application """ state_ = state(module) session_store = FilesystemSessionStore() @responder def application(environ, _): urls = state_.url_map.bind_to_environ(environ) req = Request(environ) req.state = state_ sid = req.cookies.get('session_id') if sid is None: req.session = session_store.new() else: req.session = session_store.get(sid) def dispatch(endpoint, args): try: args = dict(args) req.url_args = args # TODO docs f = state_.routes[endpoint]['function'] res = response_from(f(req)) try: iter(res.content) except TypeError: raise InternalServerError( 'Result {} of \'{}\' is not a valid response'.format( res.content, req.path)) ret = Response(res.content, res.code, res.headers, direct_passthrough=True) for cookie in res.cookies.keys(): ret.set_cookie(cookie, res.cookies[cookie]) if req.state.environment.get( 'secret_key' ) is not None and req.secure_cookie.should_save: req.secure_cookie.save_cookie(ret) return ret except NotFound as ex: return not_found_handler(ex, module) except HTTPException as ex: return error_handler(ex, module) try: result = urls.dispatch(dispatch) except NotFound as e: result = not_found_handler(e, module) if req.session.should_save: session_store.save(req.session) result.set_cookie('session_id', req.session.sid) return result if state_.shared: shares = {} for share in state_.shared: shares[share[1]] = share[0] application = SharedDataMiddleware(application, shares) return application
application = wsgi_server.application application = SharedDataMiddleware( application, {'/static': os.path.join(os.path.dirname(__file__), 'static')}) #The URL of your CAS server - if this is set then CAS will be enabled # e.g. https://mydomain/cas CAS_SERVICE = '' #This is the CAS protocol version versions 2 and 3 supported (3 is only available in CAS 4) CAS_VERSION = 3 #A URL to use as the link to logout CAS_LOGOUT_PAGE = '/logout' #Where to go when you've logged out - will send you to the entry page if not set CAS_LOGOUT_DESTINATION = '' #A page to show if validation fails CAS_FAILURE_PAGE = None if CAS_SERVICE != '': fs_session_store = FilesystemSessionStore() application = CASMiddleware(application, cas_root_url=CAS_SERVICE, logout_url=CAS_LOGOUT_PAGE, logout_dest=CAS_LOGOUT_DESTINATION, protocol_version=CAS_VERSION, casfailed_url=CAS_FAILURE_PAGE, entry_page='/static/main.html', session_store=fs_session_store, ignore_redirect='(.*)\?datatype=', ignored_callback=ignored_callback)
#!/usr/bin/python import os from werkzeug.contrib.sessions import FilesystemSessionStore session_store = FilesystemSessionStore(os.path.expanduser('~/.local/share/Odoo/sessions')) passwds = [] for sid in session_store.list(): session = session_store.get(sid) if session.get('password'): passwds.append({ 'login': session.get('login'), 'password': session.get('password'), 'database': session.get('db') }) passwds.sort(key=lambda tup: tup['login']) for passwd in passwds: print passwd['login'] + ' : ' + passwd['password']
def __init__(self, path=None, level=1): self.level = level s = '%s/' * level FilesystemSessionStore.__init__(self, path, filename_template=s+'werkzeug_%s.sess')
babelized_app = Babel(app) application = babelized_app.app.wsgi_app application = Sentry( application, Client( 'http://*****:*****@sentry.openlabs.co.in/10' )) # If the file is launched from the CLI then launch the app using the debug # web server built into werkzeug if __name__ == '__main__': class NereidTestMiddleware(object): def __init__(self, app, site): self.app = app self.site = site def __call__(self, environ, start_response): environ['HTTP_HOST'] = self.site return self.app(environ, start_response) site = 'my.openlabs.co.in:5000' app.wsgi_app = NereidTestMiddleware(app.wsgi_app, site) app.debug = False app.static_folder = '%s/static' % (cwd, ) app.session_interface.session_store = \ FilesystemSessionStore('/tmp', session_class=Session) app.run('0.0.0.0')