Python tornado.httputil.HTTPServerRequest() Examples
The following are 30
code examples of tornado.httputil.HTTPServerRequest().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
tornado.httputil
, or try the search function
.
Example #1
Source File: web.py From teleport with Apache License 2.0 | 6 votes |
def stream_request_body(cls): """Apply to `RequestHandler` subclasses to enable streaming body support. This decorator implies the following changes: * `.HTTPServerRequest.body` is undefined, and body arguments will not be included in `RequestHandler.get_argument`. * `RequestHandler.prepare` is called when the request headers have been read instead of after the entire body has been read. * The subclass must define a method ``data_received(self, data):``, which will be called zero or more times as data is available. Note that if the request has an empty body, ``data_received`` may not be called. * ``prepare`` and ``data_received`` may return Futures (such as via ``@gen.coroutine``, in which case the next method will not be called until those futures have completed. * The regular HTTP method (``post``, ``put``, etc) will be called after the entire body has been read. See the `file receiver demo <https://github.com/tornadoweb/tornado/tree/master/demos/file_upload/>`_ for example usage. """ # noqa: E501 if not issubclass(cls, RequestHandler): raise TypeError("expected subclass of RequestHandler, got %r", cls) cls._stream_request_body = True return cls
Example #2
Source File: httpserver.py From tornado-zh with MIT License | 6 votes |
def __init__(self, stream, address, protocol): self.address = address # Save the socket's address family now so we know how to # interpret self.address even after the stream is closed # and its socket attribute replaced with None. if stream.socket is not None: self.address_family = stream.socket.family else: self.address_family = None # In HTTPServerRequest we want an IP, not a full socket address. if (self.address_family in (socket.AF_INET, socket.AF_INET6) and address is not None): self.remote_ip = address[0] else: # Unix (or other) socket; fake the remote address. self.remote_ip = '0.0.0.0' if protocol: self.protocol = protocol elif isinstance(stream, iostream.SSLIOStream): self.protocol = "https" else: self.protocol = "http" self._orig_remote_ip = self.remote_ip self._orig_protocol = self.protocol
Example #3
Source File: routing.py From teleport with Apache License 2.0 | 6 votes |
def match(self, request: httputil.HTTPServerRequest) -> Optional[Dict[str, Any]]: match = self.regex.match(request.path) if match is None: return None if not self.regex.groups: return {} path_args = [] # type: List[bytes] path_kwargs = {} # type: Dict[str, bytes] # Pass matched groups to the handler. Since # match.groups() includes both named and # unnamed groups, we want to use either groups # or groupdict but not both. if self.regex.groupindex: path_kwargs = dict( (str(k), _unquote_or_none(v)) for (k, v) in match.groupdict().items() ) else: path_args = [_unquote_or_none(s) for s in match.groups()] return dict(path_args=path_args, path_kwargs=path_kwargs)
Example #4
Source File: httpserver.py From tornado-zh with MIT License | 6 votes |
def __init__(self, stream, address, protocol): self.address = address # Save the socket's address family now so we know how to # interpret self.address even after the stream is closed # and its socket attribute replaced with None. if stream.socket is not None: self.address_family = stream.socket.family else: self.address_family = None # In HTTPServerRequest we want an IP, not a full socket address. if (self.address_family in (socket.AF_INET, socket.AF_INET6) and address is not None): self.remote_ip = address[0] else: # Unix (or other) socket; fake the remote address. self.remote_ip = '0.0.0.0' if protocol: self.protocol = protocol elif isinstance(stream, iostream.SSLIOStream): self.protocol = "https" else: self.protocol = "http" self._orig_remote_ip = self.remote_ip self._orig_protocol = self.protocol
Example #5
Source File: web.py From opendevops with GNU General Public License v3.0 | 6 votes |
def get_handler_delegate( self, request: httputil.HTTPServerRequest, target_class: Type[RequestHandler], target_kwargs: Dict[str, Any] = None, path_args: List[bytes] = None, path_kwargs: Dict[str, bytes] = None, ) -> "_HandlerDelegate": """Returns `~.httputil.HTTPMessageDelegate` that can serve a request for application and `RequestHandler` subclass. :arg httputil.HTTPServerRequest request: current HTTP request. :arg RequestHandler target_class: a `RequestHandler` class. :arg dict target_kwargs: keyword arguments for ``target_class`` constructor. :arg list path_args: positional arguments for ``target_class`` HTTP method that will be executed while handling a request (``get``, ``post`` or any other). :arg dict path_kwargs: keyword arguments for ``target_class`` HTTP method. """ return _HandlerDelegate( self, request, target_class, target_kwargs, path_args, path_kwargs )
Example #6
Source File: routing.py From teleport with Apache License 2.0 | 6 votes |
def find_handler( self, request: httputil.HTTPServerRequest, **kwargs: Any ) -> Optional[httputil.HTTPMessageDelegate]: for rule in self.rules: target_params = rule.matcher.match(request) if target_params is not None: if rule.target_kwargs: target_params["target_kwargs"] = rule.target_kwargs delegate = self.get_target_delegate( rule.target, request, **target_params ) if delegate is not None: return delegate return None
Example #7
Source File: routing.py From teleport with Apache License 2.0 | 6 votes |
def headers_received( self, start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine], headers: httputil.HTTPHeaders, ) -> Optional[Awaitable[None]]: assert isinstance(start_line, httputil.RequestStartLine) request = httputil.HTTPServerRequest( connection=self.request_conn, server_connection=self.server_conn, start_line=start_line, headers=headers, ) self.delegate = self.router.find_handler(request) if self.delegate is None: app_log.debug( "Delegate for %s %s request not found", start_line.method, start_line.path, ) self.delegate = _DefaultMessageDelegate(self.request_conn) return self.delegate.headers_received(start_line, headers)
Example #8
Source File: web.py From opendevops with GNU General Public License v3.0 | 6 votes |
def stream_request_body(cls: Type[RequestHandler]) -> Type[RequestHandler]: """Apply to `RequestHandler` subclasses to enable streaming body support. This decorator implies the following changes: * `.HTTPServerRequest.body` is undefined, and body arguments will not be included in `RequestHandler.get_argument`. * `RequestHandler.prepare` is called when the request headers have been read instead of after the entire body has been read. * The subclass must define a method ``data_received(self, data):``, which will be called zero or more times as data is available. Note that if the request has an empty body, ``data_received`` may not be called. * ``prepare`` and ``data_received`` may return Futures (such as via ``@gen.coroutine``, in which case the next method will not be called until those futures have completed. * The regular HTTP method (``post``, ``put``, etc) will be called after the entire body has been read. See the `file receiver demo <https://github.com/tornadoweb/tornado/tree/master/demos/file_upload/>`_ for example usage. """ # noqa: E501 if not issubclass(cls, RequestHandler): raise TypeError("expected subclass of RequestHandler, got %r", cls) cls._stream_request_body = True return cls
Example #9
Source File: web.py From opendevops with GNU General Public License v3.0 | 6 votes |
def __init__( self, application: Application, request: httputil.HTTPServerRequest, handler_class: Type[RequestHandler], handler_kwargs: Optional[Dict[str, Any]], path_args: Optional[List[bytes]], path_kwargs: Optional[Dict[str, bytes]], ) -> None: self.application = application self.connection = request.connection self.request = request self.handler_class = handler_class self.handler_kwargs = handler_kwargs or {} self.path_args = path_args or [] self.path_kwargs = path_kwargs or {} self.chunks = [] # type: List[bytes] self.stream_request_body = _has_stream_request_body(self.handler_class)
Example #10
Source File: web.py From teleport with Apache License 2.0 | 6 votes |
def __init__( self, application: Application, request: httputil.HTTPServerRequest, handler_class: Type[RequestHandler], handler_kwargs: Optional[Dict[str, Any]], path_args: Optional[List[bytes]], path_kwargs: Optional[Dict[str, bytes]], ) -> None: self.application = application self.connection = request.connection self.request = request self.handler_class = handler_class self.handler_kwargs = handler_kwargs or {} self.path_args = path_args or [] self.path_kwargs = path_kwargs or {} self.chunks = [] # type: List[bytes] self.stream_request_body = _has_stream_request_body(self.handler_class)
Example #11
Source File: web.py From teleport with Apache License 2.0 | 6 votes |
def stream_request_body(cls: Type[RequestHandler]) -> Type[RequestHandler]: """Apply to `RequestHandler` subclasses to enable streaming body support. This decorator implies the following changes: * `.HTTPServerRequest.body` is undefined, and body arguments will not be included in `RequestHandler.get_argument`. * `RequestHandler.prepare` is called when the request headers have been read instead of after the entire body has been read. * The subclass must define a method ``data_received(self, data):``, which will be called zero or more times as data is available. Note that if the request has an empty body, ``data_received`` may not be called. * ``prepare`` and ``data_received`` may return Futures (such as via ``@gen.coroutine``, in which case the next method will not be called until those futures have completed. * The regular HTTP method (``post``, ``put``, etc) will be called after the entire body has been read. See the `file receiver demo <https://github.com/tornadoweb/tornado/tree/master/demos/file_upload/>`_ for example usage. """ # noqa: E501 if not issubclass(cls, RequestHandler): raise TypeError("expected subclass of RequestHandler, got %r", cls) cls._stream_request_body = True return cls
Example #12
Source File: routing.py From teleport with Apache License 2.0 | 6 votes |
def get_target_delegate(self, target, request, **target_params): """Returns an instance of `~.httputil.HTTPMessageDelegate` for a Rule's target. This method is called by `~.find_handler` and can be extended to provide additional target types. :arg target: a Rule's target. :arg httputil.HTTPServerRequest request: current request. :arg target_params: additional parameters that can be useful for `~.httputil.HTTPMessageDelegate` creation. """ if isinstance(target, Router): return target.find_handler(request, **target_params) elif isinstance(target, httputil.HTTPServerConnectionDelegate): return target.start_request(request.server_connection, request.connection) elif callable(target): return _CallableAdapter( partial(target, **target_params), request.connection ) return None
Example #13
Source File: routing.py From opendevops with GNU General Public License v3.0 | 6 votes |
def headers_received( self, start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine], headers: httputil.HTTPHeaders, ) -> Optional[Awaitable[None]]: assert isinstance(start_line, httputil.RequestStartLine) request = httputil.HTTPServerRequest( connection=self.request_conn, server_connection=self.server_conn, start_line=start_line, headers=headers, ) self.delegate = self.router.find_handler(request) if self.delegate is None: app_log.debug( "Delegate for %s %s request not found", start_line.method, start_line.path, ) self.delegate = _DefaultMessageDelegate(self.request_conn) return self.delegate.headers_received(start_line, headers)
Example #14
Source File: routing.py From opendevops with GNU General Public License v3.0 | 6 votes |
def find_handler( self, request: httputil.HTTPServerRequest, **kwargs: Any ) -> Optional[httputil.HTTPMessageDelegate]: for rule in self.rules: target_params = rule.matcher.match(request) if target_params is not None: if rule.target_kwargs: target_params["target_kwargs"] = rule.target_kwargs delegate = self.get_target_delegate( rule.target, request, **target_params ) if delegate is not None: return delegate return None
Example #15
Source File: httpserver.py From teleport with Apache License 2.0 | 6 votes |
def __init__(self, stream, address, protocol, trusted_downstream=None): self.address = address # Save the socket's address family now so we know how to # interpret self.address even after the stream is closed # and its socket attribute replaced with None. if stream.socket is not None: self.address_family = stream.socket.family else: self.address_family = None # In HTTPServerRequest we want an IP, not a full socket address. if (self.address_family in (socket.AF_INET, socket.AF_INET6) and address is not None): self.remote_ip = address[0] else: # Unix (or other) socket; fake the remote address. self.remote_ip = '0.0.0.0' if protocol: self.protocol = protocol elif isinstance(stream, iostream.SSLIOStream): self.protocol = "https" else: self.protocol = "http" self._orig_remote_ip = self.remote_ip self._orig_protocol = self.protocol self.trusted_downstream = set(trusted_downstream or [])
Example #16
Source File: routing.py From opendevops with GNU General Public License v3.0 | 6 votes |
def match(self, request: httputil.HTTPServerRequest) -> Optional[Dict[str, Any]]: match = self.regex.match(request.path) if match is None: return None if not self.regex.groups: return {} path_args = [] # type: List[bytes] path_kwargs = {} # type: Dict[str, bytes] # Pass matched groups to the handler. Since # match.groups() includes both named and # unnamed groups, we want to use either groups # or groupdict but not both. if self.regex.groupindex: path_kwargs = dict( (str(k), _unquote_or_none(v)) for (k, v) in match.groupdict().items() ) else: path_args = [_unquote_or_none(s) for s in match.groups()] return dict(path_args=path_args, path_kwargs=path_kwargs)
Example #17
Source File: web.py From teleport with Apache License 2.0 | 5 votes |
def cookies(self) -> Dict[str, http.cookies.Morsel]: """An alias for `self.request.cookies <.httputil.HTTPServerRequest.cookies>`.""" return self.request.cookies
Example #18
Source File: routing.py From teleport with Apache License 2.0 | 5 votes |
def match(self, request): """Matches current instance against the request. :arg httputil.HTTPServerRequest request: current HTTP request :returns: a dict of parameters to be passed to the target handler (for example, ``handler_kwargs``, ``path_args``, ``path_kwargs`` can be passed for proper `~.web.RequestHandler` instantiation). An empty dict is a valid (and common) return value to indicate a match when the argument-passing features are not used. ``None`` must be returned to indicate that there is no match.""" raise NotImplementedError()
Example #19
Source File: web.py From teleport with Apache License 2.0 | 5 votes |
def __init__( self, application: "Application", request: httputil.HTTPServerRequest, **kwargs: Any ) -> None: super(RequestHandler, self).__init__() self.application = application self.request = request self._headers_written = False self._finished = False self._auto_finish = True self._prepared_future = None self.ui = ObjectDict( (n, self._ui_method(m)) for n, m in application.ui_methods.items() ) # UIModules are available as both `modules` and `_tt_modules` in the # template namespace. Historically only `modules` was available # but could be clobbered by user additions to the namespace. # The template {% module %} directive looks in `_tt_modules` to avoid # possible conflicts. self.ui["_tt_modules"] = _UIModuleNamespace(self, application.ui_modules) self.ui["modules"] = self.ui["_tt_modules"] self.clear() assert self.request.connection is not None # TODO: need to add set_close_callback to HTTPConnection interface self.request.connection.set_close_callback( # type: ignore self.on_connection_close ) self.initialize(**kwargs) # type: ignore
Example #20
Source File: httpserver.py From teleport with Apache License 2.0 | 5 votes |
def headers_received( self, start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine], headers: httputil.HTTPHeaders, ) -> Optional[Awaitable[None]]: self.request = httputil.HTTPServerRequest( connection=self.connection, start_line=typing.cast(httputil.RequestStartLine, start_line), headers=headers, ) return None
Example #21
Source File: web.py From teleport with Apache License 2.0 | 5 votes |
def cookies(self) -> Dict[str, http.cookies.Morsel]: """An alias for `self.request.cookies <.httputil.HTTPServerRequest.cookies>`.""" return self.request.cookies
Example #22
Source File: web.py From teleport with Apache License 2.0 | 5 votes |
def get_target_delegate( self, target: Any, request: httputil.HTTPServerRequest, **target_params: Any ) -> Optional[httputil.HTTPMessageDelegate]: if isclass(target) and issubclass(target, RequestHandler): return self.application.get_handler_delegate( request, target, **target_params ) return super(_ApplicationRouter, self).get_target_delegate( target, request, **target_params )
Example #23
Source File: routing.py From teleport with Apache License 2.0 | 5 votes |
def headers_received(self, start_line, headers): request = httputil.HTTPServerRequest( connection=self.request_conn, server_connection=self.server_conn, start_line=start_line, headers=headers) self.delegate = self.router.find_handler(request) if self.delegate is None: app_log.debug("Delegate for %s %s request not found", start_line.method, start_line.path) self.delegate = _DefaultMessageDelegate(self.request_conn) return self.delegate.headers_received(start_line, headers)
Example #24
Source File: routing.py From teleport with Apache License 2.0 | 5 votes |
def find_handler(self, request, **kwargs): # type: (httputil.HTTPServerRequest, typing.Any)->httputil.HTTPMessageDelegate """Must be implemented to return an appropriate instance of `~.httputil.HTTPMessageDelegate` that can serve the request. Routing implementations may pass additional kwargs to extend the routing logic. :arg httputil.HTTPServerRequest request: current HTTP request. :arg kwargs: additional keyword arguments passed by routing implementation. :returns: an instance of `~.httputil.HTTPMessageDelegate` that will be used to process the request. """ raise NotImplementedError()
Example #25
Source File: wsgi.py From teleport with Apache License 2.0 | 5 votes |
def environ(request): """Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment. """ hostport = request.host.split(":") if len(hostport) == 2: host = hostport[0] port = int(hostport[1]) else: host = request.host port = 443 if request.protocol == "https" else 80 environ = { "REQUEST_METHOD": request.method, "SCRIPT_NAME": "", "PATH_INFO": to_wsgi_str(escape.url_unescape( request.path, encoding=None, plus=False)), "QUERY_STRING": request.query, "REMOTE_ADDR": request.remote_ip, "SERVER_NAME": host, "SERVER_PORT": str(port), "SERVER_PROTOCOL": request.version, "wsgi.version": (1, 0), "wsgi.url_scheme": request.protocol, "wsgi.input": BytesIO(escape.utf8(request.body)), "wsgi.errors": sys.stderr, "wsgi.multithread": False, "wsgi.multiprocess": True, "wsgi.run_once": False, } if "Content-Type" in request.headers: environ["CONTENT_TYPE"] = request.headers.pop("Content-Type") if "Content-Length" in request.headers: environ["CONTENT_LENGTH"] = request.headers.pop("Content-Length") for key, value in request.headers.items(): environ["HTTP_" + key.replace("-", "_").upper()] = value return environ
Example #26
Source File: web.py From teleport with Apache License 2.0 | 5 votes |
def __call__( self, request: httputil.HTTPServerRequest ) -> Optional[Awaitable[None]]: # Legacy HTTPServer interface dispatcher = self.find_handler(request) return dispatcher.execute()
Example #27
Source File: httpserver.py From teleport with Apache License 2.0 | 5 votes |
def headers_received(self, start_line, headers): self.request = httputil.HTTPServerRequest( connection=self.connection, start_line=start_line, headers=headers)
Example #28
Source File: web.py From teleport with Apache License 2.0 | 5 votes |
def get_handler_delegate(self, request, target_class, target_kwargs=None, path_args=None, path_kwargs=None): """Returns `~.httputil.HTTPMessageDelegate` that can serve a request for application and `RequestHandler` subclass. :arg httputil.HTTPServerRequest request: current HTTP request. :arg RequestHandler target_class: a `RequestHandler` class. :arg dict target_kwargs: keyword arguments for ``target_class`` constructor. :arg list path_args: positional arguments for ``target_class`` HTTP method that will be executed while handling a request (``get``, ``post`` or any other). :arg dict path_kwargs: keyword arguments for ``target_class`` HTTP method. """ return _HandlerDelegate( self, request, target_class, target_kwargs, path_args, path_kwargs)
Example #29
Source File: routing.py From teleport with Apache License 2.0 | 5 votes |
def get_target_delegate( self, target: Any, request: httputil.HTTPServerRequest, **target_params: Any ) -> Optional[httputil.HTTPMessageDelegate]: """Returns an instance of `~.httputil.HTTPMessageDelegate` for a Rule's target. This method is called by `~.find_handler` and can be extended to provide additional target types. :arg target: a Rule's target. :arg httputil.HTTPServerRequest request: current request. :arg target_params: additional parameters that can be useful for `~.httputil.HTTPMessageDelegate` creation. """ if isinstance(target, Router): return target.find_handler(request, **target_params) elif isinstance(target, httputil.HTTPServerConnectionDelegate): assert request.connection is not None return target.start_request(request.server_connection, request.connection) elif callable(target): assert request.connection is not None return _CallableAdapter( partial(target, **target_params), request.connection ) return None
Example #30
Source File: web.py From tornado-zh with MIT License | 5 votes |
def cookies(self): """ `self.request.cookies <.httputil.HTTPServerRequest.cookies>` 的别名.""" return self.request.cookies