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.clean_freq and (not cls.clean_thread)):
t = cherrypy.process.plugins.Monitor(cherrypy.engine, self.clean_up, (self.clean_freq * 60), name='Session cleanup')
t.subscribe()
cls.clean_thread = t
t.start()
|
'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:
pass
|
'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')[(len(lockfiles) > 1)]
warn(('%s session lockfile%s found at startup. If you are only running one process, then you may need to manually delete the lockfiles found at %r.' % (len(lockfiles), plural, cls.storage_path)))
|
'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.locked = True
|
'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._load(path)
if (contents is not None):
(data, expiration_time) = contents
if (expiration_time < now):
os.unlink(path)
finally:
self.release_lock(path)
|
'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(sortby)
oldout = sys.stdout
try:
sys.stdout = sio
s.print_stats()
finally:
sys.stdout = oldout
response = sio.getvalue()
sio.close()
return response
|
'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 will
dump its profile data into a separate file.'
| 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."
warnings.warn(msg)
self.nextapp = nextapp
self.aggregate = aggregate
if aggregate:
self.profiler = ProfileAggregator(path)
else:
self.profiler = Profiler(path)
|
'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-Length']
return True
else:
cherrypy.serving.request.login = username
cherrypy.session[self.session_key] = username
self.on_login(username)
raise cherrypy.HTTPRedirect((from_page or '/'))
|
'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 anonymous', 'TOOLS.SESSAUTH')
if (not username):
url = cherrypy.url(qs=request.query_string)
if self.debug:
cherrypy.log(('No username, routing to login_screen with from_page %r' % url), 'TOOLS.SESSAUTH')
response.body = self.login_screen(url)
if ('Content-Length' in response.headers):
del response.headers['Content-Length']
return True
if self.debug:
cherrypy.log(('Setting request.login to %r' % username), 'TOOLS.SESSAUTH')
request.login = username
self.on_check(username)
|
'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:
val = atom[0]
else:
val = ''
params[key] = val
return (initial_value, params)
|
'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 the \'tools\' namespace handler with the args: (\'gzip.on\', v)'
| 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 = handler.__enter__()
no_exc = True
try:
for (k, v) in ns_confs.get(ns, {}).items():
callable(k, v)
except:
no_exc = False
if (exit is None):
raise
if (not exit(*sys.exc_info())):
raise
finally:
if (no_exc and exit):
exit(None, None, None)
else:
for (k, v) in ns_confs.get(ns, {}).items():
handler(k, v)
|
'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:
msg = ('Config error in section: %r, option: %r, value: %r. Config values must be valid Python.' % (section, option, value))
raise ValueError(msg, x.__class__.__name__, x.args)
result[section][option] = value
return result
|
'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\'s tree,
starting from cherrypy.request.app.root, and matching path
components to successive objects in the tree. For example, the
URL "/path/to/handler" might return root.path.to.handler.
The second object returned will be a list of names which are
\'virtual path\' components: parts of the URL which are dynamic,
and were not used when looking up the handler.
These virtual path components are passed to the handler as
positional arguments.'
| 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_trail = [['root', root, nodeconf, curpath]]
node = root
names = ([x for x in path.strip('/').split('/') if x] + ['index'])
iternames = names[:]
while iternames:
name = iternames[0]
objname = name.replace('.', '_')
nodeconf = {}
subnode = getattr(node, objname, None)
if (subnode is None):
dispatch = getattr(node, dispatch_name, None)
if (dispatch and callable(dispatch) and (not getattr(dispatch, 'exposed', False))):
subnode = dispatch(vpath=iternames)
name = iternames.pop(0)
node = subnode
if (node is not None):
if hasattr(node, '_cp_config'):
nodeconf.update(node._cp_config)
curpath = '/'.join((curpath, name))
if (curpath in app.config):
nodeconf.update(app.config[curpath])
object_trail.append([name, node, nodeconf, curpath])
def set_conf():
'Collapse all object_trail config into cherrypy.request.config.'
base = cherrypy.config.copy()
for (name, obj, conf, curpath) in object_trail:
base.update(conf)
if ('tools.staticdir.dir' in conf):
base['tools.staticdir.section'] = curpath
return base
num_candidates = (len(object_trail) - 1)
for i in range(num_candidates, (-1), (-1)):
(name, candidate, nodeconf, curpath) = object_trail[i]
if (candidate is None):
continue
if hasattr(candidate, 'default'):
defhandler = candidate.default
if getattr(defhandler, 'exposed', False):
conf = getattr(defhandler, '_cp_config', {})
object_trail.insert((i + 1), ['default', defhandler, conf, curpath])
request.config = set_conf()
request.is_index = path.endswith('/')
return (defhandler, names[i:(-1)])
if getattr(candidate, 'exposed', False):
request.config = set_conf()
if (i == num_candidates):
request.is_index = True
else:
request.is_index = False
return (candidate, names[i:(-1)])
request.config = set_conf()
return (None, [])
|
'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['Allow'] = ', '.join(avail)
meth = request.method.upper()
func = getattr(resource, meth, None)
if ((func is None) and (meth == 'HEAD')):
func = getattr(resource, 'GET', None)
if func:
if hasattr(func, '_cp_config'):
request.config.update(func._cp_config)
vpath = [x.replace('%2F', '/') for x in vpath]
request.handler = LateParamPageHandler(func, *vpath)
else:
request.handler = cherrypy.HTTPError(405)
else:
request.handler = cherrypy.NotFound()
|
'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.redirect = self.redirect
result = self.mapper.match(path_info)
config.mapper_dict = result
params = {}
if result:
params = result.copy()
if (not self.full_result):
params.pop('controller', None)
params.pop('action', None)
request.params.update(params)
request.config = base = cherrypy.config.copy()
curpath = ''
def merge(nodeconf):
if ('tools.staticdir.dir' in nodeconf):
nodeconf['tools.staticdir.section'] = (curpath or '/')
base.update(nodeconf)
app = request.app
root = app.root
if hasattr(root, '_cp_config'):
merge(root._cp_config)
if ('/' in app.config):
merge(app.config['/'])
atoms = [x for x in path_info.split('/') if x]
if atoms:
last = atoms.pop()
else:
last = None
for atom in atoms:
curpath = '/'.join((curpath, atom))
if (curpath in app.config):
merge(app.config[curpath])
handler = None
if result:
controller = result.get('controller', None)
controller = self.controllers.get(controller)
if controller:
if hasattr(controller, '_cp_config'):
merge(controller._cp_config)
action = result.get('action', None)
if (action is not None):
handler = getattr(controller, action, None)
if hasattr(handler, '_cp_config'):
merge(handler._cp_config)
if last:
curpath = '/'.join((curpath, last))
if (curpath in app.config):
merge(app.config[curpath])
return handler
|
'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_addr)
|
'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)
else:
scheme = 'http'
if (port != 80):
host += (':%s' % port)
return ('%s://%s' % (scheme, host))
|
'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.InternalRedirect):
exc = sys.exc_info()[1]
except:
exc = sys.exc_info()[1]
cherrypy.log(traceback=True, severity=40)
if exc:
raise
|
'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) tuples.
rfile should be a file-like object containing the HTTP request entity.
When run() is done, the returned object should have 3 attributes:
status, e.g. "200 OK"
header_list, a list of (name, value) tuples
body, an iterable yielding strings
Consumer code (HTTP servers) should then access these response
attributes to build the outbound stream.'
| 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_protocol[7]))
sp = (int(self.server_protocol[5]), int(self.server_protocol[7]))
self.protocol = min(rp, sp)
response.headers.protocol = self.protocol
url = path
if query_string:
url += ('?' + query_string)
self.request_line = ('%s %s %s' % (method, url, req_protocol))
self.header_list = list(headers)
self.headers = httputil.HeaderMap()
self.rfile = rfile
self.body = None
self.cookie = SimpleCookie()
self.handler = None
self.script_name = self.app.script_name
self.path_info = pi = path[len(self.script_name):]
self.stage = 'respond'
self.respond(pi)
except self.throws:
raise
except:
if self.throw_errors:
raise
else:
cherrypy.log(traceback=True, severity=40)
if self.show_tracebacks:
body = format_exc()
else:
body = ''
r = bare_error(body)
(response.output_status, response.header_list, response.body) = r
if (self.method == 'HEAD'):
response.body = []
try:
cherrypy.log.access()
except:
cherrypy.log.error(traceback=True)
if response.timed_out:
raise cherrypy.TimeoutError()
return response
|
'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.stage = 'get_resource'
self.get_resource(path_info)
self.body = _cpreqbody.RequestBody(self.rfile, self.headers, request_params=self.params)
self.namespaces(self.config)
self.stage = 'on_start_resource'
self.hooks.run('on_start_resource')
self.stage = 'process_query_string'
self.process_query_string()
if self.process_request_body:
if (self.method not in self.methods_with_bodies):
self.process_request_body = False
self.stage = 'before_request_body'
self.hooks.run('before_request_body')
if self.process_request_body:
self.body.process()
self.stage = 'before_handler'
self.hooks.run('before_handler')
if self.handler:
self.stage = 'handler'
response.body = self.handler()
self.stage = 'before_finalize'
self.hooks.run('before_finalize')
response.finalize()
except (cherrypy.HTTPRedirect, cherrypy.HTTPError) as inst:
inst.set_response()
self.stage = 'before_finalize (HTTPError)'
self.hooks.run('before_finalize')
response.finalize()
finally:
self.stage = 'on_end_resource'
self.hooks.run('on_end_resource')
except self.throws:
raise
except:
if self.throw_errors:
raise
self.handle_error()
|
'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 with %r.' % self.query_string_encoding))
for (key, value) in p.items():
if isinstance(key, unicode):
del p[key]
p[key.encode(self.query_string_encoding)] = value
self.params.update(p)
|
'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 == 'Cookie'):
try:
self.cookie.load(value)
except CookieError:
msg = ('Illegal cookie name %s' % value.split('=')[0])
raise cherrypy.HTTPError(400, msg)
if (not dict.__contains__(headers, 'Host')):
if (self.protocol >= (1, 1)):
msg = "HTTP/1.1 requires a 'Host' request header."
raise cherrypy.HTTPError(400, msg)
host = dict.get(headers, 'Host')
if (not host):
host = (self.local.name or self.local.ip)
self.base = ('%s://%s' % (self.scheme, host))
|
'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.finalize()
|
'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 None):
dict.pop(headers, 'Content-Length', None)
elif ((code < 200) or (code in (204, 205, 304))):
dict.pop(headers, 'Content-Length', None)
self.body = ''
elif (dict.get(headers, 'Content-Length') is None):
content = self.collapse_body()
dict.__setitem__(headers, 'Content-Length', len(content))
self.header_list = h = headers.output()
cookie = self.cookie.output()
if cookie:
for line in cookie.split('\n'):
if line.endswith('\r'):
line = line[:(-1)]
(name, value) = line.split(': ', 1)
if isinstance(name, unicode):
name = name.encode('ISO-8859-1')
if isinstance(value, unicode):
value = headers.encode(value)
h.append((name, value))
|
'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_SSL):
if e.args[1].endswith('http request'):
raise wsgiserver.NoSSLError
raise
return (s, self.get_environ(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 an "abs_path" with an empty first
path segment:
abs_path = "/" path_segments
path_segments = segment *( "/" segment )
segment = *pchar *( ";" param )
param = *pchar'
| 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 (None, None, uri)
else:
return (None, uri, None)
|
'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 Request Entity Too Large')
return
self.rfile = KnownLengthRFile(self.conn.rfile, cl)
self.server.gateway(self).respond()
if (self.ready and (not self.sent_headers)):
self.sent_headers = True
self.send_headers()
if self.chunked_write:
self.conn.wfile.sendall('0\r\n\r\n')
|
'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\n')
buf.append(CRLF)
if msg:
if isinstance(msg, unicode):
msg = msg.encode('ISO-8859-1')
buf.append(msg)
try:
self.conn.wfile.sendall(''.join(buf))
except socket.error as x:
if (x.args[0] not in socket_errors_to_ignore):
raise
|
'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 == 'HTTP/1.1') and (self.method != 'HEAD')):
self.chunked_write = True
self.outheaders.append(('Transfer-Encoding', 'chunked'))
else:
self.close_connection = True
if ('connection' not in hkeys):
if (self.response_protocol == 'HTTP/1.1'):
if self.close_connection:
self.outheaders.append(('Connection', 'close'))
elif (not self.close_connection):
self.outheaders.append(('Connection', 'Keep-Alive'))
if ((not self.close_connection) and (not self.chunked_read)):
remaining = getattr(self.rfile, 'remaining', 0)
if (remaining > 0):
self.rfile.read(remaining)
if ('date' not in hkeys):
self.outheaders.append(('Date', rfc822.formatdate()))
if ('server' not in hkeys):
self.outheaders.append(('Server', self.server.server_name))
buf = [(((self.server.protocol + ' ') + self.status) + CRLF)]
for (k, v) in self.outheaders:
buf.append((((k + ': ') + v) + CRLF))
buf.append(CRLF)
self.conn.wfile.sendall(''.join(buf))
|
'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:
return
except socket.error as e:
errnum = e.args[0]
if (errnum == 'timed out'):
if ((not request_seen) or (req and req.started_request)):
if (req and (not req.sent_headers)):
try:
req.simple_response('408 Request Timeout')
except FatalSSLAlert:
return
elif (errnum not in socket_errors_to_ignore):
if (req and (not req.sent_headers)):
try:
req.simple_response('500 Internal Server Error', format_exc())
except FatalSSLAlert:
return
return
except (KeyboardInterrupt, SystemExit):
raise
except FatalSSLAlert:
return
except NoSSLError:
if (req and (not req.sent_headers)):
self.wfile = CP_fileobject(self.socket._sock, 'wb', (-1))
req.simple_response('400 Bad Request', 'The client sent a plain HTTP request, but this server only speaks HTTPS on this port.')
self.linger = True
except Exception:
if (req and (not req.sent_headers)):
try:
req.simple_response('500 Internal Server Error', format_exc())
except FatalSSLAlert:
return
|
'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_adapter attribute instead.', DeprecationWarning)
try:
from cherrypy.wsgiserver.ssl_pyopenssl import pyOpenSSLAdapter
except ImportError:
pass
else:
self.ssl_adapter = pyOpenSSLAdapter(self.ssl_certificate, self.ssl_private_key, getattr(self, 'ssl_certificate_chain', None))
if isinstance(self.bind_addr, basestring):
try:
os.unlink(self.bind_addr)
except:
pass
try:
os.chmod(self.bind_addr, 511)
except:
pass
info = [(socket.AF_UNIX, socket.SOCK_STREAM, 0, '', self.bind_addr)]
else:
(host, port) = self.bind_addr
try:
info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)
except socket.gaierror:
if (':' in self.bind_addr[0]):
info = [(socket.AF_INET6, socket.SOCK_STREAM, 0, '', (self.bind_addr + (0, 0)))]
else:
info = [(socket.AF_INET, socket.SOCK_STREAM, 0, '', self.bind_addr)]
self.socket = None
msg = 'No socket could be created'
for res in info:
(af, socktype, proto, canonname, sa) = res
try:
self.bind(af, socktype, proto)
except socket.error as msg:
if self.socket:
self.socket.close()
self.socket = None
continue
break
if (not self.socket):
raise socket.error(msg)
self.socket.settimeout(1)
self.socket.listen(self.request_queue_size)
self.requests.start()
self.ready = True
while self.ready:
self.tick()
if self.interrupt:
while (self.interrupt is True):
time.sleep(0.1)
if self.interrupt:
raise self.interrupt
|
'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.ssl_adapter is not None):
self.socket = self.ssl_adapter.bind(self.socket)
if ((family == socket.AF_INET6) and (self.bind_addr[0] in ('::', '::0', '::0.0.0.0'))):
try:
self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
except (AttributeError, socket.error):
pass
self.socket.bind(self.bind_addr)
|
'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)
makefile = CP_fileobject
ssl_env = {}
if (self.ssl_adapter is not None):
try:
(s, ssl_env) = self.ssl_adapter.wrap(s)
except NoSSLError:
msg = 'The client sent a plain HTTP request, but this server only speaks HTTPS on this port.'
buf = [('%s 400 Bad Request\r\n' % self.protocol), ('Content-Length: %s\r\n' % len(msg)), 'Content-Type: text/plain\r\n\r\n', msg]
wfile = CP_fileobject(s, 'wb', (-1))
try:
wfile.sendall(''.join(buf))
except socket.error as x:
if (x.args[0] not in socket_errors_to_ignore):
raise
return
if (not s):
return
makefile = self.ssl_adapter.makefile
conn = self.ConnectionClass(self, s, makefile)
if (not isinstance(self.bind_addr, basestring)):
if (addr is None):
if (len(s.getsockname()) == 2):
addr = ('0.0.0.0', 0)
else:
addr = ('::', 0)
conn.remote_addr = addr[0]
conn.remote_port = addr[1]
conn.ssl_env = ssl_env
self.requests.put(conn)
except socket.timeout:
return
except socket.error as x:
if (x.args[0] in socket_error_eintr):
return
if (x.args[0] in socket_errors_nonblocking):
return
if (x.args[0] in socket_errors_to_ignore):
return
raise
|
'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):
raise
else:
for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM):
(af, socktype, proto, canonname, sa) = res
s = None
try:
s = socket.socket(af, socktype, proto)
s.settimeout(1.0)
s.connect((host, port))
s.close()
except socket.error:
if s:
s.close()
if hasattr(sock, 'close'):
sock.close()
self.socket = None
self.requests.stop(self.shutdown_timeout)
|
'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:
exc_info = None
self.req.status = status
for (k, v) in headers:
if (not isinstance(k, str)):
raise TypeError(('WSGI response header key %r is not a byte string.' % k))
if (not isinstance(v, str)):
raise TypeError(('WSGI response header value %r is not a byte string.' % v))
self.req.outheaders.extend(headers)
return self.write
|
'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.server_name, 'SERVER_PROTOCOL': req.request_protocol, 'wsgi.errors': sys.stderr, 'wsgi.input': req.rfile, 'wsgi.multiprocess': False, 'wsgi.multithread': True, 'wsgi.run_once': False, 'wsgi.url_scheme': req.scheme, 'wsgi.version': (1, 0)}
if isinstance(req.server.bind_addr, basestring):
env['SERVER_PORT'] = ''
else:
env['SERVER_PORT'] = str(req.server.bind_addr[1])
for (k, v) in req.inheaders.iteritems():
env[('HTTP_' + k.upper().replace('-', '_'))] = v
ct = env.pop('HTTP_CONTENT_TYPE', None)
if (ct is not None):
env['CONTENT_TYPE'] = ct
cl = env.pop('HTTP_CONTENT_LENGTH', None)
if (cl is not None):
env['CONTENT_LENGTH'] = cl
if req.conn.ssl_env:
env.update(req.conn.ssl_env)
return env
|
'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']:
env[key] = env_10[str(key)].decode(env[u'wsgi.url_encoding'])
except UnicodeDecodeError:
env[u'wsgi.url_encoding'] = u'ISO-8859-1'
for key in [u'PATH_INFO', u'SCRIPT_NAME', u'QUERY_STRING']:
env[key] = env_10[str(key)].decode(env[u'wsgi.url_encoding'])
for (k, v) in sorted(env.items()):
if (isinstance(v, str) and (k not in ('REQUEST_URI', 'wsgi.input'))):
env[k] = v.decode('ISO-8859-1')
return env
|
'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 == ((-1), 'Unexpected EOF'))):
return ''
errnum = e.args[0]
if (is_reader and (errnum in wsgiserver.socket_errors_to_ignore)):
return ''
raise socket.error(errnum)
except SSL.Error as e:
if (is_reader and (e.args == ((-1), 'Unexpected EOF'))):
return ''
thirdarg = None
try:
thirdarg = e.args[0][0][2]
except IndexError:
pass
if (thirdarg == 'http request'):
raise wsgiserver.NoSSLError()
raise wsgiserver.FatalSSLAlert(*e.args)
except:
raise
if ((time.time() - start) > self.ssl_timeout):
raise socket.timeout('timed out')
|
'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, dn) in [('I', cert.get_issuer()), ('S', cert.get_subject())]:
dnstr = str(dn)[18:(-2)]
wsgikey = ('SSL_SERVER_%s_DN' % prefix)
ssl_environ[wsgikey] = dnstr
while dnstr:
pos = dnstr.rfind('=')
(dnstr, value) = (dnstr[:pos], dnstr[(pos + 1):])
pos = dnstr.rfind('/')
(dnstr, key) = (dnstr[:pos], dnstr[(pos + 1):])
if (key and value):
wsgikey = ('SSL_SERVER_%s_DN_%s' % (prefix, key))
ssl_environ[wsgikey] = value
return ssl_environ
|
'Close and de-reference the current request and response. (Core)'
| def close(self):
| self.cpapp.release_serving()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.