def _send_email(cls):
"""
Check the email type and send the requested email using
the email plugin.
"""
if not hasattr(cherrypy.request, 'email_address'):
return
if not hasattr(cherrypy.request, 'email_type'):
return
cherrypy.request.user = User.get_by_email(cherrypy.request.email_address)
if 'mail' in cherrypy.request.user:
if cherrypy.request.email_type == 'password':
cherrypy.engine.publish('email-send-reset', cherrypy.request.user)
if cherrypy.request.email_type == 'username':
cherrypy.engine.publish('email-send-username', cherrypy.request.user)
python类request()的实例源码
cherrypyserver.py 文件源码
项目:arduino-ciao-meteor-ddp-connector
作者: andrea689
项目源码
文件源码
阅读 17
收藏 0
点赞 0
评论 0
def start_handler(self):
"""
Runs at the end of the request processing by calling
the opened method of the handler.
"""
request = cherrypy.request
if not hasattr(request, 'ws_handler'):
return
addr = (request.remote.ip, request.remote.port)
ws_handler = request.ws_handler
request.ws_handler = None
delattr(request, 'ws_handler')
# By doing this we detach the socket from
# the CherryPy stack avoiding memory leaks
detach_connection(request.rfile.rfile)
cherrypy.engine.publish('handle-websocket', ws_handler, addr)
def start_handler(self):
"""
Runs at the end of the request processing by calling
the opened method of the handler.
"""
request = cherrypy.request
if not hasattr(request, 'ws_handler'):
return
addr = (request.remote.ip, request.remote.port)
ws_handler = request.ws_handler
request.ws_handler = None
delattr(request, 'ws_handler')
# By doing this we detach the socket from
# the CherryPy stack avoiding memory leaks
detach_connection(request.rfile.rfile)
cherrypy.engine.publish('handle-websocket', ws_handler, addr)
def emit(self, record):
"""Emit a record."""
try:
stream = cherrypy.serving.request.wsgi_environ.get('wsgi.errors')
except (AttributeError, KeyError):
pass
else:
try:
msg = self.format(record)
fs = '%s\n'
import types
# if no unicode support...
if not hasattr(types, 'UnicodeType'):
stream.write(fs % msg)
else:
try:
stream.write(fs % msg)
except UnicodeError:
stream.write(fs % msg.encode('UTF-8'))
self.flush()
except:
self.handleError(record)
def __init__(self, path, query_string=''):
import cherrypy
self.request = cherrypy.serving.request
self.query_string = query_string
if '?' in path:
# Separate any params included in the path
path, self.query_string = path.split('?', 1)
# Note that urljoin will "do the right thing" whether url is:
# 1. a URL relative to root (e.g. "/dummy")
# 2. a URL relative to the current path
# Note that any query string will be discarded.
path = _urljoin(self.request.path_info, path)
# Set a 'path' member attribute so that code which traps this
# error can have access to it.
self.path = path
CherryPyException.__init__(self, path, self.query_string)
def _populate_known_types(self):
b = [x for x in vars(builtins).values()
if type(x) is type(str)]
def traverse(obj, namespace):
for name in dir(obj):
# Hack for 3.2's warning about body_params
if name == 'body_params':
continue
vtype = type(getattr(obj, name, None))
if vtype in b:
self.known_config_types[namespace + '.' + name] = vtype
traverse(cherrypy.request, 'request')
traverse(cherrypy.response, 'response')
traverse(cherrypy.server, 'server')
traverse(cherrypy.engine, 'engine')
traverse(cherrypy.log, 'log')
def most_similar(self, *args, **kwargs):
positive = cherrypy.request.params.get('positive[]', [])
if isinstance(positive, basestring):
positive = [positive]
negative = cherrypy.request.params.get('negative[]', [])
if isinstance(negative, basestring):
negative = [negative]
try:
result = self.model.most_similar(
positive=[gensim.utils.to_utf8(word).strip() for word in positive if word],
negative=[gensim.utils.to_utf8(word).strip() for word in negative if word],
topn=5)
except:
result = []
logger.info("similars for %s vs. %s: %s" % (positive, negative, result))
return {'similars': result}
def emit(self, record):
"""Emit a record."""
try:
stream = cherrypy.serving.request.wsgi_environ.get('wsgi.errors')
except (AttributeError, KeyError):
pass
else:
try:
msg = self.format(record)
fs = "%s\n"
import types
# if no unicode support...
if not hasattr(types, "UnicodeType"):
stream.write(fs % msg)
else:
try:
stream.write(fs % msg)
except UnicodeError:
stream.write(fs % msg.encode("UTF-8"))
self.flush()
except:
self.handleError(record)
def script_name(self, path=None):
"""The script_name of the app at the given path, or None.
If path is None, cherrypy.request is used.
"""
if path is None:
try:
request = cherrypy.serving.request
path = httputil.urljoin(request.script_name,
request.path_info)
except AttributeError:
return None
while True:
if path in self.apps:
return path
if path == "":
return None
# Move one node up the tree and try again.
path = path[:path.rfind("/")]
def __init__(self, path, query_string=""):
import cherrypy
self.request = cherrypy.serving.request
self.query_string = query_string
if "?" in path:
# Separate any params included in the path
path, self.query_string = path.split("?", 1)
# Note that urljoin will "do the right thing" whether url is:
# 1. a URL relative to root (e.g. "/dummy")
# 2. a URL relative to the current path
# Note that any query string will be discarded.
path = _urljoin(self.request.path_info, path)
# Set a 'path' member attribute so that code which traps this
# error can have access to it.
self.path = path
CherryPyException.__init__(self, path, self.query_string)
def _populate_known_types(self):
b = [x for x in vars(builtins).values()
if type(x) is type(str)]
def traverse(obj, namespace):
for name in dir(obj):
# Hack for 3.2's warning about body_params
if name == 'body_params':
continue
vtype = type(getattr(obj, name, None))
if vtype in b:
self.known_config_types[namespace + "." + name] = vtype
traverse(cherrypy.request, "request")
traverse(cherrypy.response, "response")
traverse(cherrypy.server, "server")
traverse(cherrypy.engine, "engine")
traverse(cherrypy.log, "log")
def _get_req_pub(self):
"""Private helper function to retrieve the publisher prefix
for the current operation from the request path. Returns None
if a publisher prefix was not found in the request path. The
publisher is assumed to be the first component of the path_info
string if it doesn't match the operation's name. This does mean
that a publisher can't be named the same as an operation, but
that isn't viewed as an unreasonable limitation.
"""
if self.request_pub_func:
return self.request_pub_func(cherrypy.request.path_info)
try:
req_pub = cherrypy.request.path_info.strip("/").split(
"/")[0]
except IndexError:
return None
if req_pub not in self.REPO_OPS_DEFAULT and req_pub != "feed":
# Assume that if the first component of the request path
# doesn't match a known operation that it's a publisher
# prefix.
return req_pub
return None
def catalog_1(self, *tokens):
"""Outputs the contents of the specified catalog file, using the
name in the request path, directly to the client."""
try:
name = tokens[0]
except IndexError:
raise cherrypy.HTTPError(http_client.FORBIDDEN,
_("Directory listing not allowed."))
try:
fpath = self.repo.catalog_1(name,
pub=self._get_req_pub())
except srepo.RepositoryError as e:
# Treat any remaining repository error as a 404, but
# log the error and include the real failure
# information.
cherrypy.log("Request failed: {0}".format(str(e)))
raise cherrypy.HTTPError(http_client.NOT_FOUND, str(e))
self.__set_response_expires("catalog", 86400, 86400)
return serve_file(fpath, "text/plain; charset=utf-8")
def manifest_1(self, *tokens):
"""Outputs the contents of the manifest or uploads the
manifest."""
method = cherrypy.request.method
if method == "GET":
return self.manifest_0(*tokens)
elif method in ("POST", "PUT"):
return self.__upload_manifest(*tokens)
raise cherrypy.HTTPError(http_client.METHOD_NOT_ALLOWED,
"{0} is not allowed".format(method))
# We need to prevent cherrypy from processing the request body so that
# manifest can parse the request body itself. In addition, we also need
# to set the timeout higher since the default is five minutes; not
# really enough for a slow connection to upload content.
def file_0(self, *tokens):
"""Outputs the contents of the file, named by the SHA-1 hash
name in the request path, directly to the client."""
try:
fhash = tokens[0]
except IndexError:
fhash = None
try:
fpath = self.repo.file(fhash, pub=self._get_req_pub())
except srepo.RepositoryFileNotFoundError as e:
raise cherrypy.HTTPError(http_client.NOT_FOUND, str(e))
except srepo.RepositoryError as e:
# Treat any remaining repository error as a 404, but
# log the error and include the real failure
# information.
cherrypy.log("Request failed: {0}".format(str(e)))
raise cherrypy.HTTPError(http_client.NOT_FOUND, str(e))
self.__set_response_expires("file", 86400*365, 86400*365)
return serve_file(fpath, "application/data")
def file_1(self, *tokens):
"""Outputs the contents of the file, named by the SHA hash
name in the request path, directly to the client."""
method = cherrypy.request.method
if method == "GET":
return self.file_0(*tokens)
elif method in ("POST", "PUT"):
return self.__upload_file(*tokens)
raise cherrypy.HTTPError(http_client.METHOD_NOT_ALLOWED,
"{0} is not allowed".format(method))
# We need to prevent cherrypy from processing the request body so that
# file can parse the request body itself. In addition, we also need to
# set the timeout higher since the default is five minutes; not really
# enough for a slow connection to upload content.
def abandon_0(self, *tokens):
"""Aborts an in-flight transaction for the Transaction ID
specified in the request path. Returns no output."""
try:
# cherrypy decoded it, but we actually need it encoded.
trans_id = quote(tokens[0], "")
except IndexError:
trans_id = None
try:
self.repo.abandon(trans_id)
except srepo.RepositoryError as e:
# Assume a bad request was made. A 404 can't be
# returned here as misc.versioned_urlopen will interpret
# that to mean that the server doesn't support this
# operation.
raise cherrypy.HTTPError(http_client.BAD_REQUEST, str(e))
def start(self):
"""Start the background task thread. Since we configure
mod_wsgi with an inactivity-timeout, long-running background
tasks which don't cause new WSGI HTTP requests can
result in us hitting that inactivity-timeout. To prevent this,
while background tasks are running, we periodically send a HTTP
request to the server."""
self.__running = True
if not self.__thread:
# Create and start a thread for the caller.
self.__thread = threading.Thread(target=self.run)
self.__thread.start()
self.__keep_busy_thread = threading.Thread(
target=self.run_keep_busy)
self.__keep_busy_thread.start()
def manifest(self, *tokens):
"""Manifest requests coming from the BUI need to be redirected
back through the RewriteRules defined in the Apache
configuration in order to be served directly.
pkg(1) will never hit this code, as those requests don't get
handled by this webapp.
"""
self.setup(cherrypy.request)
rel_uri = cherrypy.request.path_info
# we need to recover the escaped portions of the URI
redir = rel_uri.lstrip("/").split("/")
pub_mf = "/".join(redir[0:4])
pkg_name = "/".join(redir[4:])
# encode the URI so our RewriteRules can process them
pkg_name = quote(pkg_name)
pkg_name = pkg_name.replace("/", "%2F")
pkg_name = pkg_name.replace("%40", "@", 1)
# build a URI that we can redirect to
redir = "{0}/{1}".format(pub_mf, pkg_name)
redir = "/{0}".format(redir.lstrip("/"))
raise cherrypy.HTTPRedirect(redir)
def __init__(self):
"""
The Email Tool provides functionality for sending password
reset emails in the background rather than blocking
the request. The user should not be made aware of success
or failure, so all error handling is logged.
"""
cherrypy.Tool.__init__(self, 'on_end_request',
self._send_email,
priority=80)
cherrypyserver.py 文件源码
项目:arduino-ciao-meteor-ddp-connector
作者: andrea689
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
def _setup(self):
conf = self._merged_args()
hooks = cherrypy.serving.request.hooks
p = conf.pop("priority", getattr(self.callable, "priority",
self._priority))
hooks.attach(self._point, self.callable, priority=p, **conf)
hooks.attach('before_finalize', self.complete,
priority=p)
hooks.attach('on_end_resource', self.cleanup_headers,
priority=70)
hooks.attach('on_end_request', self.start_handler,
priority=70)
cherrypyserver.py 文件源码
项目:arduino-ciao-meteor-ddp-connector
作者: andrea689
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
def index(self):
cherrypy.log("Handler created: %s" % repr(cherrypy.request.ws_handler))
def _setup(self):
conf = self._merged_args()
hooks = cherrypy.serving.request.hooks
p = conf.pop("priority", getattr(self.callable, "priority",
self._priority))
hooks.attach(self._point, self.callable, priority=p, **conf)
hooks.attach('before_finalize', self.complete,
priority=p)
hooks.attach('on_end_resource', self.cleanup_headers,
priority=70)
hooks.attach('on_end_request', self.start_handler,
priority=70)
def index(self):
cherrypy.log("Handler created: %s" % repr(cherrypy.request.ws_handler))
def flush(self):
"""Flushes the stream."""
try:
stream = cherrypy.serving.request.wsgi_environ.get('wsgi.errors')
except (AttributeError, KeyError):
pass
else:
stream.flush()
def _get_script_name(self):
if self._script_name is not None:
return self._script_name
# A `_script_name` with a value of None signals that the script name
# should be pulled from WSGI environ.
return cherrypy.serving.request.wsgi_environ['SCRIPT_NAME'].rstrip('/')
def release_serving(self):
"""Release the current serving (request and response)."""
req = cherrypy.serving.request
cherrypy.engine.publish('after_request')
try:
req.close()
except:
cherrypy.log(traceback=True, severity=40)
cherrypy.serving.clear()
def __init__(self, urls, status=None, encoding=None):
import cherrypy
request = cherrypy.serving.request
if isinstance(urls, text_or_bytes):
urls = [urls]
abs_urls = []
for url in urls:
url = tonative(url, encoding or self.encoding)
# Note that urljoin will "do the right thing" whether url is:
# 1. a complete URL with host (e.g. "http://www.example.com/test")
# 2. a URL relative to root (e.g. "/dummy")
# 3. a URL relative to the current path
# Note that any query string in cherrypy.request is discarded.
url = _urljoin(cherrypy.url(), url)
abs_urls.append(url)
self.urls = abs_urls
# RFC 2616 indicates a 301 response code fits our goal; however,
# browser support for 301 is quite messy. Do 302/303 instead. See
# http://www.alanflavell.org.uk/www/post-redirect.html
if status is None:
if request.protocol >= (1, 1):
status = 303
else:
status = 302
else:
status = int(status)
if status < 300 or status > 399:
raise ValueError('status must be between 300 and 399.')
self.status = status
CherryPyException.__init__(self, abs_urls, status)
def __call__(self):
"""Use this exception as a request.handler (raise self)."""
raise self
def set_response(self):
"""Modify cherrypy.response status, headers, and body to represent
self.
CherryPy uses this internally, but you can also use it to create an
HTTPError object and set its output without *raising* the exception.
"""
import cherrypy
response = cherrypy.serving.response
clean_headers(self.code)
# In all cases, finalize will be called after this method,
# so don't bother cleaning up response values here.
response.status = self.status
tb = None
if cherrypy.serving.request.show_tracebacks:
tb = format_exc()
response.headers.pop('Content-Length', None)
content = self.get_error_page(self.status, traceback=tb,
message=self._message)
response.body = content
_be_ie_unfriendly(self.code)