desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Copy stored session data into this session instance.'
def load(self):
data = self._load() if ((data is None) or (data[1] < datetime.datetime.now())): if self.debug: cherrypy.log('Expired session, flushing data', 'TOOLS.SESSIONS') self._data = {} else: self._data = data[0] self.loaded = True cls = self.__class__ if (self...
'Delete stored session data.'
def delete(self):
self._delete()
'Remove the specified key and return the corresponding value. If key is not found, default is returned if given, otherwise KeyError is raised.'
def pop(self, key, default=missing):
if (not self.loaded): self.load() if (default is missing): return self._data.pop(key) else: return self._data.pop(key, default)
'D.has_key(k) -> True if D has a key k, else False.'
def has_key(self, key):
if (not self.loaded): self.load() return (key in self._data)
'D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.'
def get(self, key, default=None):
if (not self.loaded): self.load() return self._data.get(key, default)
'D.update(E) -> None. Update D from E: for k in E: D[k] = E[k].'
def update(self, d):
if (not self.loaded): self.load() self._data.update(d)
'D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D.'
def setdefault(self, key, default=None):
if (not self.loaded): self.load() return self._data.setdefault(key, default)
'D.clear() -> None. Remove all items from D.'
def clear(self):
if (not self.loaded): self.load() self._data.clear()
'D.keys() -> list of D\'s keys.'
def keys(self):
if (not self.loaded): self.load() return self._data.keys()
'D.items() -> list of D\'s (key, value) pairs, as 2-tuples.'
def items(self):
if (not self.loaded): self.load() return self._data.items()
'D.values() -> list of D\'s values.'
def values(self):
if (not self.loaded): self.load() return self._data.values()
'Clean up expired sessions.'
def clean_up(self):
now = datetime.datetime.now() for (id, (data, expiration_time)) in self.cache.items(): if (expiration_time <= now): try: del self.cache[id] except KeyError: pass try: del self.locks[id] except KeyError: ...
'Acquire an exclusive lock on the currently-loaded session data.'
def acquire_lock(self):
self.locked = True self.locks.setdefault(self.id, threading.RLock()).acquire()
'Release the lock on the currently-loaded session data.'
def release_lock(self):
self.locks[self.id].release() self.locked = False
'Return the number of active sessions.'
def __len__(self):
return len(self.cache)
'Set up the storage system for file-based sessions. This should only be called once per process; this will be done automatically when using sessions.init (as the built-in Tool does).'
def setup(cls, **kwargs):
kwargs['storage_path'] = os.path.abspath(kwargs['storage_path']) for (k, v) in kwargs.items(): setattr(cls, k, v) lockfiles = [fname for fname in os.listdir(cls.storage_path) if (fname.startswith(cls.SESSION_PREFIX) and fname.endswith(cls.LOCK_SUFFIX))] if lockfiles: plural = ('', 's')[(...
'Acquire an exclusive lock on the currently-loaded session data.'
def acquire_lock(self, path=None):
if (path is None): path = self._get_file_path() path += self.LOCK_SUFFIX while True: try: lockfd = os.open(path, ((os.O_CREAT | os.O_WRONLY) | os.O_EXCL)) except OSError: time.sleep(0.1) else: os.close(lockfd) break self.loc...
'Release the lock on the currently-loaded session data.'
def release_lock(self, path=None):
if (path is None): path = self._get_file_path() os.unlink((path + self.LOCK_SUFFIX)) self.locked = False
'Clean up expired sessions.'
def clean_up(self):
now = datetime.datetime.now() for fname in os.listdir(self.storage_path): if (fname.startswith(self.SESSION_PREFIX) and (not fname.endswith(self.LOCK_SUFFIX))): path = os.path.join(self.storage_path, fname) self.acquire_lock(path) try: contents = self....
'Return the number of active sessions.'
def __len__(self):
return len([fname for fname in os.listdir(self.storage_path) if (fname.startswith(self.SESSION_PREFIX) and (not fname.endswith(self.LOCK_SUFFIX)))])
'Set up the storage system for Postgres-based sessions. This should only be called once per process; this will be done automatically when using sessions.init (as the built-in Tool does).'
def setup(cls, **kwargs):
for (k, v) in kwargs.items(): setattr(cls, k, v) self.db = self.get_db()
'Acquire an exclusive lock on the currently-loaded session data.'
def acquire_lock(self):
self.locked = True self.cursor.execute('select id from session where id=%s for update', (self.id,))
'Release the lock on the currently-loaded session data.'
def release_lock(self):
self.cursor.close() self.locked = False
'Clean up expired sessions.'
def clean_up(self):
self.cursor.execute('delete from session where expiration_time < %s', (datetime.datetime.now(),))
'Set up the storage system for memcached-based sessions. This should only be called once per process; this will be done automatically when using sessions.init (as the built-in Tool does).'
def setup(cls, **kwargs):
for (k, v) in kwargs.items(): setattr(cls, k, v) import memcache cls.cache = memcache.Client(cls.servers)
'Acquire an exclusive lock on the currently-loaded session data.'
def acquire_lock(self):
self.locked = True self.locks.setdefault(self.id, threading.RLock()).acquire()
'Release the lock on the currently-loaded session data.'
def release_lock(self):
self.locks[self.id].release() self.locked = False
'Return the number of active sessions.'
def __len__(self):
raise NotImplementedError
'Dump profile data into self.path.'
def run(self, func, *args, **params):
global _count c = _count = (_count + 1) path = os.path.join(self.path, ('cp_%04d.prof' % c)) prof = profile.Profile() result = prof.runcall(func, *args, **params) prof.dump_stats(path) return result
'statfiles() -> list of available profiles.'
def statfiles(self):
return [f for f in os.listdir(self.path) if (f.startswith('cp_') and f.endswith('.prof'))]
'stats(index) -> output of print_stats() for the given profile.'
def stats(self, filename, sortby='cumulative'):
sio = StringIO() if (sys.version_info >= (2, 5)): s = pstats.Stats(os.path.join(self.path, filename), stream=sio) s.strip_dirs() s.sort_stats(sortby) s.print_stats() else: s = pstats.Stats(os.path.join(self.path, filename)) s.strip_dirs() s.sort_stats(...
'Make a WSGI middleware app which wraps \'nextapp\' with profiling. nextapp: the WSGI application to wrap, usually an instance of cherrypy.Application. path: where to dump the profiling output. aggregate: if True, profile data for all HTTP requests will go in a single file. If False (the default), each HTTP request wil...
def __init__(self, nextapp, path=None, aggregate=False):
if ((profile is None) or (pstats is None)): msg = "Your installation of Python does not have a profile module. If you're on Debian, try `sudo apt-get install python-profiler`. See http://www.cherrypy.org/wiki/ProfilingOnDebian for details." ...
'Provide a temporary user name for anonymous users.'
def anonymous(self):
pass
'Login. May raise redirect, or return True if request handled.'
def do_login(self, username, password, from_page='..', **kwargs):
response = cherrypy.serving.response error_msg = self.check_username_and_password(username, password) if error_msg: body = self.login_screen(from_page, username, error_msg) response.body = body if ('Content-Length' in response.headers): del response.headers['Content-Lengt...
'Logout. May raise redirect, or return True if request handled.'
def do_logout(self, from_page='..', **kwargs):
sess = cherrypy.session username = sess.get(self.session_key) sess[self.session_key] = None if username: cherrypy.serving.request.login = None self.on_logout(username) raise cherrypy.HTTPRedirect(from_page)
'Assert username. May raise redirect, or return True if request handled.'
def do_check(self):
sess = cherrypy.session request = cherrypy.serving.request response = cherrypy.serving.response username = sess.get(self.session_key) if (not username): sess[self.session_key] = username = self.anonymous() if self.debug: cherrypy.log('No session[username], trying ...
'Transform \'token;key=val\' to (\'token\', {\'key\': \'val\'}).'
def parse(elementstr):
atoms = [x.strip() for x in elementstr.split(';') if x.strip()] if (not atoms): initial_value = '' else: initial_value = atoms.pop(0).strip() params = {} for atom in atoms: atom = [x.strip() for x in atom.split('=', 1) if x.strip()] key = atom.pop(0) if atom: ...
'Construct an instance from a string of the form \'token;key=val\'.'
def from_str(cls, elementstr):
(ival, params) = cls.parse(elementstr) return cls(ival, params)
'Return a sorted list of HeaderElements for the given header.'
def elements(self, key):
key = str(key).title() value = self.get(key) return header_elements(key, value)
'Return a sorted list of HeaderElement.value for the given header.'
def values(self, key):
return [e.value for e in self.elements(key)]
'Transform self into a list of (name, value) tuples.'
def output(self):
header_list = [] for (k, v) in self.items(): if isinstance(k, unicode): k = k.encode('ISO-8859-1') if (not isinstance(v, basestring)): v = str(v) if isinstance(v, unicode): v = self.encode(v) header_list.append((k, v)) return header_list
'Return the given header value, encoded for HTTP output.'
def encode(self, v):
try: v = v.encode('ISO-8859-1') except UnicodeEncodeError: if (self.protocol == (1, 1)): v = b2a_base64(v.encode('utf-8')) v = (('=?utf-8?b?' + v.strip('\n')) + '?=') else: raise return v
'Iterate through config and pass it to each namespace handler. \'config\' should be a flat dict, where keys use dots to separate namespaces, and values are arbitrary. The first name in each config key is used to look up the corresponding namespace handler. For example, a config entry of {\'tools.gzip.on\': v} will call...
def __call__(self, config):
ns_confs = {} for k in config: if ('.' in k): (ns, name) = k.split('.', 1) bucket = ns_confs.setdefault(ns, {}) bucket[name] = config[k] for (ns, handler) in self.items(): exit = getattr(handler, '__exit__', None) if exit: callable = ha...
'Reset self to default values.'
def reset(self):
self.clear() dict.update(self, self.defaults)
'Update self from a dict, file or filename.'
def update(self, config):
if isinstance(config, basestring): config = Parser().dict_from_file(config) elif hasattr(config, 'read'): config = Parser().dict_from_file(config) else: config = config.copy() self._apply(config)
'Update self from a dict.'
def _apply(self, config):
which_env = config.get('environment') if which_env: env = self.environments[which_env] for k in env: if (k not in config): config[k] = env[k] dict.update(self, config) self.namespaces(config)
'Convert an INI file to a dictionary'
def as_dict(self, raw=False, vars=None):
result = {} for section in self.sections(): if (section not in result): result[section] = {} for option in self.options(section): value = self.get(section, option, raw, vars) try: value = unrepr(value) except Exception as x: ...
'Set handler and config for the current request.'
def __call__(self, path_info):
request = cherrypy.serving.request (func, vpath) = self.find_handler(path_info) if func: vpath = [x.replace('%2F', '/') for x in vpath] request.handler = LateParamPageHandler(func, *vpath) else: request.handler = cherrypy.NotFound()
'Return the appropriate page handler, plus any virtual path. This will return two objects. The first will be a callable, which can be used to generate page output. Any parameters from the query string or request body will be sent to that callable as keyword arguments. The callable is found by traversing the application...
def find_handler(self, path):
request = cherrypy.serving.request app = request.app root = app.root dispatch_name = self.dispatch_method_name curpath = '' nodeconf = {} if hasattr(root, '_cp_config'): nodeconf.update(root._cp_config) if ('/' in app.config): nodeconf.update(app.config['/']) object_t...
'Set handler and config for the current request.'
def __call__(self, path_info):
request = cherrypy.serving.request (resource, vpath) = self.find_handler(path_info) if resource: avail = [m for m in dir(resource) if m.isupper()] if (('GET' in avail) and ('HEAD' not in avail)): avail.append('HEAD') avail.sort() cherrypy.serving.response.headers[...
'Routes dispatcher Set full_result to True if you wish the controller and the action to be passed on to the page handler parameters. By default they won\'t be.'
def __init__(self, full_result=False):
import routes self.full_result = full_result self.controllers = {} self.mapper = routes.Mapper() self.mapper.controller_scan = self.controllers.keys
'Set handler and config for the current request.'
def __call__(self, path_info):
func = self.find_handler(path_info) if func: cherrypy.serving.request.handler = LateParamPageHandler(func) else: cherrypy.serving.request.handler = cherrypy.NotFound()
'Find the right page handler, and set request.config.'
def find_handler(self, path_info):
import routes request = cherrypy.serving.request config = routes.request_config() config.mapper = self.mapper if hasattr(request, 'wsgi_environ'): config.environ = request.wsgi_environ config.host = request.headers.get('Host', None) config.protocol = request.scheme config.redirec...
'Return a (httpserver, bind_addr) pair based on self attributes.'
def httpserver_from_self(self, httpserver=None):
if (httpserver is None): httpserver = self.instance if (httpserver is None): from cherrypy import _cpwsgi_server httpserver = _cpwsgi_server.CPWSGIServer(self) if isinstance(httpserver, basestring): httpserver = attributes(httpserver)(self) return (httpserver, self.bind_a...
'Start the HTTP server.'
def start(self):
if (not self.httpserver): (self.httpserver, self.bind_addr) = self.httpserver_from_self() ServerAdapter.start(self)
'Return the base (scheme://host[:port] or sock file) for this server.'
def base(self):
if self.socket_file: return self.socket_file host = self.socket_host if (host in ('0.0.0.0', '::')): import socket host = socket.gethostname() port = self.socket_port if self.ssl_certificate: scheme = 'https' if (port != 443): host += (':%s' % port...
'Run self.callback(**self.kwargs).'
def __call__(self):
return self.callback(**self.kwargs)
'Append a new Hook made from the supplied arguments.'
def attach(self, point, callback, failsafe=None, priority=None, **kwargs):
self[point].append(Hook(callback, failsafe, priority, **kwargs))
'Execute all registered Hooks (callbacks) for the given point.'
def run(self, point):
exc = None hooks = self[point] hooks.sort() for hook in hooks: if ((exc is None) or hook.failsafe): try: hook() except (KeyboardInterrupt, SystemExit): raise except (cherrypy.HTTPError, cherrypy.HTTPRedirect, cherrypy.InternalRe...
'Populate a new Request object. local_host should be an httputil.Host object with the server info. remote_host should be an httputil.Host object with the client info. scheme should be a string, either "http" or "https".'
def __init__(self, local_host, remote_host, scheme='http', server_protocol='HTTP/1.1'):
self.local = local_host self.remote = remote_host self.scheme = scheme self.server_protocol = server_protocol self.closed = False self.error_page = self.error_page.copy() self.namespaces = self.namespaces.copy() self.stage = None
'Run cleanup code. (Core)'
def close(self):
if (not self.closed): self.closed = True self.stage = 'on_end_request' self.hooks.run('on_end_request') self.stage = 'close'
'Process the Request. (Core) method, path, query_string, and req_protocol should be pulled directly from the Request-Line (e.g. "GET /path?key=val HTTP/1.0"). path should be %XX-unquoted, but query_string should not be. They both MUST be byte strings, not unicode strings. headers should be a list of (name, value) tuple...
def run(self, method, path, query_string, req_protocol, headers, rfile):
response = cherrypy.serving.response self.stage = 'run' try: self.error_response = cherrypy.HTTPError(500).set_response self.method = method path = (path or '/') self.query_string = (query_string or '') self.params = {} rp = (int(req_protocol[5]), int(req_prot...
'Generate a response for the resource at self.path_info. (Core)'
def respond(self, path_info):
response = cherrypy.serving.response try: try: if (self.app is None): raise cherrypy.NotFound() self.stage = 'process_headers' self.process_headers() self.hooks = self.__class__.hooks.copy() self.toolmaps = {} self.s...
'Parse the query string into Python structures. (Core)'
def process_query_string(self):
try: p = httputil.parse_query_string(self.query_string, encoding=self.query_string_encoding) except UnicodeDecodeError: raise cherrypy.HTTPError(404, ('The given query string could not be processed. Query strings for this resource must be encoded w...
'Parse HTTP header data into Python structures. (Core)'
def process_headers(self):
headers = self.headers for (name, value) in self.header_list: name = name.title() value = value.strip() if ('=?' in value): dict.__setitem__(headers, name, httputil.decode_TEXT(value)) else: dict.__setitem__(headers, name, value) if (name == 'Cooki...
'Call a dispatcher (which sets self.handler and .config). (Core)'
def get_resource(self, path):
dispatch = self.app.find_config(path, 'request.dispatch', self.dispatch) dispatch(path)
'Handle the last unanticipated exception. (Core)'
def handle_error(self):
try: self.hooks.run('before_error_response') if self.error_response: self.error_response() self.hooks.run('after_error_response') cherrypy.serving.response.finalize() except cherrypy.HTTPRedirect as inst: inst.set_response() cherrypy.serving.response.f...
'Collapse self.body to a single string; replace it and return it.'
def collapse_body(self):
if isinstance(self.body, basestring): return self.body newbody = ''.join([chunk for chunk in self.body]) self.body = newbody return newbody
'Transform headers (and cookies) into self.header_list. (Core)'
def finalize(self):
try: (code, reason, _) = httputil.valid_status(self.status) except ValueError as x: raise cherrypy.HTTPError(500, x.args[0]) headers = self.headers self.output_status = ((str(code) + ' ') + headers.encode(reason)) if self.stream: if (dict.get(headers, 'Content-Length') is ...
'If now > self.time + self.timeout, set self.timed_out. This purposefully sets a flag, rather than raising an error, so that a monitor thread can interrupt the Response thread.'
def check_timeout(self):
if (time.time() > (self.time + self.timeout)): self.timed_out = True
'Wrap and return the given socket.'
def bind(self, sock):
return sock
'Wrap and return the given socket, plus WSGI environ entries.'
def wrap(self, sock):
try: s = ssl.wrap_socket(sock, do_handshake_on_connect=True, server_side=True, certfile=self.certificate, keyfile=self.private_key, ssl_version=ssl.PROTOCOL_SSLv23) except ssl.SSLError as e: if (e.errno == ssl.SSL_ERROR_EOF): return (None, {}) elif (e.errno == ssl.SSL_ERROR_S...
'Create WSGI environ entries to be merged into each request.'
def get_environ(self, sock):
cipher = sock.cipher() ssl_environ = {'wsgi.url_scheme': 'https', 'HTTPS': 'on', 'SSL_PROTOCOL': cipher[1], 'SSL_CIPHER': cipher[0]} return ssl_environ
'Parse the next HTTP request start-line and message-headers.'
def parse_request(self):
self.rfile = SizeCheckWrapper(self.conn.rfile, self.server.max_request_header_size) try: self._parse_request() except MaxSizeExceeded: self.simple_response('413 Request Entity Too Large') return
'Parse a Request-URI into (scheme, authority, path). Note that Request-URI\'s must be one of: Request-URI = "*" | absoluteURI | abs_path | authority Therefore, a Request-URI which starts with a double forward-slash cannot be a "net_path": net_path = "//" authority [ abs_path ] Instead, it must be interpreted as...
def parse_request_uri(self, uri):
if (uri == '*'): return (None, None, uri) i = uri.find('://') if ((i > 0) and ('?' not in uri[:i])): (scheme, remainder) = (uri[:i].lower(), uri[(i + 3):]) (authority, path) = remainder.split('/', 1) return (scheme, authority, path) if uri.startswith('/'): return ...
'Call the gateway and write its iterable output.'
def respond(self):
mrbs = self.server.max_request_body_size if self.chunked_read: self.rfile = ChunkedRFile(self.conn.rfile, mrbs) else: cl = int(self.inheaders.get('Content-Length', 0)) if (mrbs and (mrbs < cl)): if (not self.sent_headers): self.simple_response('413 Requ...
'Write a simple response back to the client.'
def simple_response(self, status, msg=''):
status = str(status) buf = [(((self.server.protocol + ' ') + status) + CRLF), ('Content-Length: %s\r\n' % len(msg)), 'Content-Type: text/plain\r\n'] if ((status[:3] == '413') and (self.response_protocol == 'HTTP/1.1')): self.close_connection = True buf.append('Connection: close\r...
'Write unbuffered data to the client.'
def write(self, chunk):
if (self.chunked_write and chunk): buf = [hex(len(chunk))[2:], CRLF, chunk, CRLF] self.conn.wfile.sendall(''.join(buf)) else: self.conn.wfile.sendall(chunk)
'Assert, process, and send the HTTP response message-headers. You must set self.status, and self.outheaders before calling this.'
def send_headers(self):
hkeys = [key.lower() for (key, value) in self.outheaders] status = int(self.status[:3]) if (status == 413): self.close_connection = True elif ('content-length' not in hkeys): if ((status < 200) or (status in (204, 205, 304))): pass elif ((self.response_protocol == 'HT...
'Read each request and respond appropriately.'
def communicate(self):
request_seen = False try: while True: req = None req = self.RequestHandlerClass(self.server, self) req.parse_request() if (not req.ready): return request_seen = True req.respond() if req.close_connection:...
'Close the socket underlying this connection.'
def close(self):
self.rfile.close() if (not self.linger): if hasattr(self.socket, '_sock'): self.socket._sock.close() self.socket.close() else: pass
'Start the pool of threads.'
def start(self):
for i in range(self.min): self._threads.append(WorkerThread(self.server)) for worker in self._threads: worker.setName(('CP Server ' + worker.getName())) worker.start() for worker in self._threads: while (not worker.ready): time.sleep(0.1)
'Number of worker threads which are idle. Read-only.'
def _get_idle(self):
return len([t for t in self._threads if (t.conn is None)])
'Spawn new worker threads (not above self.max).'
def grow(self, amount):
for i in range(amount): if ((self.max > 0) and (len(self._threads) >= self.max)): break worker = WorkerThread(self.server) worker.setName(('CP Server ' + worker.getName())) self._threads.append(worker) worker.start()
'Kill off worker threads (not below self.min).'
def shrink(self, amount):
for t in self._threads: if (not t.isAlive()): self._threads.remove(t) amount -= 1 if (amount > 0): for i in range(min(amount, (len(self._threads) - self.min))): self._queue.put(_SHUTDOWNREQUEST)
'Run the server forever.'
def start(self):
self._interrupt = None if ((self.ssl_adapter is None) and getattr(self, 'ssl_certificate', None) and getattr(self, 'ssl_private_key', None)): warnings.warn('SSL attributes are deprecated in CherryPy 3.2, and will be removed in CherryPy 3.3. Use an ssl_adap...
'Create (or recreate) the actual socket object.'
def bind(self, family, type, proto=0):
self.socket = socket.socket(family, type, proto) prevent_socket_inheritance(self.socket) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if (self.nodelay and (not isinstance(self.bind_addr, str))): self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) if (self.s...
'Accept a new connection and put it on the Queue.'
def tick(self):
try: (s, addr) = self.socket.accept() if (not self.ready): return prevent_socket_inheritance(s) if hasattr(s, 'settimeout'): s.settimeout(self.timeout) if (self.response_header is None): self.response_header = ('%s Server' % self.version...
'Gracefully shutdown a server that is serving forever.'
def stop(self):
self.ready = False sock = getattr(self, 'socket', None) if sock: if (not isinstance(self.bind_addr, basestring)): try: (host, port) = sock.getsockname()[:2] except socket.error as x: if (x.args[0] not in socket_errors_to_ignore): ...
'Return a new environ dict targeting the given wsgi.version'
def get_environ(self):
raise NotImplemented
'WSGI callable to begin the HTTP response.'
def start_response(self, status, headers, exc_info=None):
if (self.started_response and (not exc_info)): raise AssertionError('WSGI start_response called a second time with no exc_info.') self.started_response = True if self.req.sent_headers: try: raise exc_info[0], exc_info[1], exc_info[2] finally: ...
'WSGI callable to write unbuffered data to the client. This method is also used internally by start_response (to write data from the iterable returned by the WSGI application).'
def write(self, chunk):
if (not self.started_response): raise AssertionError('WSGI write called before start_response.') if (not self.req.sent_headers): self.req.sent_headers = True self.req.send_headers() self.req.write(chunk)
'Return a new environ dict targeting the given wsgi.version'
def get_environ(self):
req = self.req env = {'ACTUAL_SERVER_PROTOCOL': req.server.protocol, 'PATH_INFO': req.path, 'QUERY_STRING': req.qs, 'REMOTE_ADDR': (req.conn.remote_addr or ''), 'REMOTE_PORT': str((req.conn.remote_port or '')), 'REQUEST_METHOD': req.method, 'REQUEST_URI': req.uri, 'SCRIPT_NAME': '', 'SERVER_NAME': req.server.se...
'Return a new environ dict targeting the given wsgi.version'
def get_environ(self):
req = self.req env_10 = WSGIGateway_10.get_environ(self) env = dict([(k.decode('ISO-8859-1'), v) for (k, v) in env_10.iteritems()]) env[u'wsgi.version'] = ('u', 0) env.setdefault(u'wsgi.url_encoding', u'utf-8') try: for key in [u'PATH_INFO', u'SCRIPT_NAME', u'QUERY_STRING']: ...
'Wrap the given call with SSL error-trapping. is_reader: if False EOF errors will be raised. If True, EOF errors will return "" (to emulate normal sockets).'
def _safe_call(self, is_reader, call, *args, **kwargs):
start = time.time() while True: try: return call(*args, **kwargs) except SSL.WantReadError: time.sleep(self.ssl_retry) except SSL.WantWriteError: time.sleep(self.ssl_retry) except SSL.SysCallError as e: if (is_reader and (e.args == ...
'Wrap and return the given socket.'
def bind(self, sock):
if (self.context is None): self.context = self.get_context() conn = SSLConnection(self.context, sock) self._environ = self.get_environ() return conn
'Wrap and return the given socket, plus WSGI environ entries.'
def wrap(self, sock):
return (sock, self._environ.copy())
'Return an SSL.Context from self attributes.'
def get_context(self):
c = SSL.Context(SSL.SSLv23_METHOD) c.use_privatekey_file(self.private_key) if self.certificate_chain: c.load_verify_locations(self.certificate_chain) c.use_certificate_file(self.certificate) return c
'Return WSGI environ entries to be merged into each request.'
def get_environ(self):
ssl_environ = {'HTTPS': 'on'} if self.certificate: cert = open(self.certificate, 'rb').read() cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert) ssl_environ.update({'SSL_SERVER_M_VERSION': cert.get_version(), 'SSL_SERVER_M_SERIAL': cert.get_serial_number()}) for (prefix, d...
'Close and de-reference the current request and response. (Core)'
def close(self):
self.cpapp.release_serving()