本文整理汇总了Python中tornado.web.RequestHandler方法的典型用法代码示例。如果您正苦于以下问题:Python web.RequestHandler方法的具体用法?Python web.RequestHandler怎么用?Python web.RequestHandler使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tornado.web
的用法示例。
在下文中一共展示了web.RequestHandler方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_app
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import RequestHandler [as 别名]
def get_app(self):
class HelloHandler(RequestHandler):
def get(self):
self.write("Hello world!")
class PathQuotingHandler(RequestHandler):
def get(self, path):
self.write(path)
# It would be better to run the wsgiref server implementation in
# another thread instead of using our own WSGIContainer, but this
# fits better in our async testing framework and the wsgiref
# validator should keep us honest
return WSGIContainer(validator(WSGIApplication([
("/", HelloHandler),
("/path/(.*)", PathQuotingHandler),
("/typecheck", TypeCheckHandler),
])))
示例2: test_formdata
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import RequestHandler [as 别名]
def test_formdata(tornado_testcase, sentry_init, capture_events):
sentry_init(integrations=[TornadoIntegration()], send_default_pii=True)
events = capture_events()
class FormdataHandler(RequestHandler):
def post(self):
raise ValueError(json.dumps(sorted(self.request.body_arguments)))
client = tornado_testcase(Application([(r"/form", FormdataHandler)]))
response = client.fetch(
"/form?queryarg=1",
method="POST",
headers={"Content-Type": "application/x-www-form-urlencoded"},
body=b"field1=value1&field2=value2",
)
assert response.code == 500
(event,) = events
(exception,) = event["exception"]["values"]
assert exception["value"] == '["field1", "field2"]'
assert event["request"]["data"] == {"field1": ["value1"], "field2": ["value2"]}
示例3: _on_request_token
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import RequestHandler [as 别名]
def _on_request_token(
self,
authorize_url: str,
callback_uri: Optional[str],
response: httpclient.HTTPResponse,
) -> None:
handler = cast(RequestHandler, self)
request_token = _oauth_parse_response(response.body)
data = (
base64.b64encode(escape.utf8(request_token["key"]))
+ b"|"
+ base64.b64encode(escape.utf8(request_token["secret"]))
)
handler.set_cookie("_oauth_request_token", data)
args = dict(oauth_token=request_token["key"])
if callback_uri == "oob":
handler.finish(authorize_url + "?" + urllib.parse.urlencode(args))
return
elif callback_uri:
args["oauth_callback"] = urllib.parse.urljoin(
handler.request.full_url(), callback_uri
)
handler.redirect(authorize_url + "?" + urllib.parse.urlencode(args))
示例4: open
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import RequestHandler [as 别名]
def open(self):
methods_to_test = [
functools.partial(self.write, "This should not work"),
functools.partial(self.redirect, "http://localhost/elsewhere"),
functools.partial(self.set_header, "X-Test", ""),
functools.partial(self.set_cookie, "Chocolate", "Chip"),
functools.partial(self.set_status, 503),
self.flush,
self.finish,
]
for method in methods_to_test:
try:
# In a websocket context, many RequestHandler methods
# raise RuntimeErrors.
method()
raise Exception("did not get expected exception")
except RuntimeError:
pass
self.write_message(self.request.headers.get("X-Test", ""))
示例5: get_app
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import RequestHandler [as 别名]
def get_app(self):
wsgi_app = WSGIContainer(self.wsgi_app)
class Handler(RequestHandler):
def get(self, *args, **kwargs):
self.finish(self.reverse_url("tornado"))
return RuleRouter(
[
(
PathMatches("/tornado.*"),
Application([(r"/tornado/test", Handler, {}, "tornado")]),
),
(PathMatches("/wsgi"), wsgi_app),
]
)
示例6: test_path_with_multiple_methods
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import RequestHandler [as 别名]
def test_path_with_multiple_methods(self, spec):
class HelloHandler(RequestHandler):
def get(self):
self.write("hello")
def post(self):
self.write("hello")
urlspec = (r"/hello", HelloHandler)
operations = {
"get": {"description": "get a greeting", "responses": {"200": {}}},
"post": {"description": "post a greeting", "responses": {"200": {}}},
}
spec.path(urlspec=urlspec, operations=operations)
paths = get_paths(spec)
get_op = paths["/hello"]["get"]
post_op = paths["/hello"]["post"]
assert get_op["description"] == "get a greeting"
assert post_op["description"] == "post a greeting"
示例7: initialize
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import RequestHandler [as 别名]
def initialize(self):
"""Hook for subclass initialization.
A dictionary passed as the third argument of a url spec will be
supplied as keyword arguments to initialize().
Example::
class ProfileHandler(RequestHandler):
def initialize(self, database):
self.database = database
def get(self, username):
...
app = Application([
(r'/user/(.*)', ProfileHandler, dict(database=database)),
])
"""
pass
示例8: _convert_header_value
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import RequestHandler [as 别名]
def _convert_header_value(self, value):
if isinstance(value, bytes_type):
pass
elif isinstance(value, unicode_type):
value = value.encode('utf-8')
elif isinstance(value, numbers.Integral):
# return immediately since we know the converted value will be safe
return str(value)
elif isinstance(value, datetime.datetime):
return httputil.format_timestamp(value)
else:
raise TypeError("Unsupported header value %r" % value)
# If \n is allowed into the header, it is possible to inject
# additional headers or split the request. Also cap length to
# prevent obviously erroneous values.
if (len(value) > 4000 or
RequestHandler._INVALID_HEADER_CHAR_RE.search(value)):
raise ValueError("Unsafe header value %r", value)
return value
示例9: get_arguments
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import RequestHandler [as 别名]
def get_arguments(self, name, strip=True):
"""Returns a list of the arguments with the given name.
If the argument is not present, returns an empty list.
The returned values are always unicode.
"""
values = []
for v in self.request.arguments.get(name, []):
v = self.decode_argument(v, name=name)
if isinstance(v, unicode_type):
# Get rid of any weird control chars (unless decoding gave
# us bytes, in which case leave it alone)
v = RequestHandler._remove_control_chars_regex.sub(" ", v)
if strip:
v = v.strip()
values.append(v)
return values
示例10: render_string
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import RequestHandler [as 别名]
def render_string(self, template_name, **kwargs):
"""Generate the given template with the given arguments.
We return the generated byte string (in utf8). To generate and
write a template as a response, use render() above.
"""
# If no template_path is specified, use the path of the calling file
template_path = self.get_template_path()
if not template_path:
frame = sys._getframe(0)
web_file = frame.f_code.co_filename
while frame.f_code.co_filename == web_file:
frame = frame.f_back
template_path = os.path.dirname(frame.f_code.co_filename)
with RequestHandler._template_loader_lock:
if template_path not in RequestHandler._template_loaders:
loader = self.create_template_loader(template_path)
RequestHandler._template_loaders[template_path] = loader
else:
loader = RequestHandler._template_loaders[template_path]
t = loader.load(template_name)
namespace = self.get_template_namespace()
namespace.update(kwargs)
return t.generate(**namespace)
示例11: authenticated
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import RequestHandler [as 别名]
def authenticated(method):
"""Decorate methods with this to require that the user be logged in.
If the user is not logged in, they will be redirected to the configured
`login url <RequestHandler.get_login_url>`.
"""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if not self.current_user:
if self.request.method in ("GET", "HEAD"):
url = self.get_login_url()
if "?" not in url:
if urlparse.urlsplit(url).scheme:
# if login url is absolute, make next absolute too
next_url = self.request.full_url()
else:
next_url = self.request.uri
url += "?" + urlencode(dict(next=next_url))
self.redirect(url)
return
raise HTTPError(403)
return method(self, *args, **kwargs)
return wrapper
示例12: get_app
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import RequestHandler [as 别名]
def get_app(self):
class HelloHandler(RequestHandler):
def get(self):
self.finish('Hello world')
class LargeHandler(RequestHandler):
def get(self):
# 512KB should be bigger than the socket buffers so it will
# be written out in chunks.
self.write(''.join(chr(i % 256) * 1024 for i in range(512)))
class FinishOnCloseHandler(RequestHandler):
@asynchronous
def get(self):
self.flush()
def on_connection_close(self):
# This is not very realistic, but finishing the request
# from the close callback has the right timing to mimic
# some errors seen in the wild.
self.finish('closed')
return Application([('/', HelloHandler),
('/large', LargeHandler),
('/finish_on_close', FinishOnCloseHandler)])
示例13: __init__
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import RequestHandler [as 别名]
def __init__(self, pattern, handler_class, kwargs=None, name=None):
"""Parameters:
* ``pattern``: Regular expression to be matched. Any groups
in the regex will be passed in to the handler's get/post/etc
methods as arguments.
* ``handler_class``: `RequestHandler` subclass to be invoked.
* ``kwargs`` (optional): A dictionary of additional arguments
to be passed to the handler's constructor.
* ``name`` (optional): A name for this handler. Used by
`Application.reverse_url`.
"""
if not pattern.endswith('$'):
pattern += '$'
self.regex = re.compile(pattern)
assert len(self.regex.groupindex) in (0, self.regex.groups), \
("groups in url regexes must either be all named or all "
"positional: %r" % self.regex.pattern)
self.handler_class = handler_class
self.kwargs = kwargs or {}
self.name = name
self._path, self._group_count = self._find_groups()
示例14: open
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import RequestHandler [as 别名]
def open(self):
try:
# In a websocket context, many RequestHandler methods
# raise RuntimeErrors.
self.set_status(503)
raise Exception("did not get expected exception")
except RuntimeError:
pass
self.write_message(self.request.headers.get('X-Test', ''))
示例15: get_app
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import RequestHandler [as 别名]
def get_app(self):
class ProcessHandler(RequestHandler):
def get(self):
if self.get_argument("exit", None):
# must use os._exit instead of sys.exit so unittest's
# exception handler doesn't catch it
os._exit(int(self.get_argument("exit")))
if self.get_argument("signal", None):
os.kill(os.getpid(),
int(self.get_argument("signal")))
self.write(str(os.getpid()))
return Application([("/", ProcessHandler)])