class documentation

class twisted.web.http.Request: (source)

Known subclasses: twisted.web.proxy.ProxyRequest, twisted.web.proxy.ReverseProxyRequest, twisted.web.server.Request

Implements interfaces: twisted.internet.interfaces.IConsumer, twisted.web.http._IDeprecatedHTTPChannelToRequestInterface

View In Hierarchy

A HTTP request.

Subclasses should override the process() method to determine how the request will be processed.

Instance Variable method The HTTP method that was used, e.g. b'GET'.
Instance Variable uri The full encoded URI which was requested (including query arguments), e.g. b'/a/b%20/c?q=v'.
Instance Variable path The encoded path of the request URI (not including query arguments), e.g. b'/a/b%20/c'.
Instance Variable args A mapping of decoded query argument names as bytes to corresponding query argument values as lists of bytes. For example, for a URI with foo=bar&foo=baz&quux=spam as its query part args will be {b'foo': [b'bar', b'baz'], b'quux': [b'spam']}.
Instance Variable content A file-like object giving the request body. This may be a file on disk, an io.BytesIO, or some other type. The implementation is free to decide on a per-request basis.
Instance Variable cookies The cookies that will be sent in the response.
Instance Variable requestHeaders A http_headers.Headers instance giving all received HTTP request headers.
Instance Variable responseHeaders A http_headers.Headers instance holding all HTTP response headers to be sent.
Instance Variable notifications A list of Deferreds which are waiting for notification that the response to this request has been finished (successfully or with an error). Don't use this attribute directly, instead use the Request.notifyFinish method.
Instance Variable producer Undocumented
Instance Variable finished Undocumented
Instance Variable code_message Undocumented
Instance Variable clientproto Undocumented
Instance Variable startedWriting Undocumented
Instance Variable chunked Undocumented
Instance Variable sentLength Undocumented
Instance Variable etag Undocumented
Instance Variable lastModified Undocumented
Method __init__
Instance Variable channel Undocumented
Instance Variable client Undocumented
Instance Variable host Undocumented
Instance Variable received_cookies Undocumented
Instance Variable transport Undocumented
Instance Variable queued Undocumented
Method noLongerQueued Notify the object that it is no longer queued.
Method gotLength Called when HTTP channel got length of content in this request.
Method parseCookies Parse cookie headers.
Method handleContentChunk Write a chunk of data.
Method requestReceived Called by channel when all data has been received.
Method __repr__ Return a string description of the request including such information as the request method and request URI.
Method process Override in subclasses.
Method registerProducer Register a producer.
Instance Variable streamingProducer Undocumented
Method unregisterProducer Unregister the producer.
Method getHeader Get an HTTP request header.
Method getCookie Get a cookie that was sent from the network.
Method notifyFinish Notify when the response to this request has finished.
Method finish Indicate that all response data has been written to this Request.
Method write Write some data as a result of an HTTP request. The first time this is called, it writes out response data.
Method addCookie Set an outgoing HTTP cookie.
Method setResponseCode Set the HTTP response code.
Instance Variable code Undocumented
Method setHeader Set an HTTP response header. Overrides any previously set values for this header.
Method redirect Utility function that does a redirect.
Method setLastModified Set the Last-Modified time for the response to this request.
Method setETag Set an entity tag for the outgoing response.
Method getAllHeaders Return dictionary mapping the names of all received headers to the last value received for each.
Method getRequestHostname Get the hostname that the HTTP client passed in to the request.
Method getHost Get my originally requesting transport's host.
Method setHost Change the host and port the request thinks it's using.
Method getClientIP Return the IP address of the client who submitted this request.
Method getClientAddress Return the address of the client who submitted this request.
Method isSecure Return True if this request is using a secure transport.
Instance Variable user Undocumented
Instance Variable password Undocumented
Method getUser Return the HTTP user sent with this request, if any.
Method getPassword Return the HTTP password sent with this request, if any.
Method connectionLost There is no longer a connection for this request to respond over. Clean up anything which can't be useful anymore.
Method loseConnection Pass the loseConnection through to the underlying channel.
Method __eq__ Determines if two requests are the same object.
Method __hash__ A Request is hashable so that it can be used as a mapping key.
Instance Variable _disconnected A flag which is False until the connection over which this request was received is closed and which is True after that.
Instance Variable _log A logger instance for request related messages.
Instance Variable _forceSSL Undocumented
Method _cleanup Called when have finished responding and are no longer queued.
Method _authorize Undocumented
method = (source)
The HTTP method that was used, e.g. b'GET'.
(type: bytes)
The full encoded URI which was requested (including query arguments), e.g. b'/a/b%20/c?q=v'.
(type: bytes)
path = (source)
The encoded path of the request URI (not including query arguments), e.g. b'/a/b%20/c'.
(type: bytes)
args = (source)
A mapping of decoded query argument names as bytes to corresponding query argument values as lists of bytes. For example, for a URI with foo=bar&foo=baz&quux=spam as its query part args will be {b'foo': [b'bar', b'baz'], b'quux': [b'spam']}.
(type: dict of bytes to list of bytes)
content = (source)
A file-like object giving the request body. This may be a file on disk, an io.BytesIO, or some other type. The implementation is free to decide on a per-request basis.
(type: typing.BinaryIO)
cookies = (source)
The cookies that will be sent in the response.
(type: list of bytes)
requestHeaders = (source)
responseHeaders = (source)
All HTTP response headers to be sent.
(type: http_headers.Headers)
notifications = (source)
A list of Deferreds which are waiting for notification that the response to this request has been finished (successfully or with an error). Don't use this attribute directly, instead use the Request.notifyFinish method.
(type: list)
_disconnected = (source)
A flag which is False until the connection over which this request was received is closed and which is True after that.
(type: bool)
_log = (source)
A logger instance for request related messages.
(type: twisted.logger.Logger)
producer = (source)

Undocumented

finished = (source)

Undocumented

(type: int)
code_message = (source)

Undocumented

clientproto = (source)

Undocumented

startedWriting = (source)

Undocumented

(type: int)
chunked = (source)

Undocumented

(type: int)
sentLength = (source)

Undocumented

etag = (source)

Undocumented

lastModified = (source)

Undocumented

_forceSSL = (source)

Undocumented

def __init__(self, channel, queued=_QUEUED_SENTINEL): (source)
Parameterschannelthe channel we're connected to.
queued(deprecated) are we in the request queue, or can we start writing to the transport?
channel = (source)

Undocumented

client = (source)

Undocumented

host = (source)

Undocumented

received_cookies = (source)

Undocumented

(type: dict)
transport = (source)

Undocumented

queued = (source)

Undocumented

def _cleanup(self): (source)

Called when have finished responding and are no longer queued.

def noLongerQueued(self): (source)

Notify the object that it is no longer queued.

We start writing whatever data we have to the transport, etc.

This method is not intended for users.

In 16.3 this method was changed to become a no-op, as Request objects are now never queued.

def gotLength(self, length): (source)

Called when HTTP channel got length of content in this request.

This method is not intended for users.

ParameterslengthThe length of the request body, as indicated by the request headers. None if the request headers do not indicate a length.
def parseCookies(self): (source)

Parse cookie headers.

This method is not intended for users.

def handleContentChunk(self, data): (source)

Write a chunk of data.

This method is not intended for users.

def requestReceived(self, command, path, version): (source)

Called by channel when all data has been received.

This method is not intended for users.

ParameterscommandThe HTTP verb of this request. This has the case supplied by the client (eg, it maybe "get" rather than "GET"). (type: bytes)
pathThe URI of this request. (type: bytes)
versionThe HTTP version of this request. (type: bytes)
def __repr__(self): (source)

Return a string description of the request including such information as the request method and request URI.

ReturnsA string loosely describing this Request object. (type: str)
def process(self): (source)

Override in subclasses.

This method is not intended for users.

def registerProducer(self, producer, streaming): (source)
streamingProducer = (source)

Undocumented

def unregisterProducer(self): (source)

Unregister the producer.

def getHeader(self, key): (source)

Get an HTTP request header.

ParameterskeyThe name of the header to get the value of. (type: bytes or str)
ReturnsThe value of the specified header, or None if that header was not present in the request. The string type of the result matches the type of key. (type: bytes or str or None)
def getCookie(self, key): (source)

Get a cookie that was sent from the network.

ParameterskeyThe name of the cookie to get. (type: bytes)
ReturnsThe value of the specified cookie, or None if that cookie was not present in the request. (type: bytes or None)
def notifyFinish(self): (source)

Notify when the response to this request has finished.

ReturnsA Deferred which will be triggered when the request is finished -- with a None value if the request finishes successfully or with an error if the request is interrupted by an error (for example, the client closing the connection prematurely). (type: Deferred)
NoteThere are some caveats around the reliability of the delivery of this notification.
  1. If this Request's channel is paused, the notification will not be delivered. This can happen in one of two ways; either you can call request.transport.pauseProducing yourself, or,
  2. In order to deliver this notification promptly when a client disconnects, the reactor must continue reading from the transport, so that it can tell when the underlying network connection has gone away. Twisted Web will only keep reading up until a finite (small) maximum buffer size before it gives up and pauses the transport itself. If this occurs, you will not discover that the connection has gone away until a timeout fires or until the application attempts to send some data via Request.write.
  3. It is theoretically impossible to distinguish between successfully sending a response and the peer successfully receiving it. There are several networking edge cases where the Deferreds returned by notifyFinish will indicate success, but the data will never be received. There are also edge cases where the connection will appear to fail, but in reality the response was delivered. As a result, the information provided by the result of the Deferreds returned by this method should be treated as a guess; do not make critical decisions in your applications based upon it.
def finish(self): (source)

Indicate that all response data has been written to this Request.

def write(self, data): (source)

Write some data as a result of an HTTP request. The first time this is called, it writes out response data.

ParametersdataSome bytes to be sent as part of the response body. (type: bytes)
def addCookie(self, k, v, expires=None, domain=None, path=None, max_age=None, comment=None, secure=None, httpOnly=False, sameSite=None): (source)

Set an outgoing HTTP cookie.

In general, you should consider using sessions instead of cookies, see twisted.web.server.Request.getSession and the twisted.web.server.Session class for details.

Parameterskcookie name (type: bytes or str)
vcookie value (type: bytes or str)
expirescookie expire attribute value in "Wdy, DD Mon YYYY HH:MM:SS GMT" format (type: bytes or str)
domaincookie domain (type: bytes or str)
pathcookie path (type: bytes or str)
max_agecookie expiration in seconds from reception (type: bytes or str)
commentcookie comment (type: bytes or str)
securedirect browser to send the cookie on encrypted connections only (type: bool)
httpOnlydirect browser not to expose cookies through channels other than HTTP (and HTTPS) requests (type: bool)
sameSiteOne of None (default), 'lax' or 'strict'. Direct browsers not to send this cookie on cross-origin requests. Please see: https://tools.ietf.org/html/draft-west-first-party-cookies-07 (type: None, bytes or str)
RaisesValueErrorIf the value for sameSite is not supported.
def setResponseCode(self, code, message=None): (source)

Set the HTTP response code.

ParameterscodeUndocumented (type: int)
messageUndocumented (type: bytes)
code = (source)

Undocumented

def setHeader(self, name, value): (source)

Set an HTTP response header. Overrides any previously set values for this header.

ParametersnameThe name of the header for which to set the value. (type: bytes or str)
valueThe value to set for the named header. A str will be UTF-8 encoded, which may not interoperable with other implementations. Avoid passing non-ASCII characters if possible. (type: bytes or str)
def redirect(self, url): (source)

Utility function that does a redirect.

Set the response code to FOUND and the Location header to the given URL.

The request should have finish() called after this.

ParametersurlLocation header value. (type: bytes or str)
def setLastModified(self, when): (source)

Set the Last-Modified time for the response to this request.

If I am called more than once, I ignore attempts to set Last-Modified earlier, only replacing the Last-Modified time if it is to a later value.

If I am a conditional request, I may modify my response code to NOT_MODIFIED if appropriate for the time given.

ParameterswhenThe last time the resource being returned was modified, in seconds since the epoch. (type: number)
ReturnsIf I am a If-Modified-Since conditional request and the time given is not newer than the condition, I return http.CACHED to indicate that you should write no body. Otherwise, I return a false value.
def setETag(self, etag): (source)

Set an entity tag for the outgoing response.

That's "entity tag" as in the HTTP/1.1 ETag header, "used for comparing two or more entities from the same requested resource."

If I am a conditional request, I may modify my response code to NOT_MODIFIED or PRECONDITION_FAILED, if appropriate for the tag given.

ParametersetagThe entity tag for the resource being returned. (type: string)
ReturnsIf I am a If-None-Match conditional request and the tag matches one in the request, I return http.CACHED to indicate that you should write no body. Otherwise, I return a false value.
def getAllHeaders(self): (source)

Return dictionary mapping the names of all received headers to the last value received for each.

Since this method does not return all header information, self.requestHeaders.getAllRawHeaders() may be preferred.

def getRequestHostname(self): (source)

Get the hostname that the HTTP client passed in to the request.

Returnsthe requested hostname (type: bytes)
See AlsoIRequest.getRequestHostname
def getHost(self): (source)

Get my originally requesting transport's host.

Don't rely on the 'transport' attribute, since Request objects may be copied remotely. For information on this method's return value, see twisted.internet.tcp.Port.

def setHost(self, host, port, ssl=0): (source)

Change the host and port the request thinks it's using.

This method is useful for working with reverse HTTP proxies (e.g. both Squid and Apache's mod_proxy can do this), when the address the HTTP client is using is different than the one we're listening on.

For example, Apache may be listening on https://www.example.com/, and then forwarding requests to http://localhost:8080/, but we don't want HTML produced by Twisted to say b'http://localhost:8080/', they should say b'https://www.example.com/', so we do:

   request.setHost(b'www.example.com', 443, ssl=1)
ParametershostThe value to which to change the host header. (type: bytes)
portUndocumented
sslA flag which, if True, indicates that the request is considered secure (if True, isSecure will return True). (type: bool)
def getClientIP(self): (source)

Return the IP address of the client who submitted this request.

This method is deprecated. Use getClientAddress instead.

Returnsthe client IP address (type: str)
def getClientAddress(self): (source)

Return the address of the client who submitted this request.

This may not be a network address (e.g., a server listening on a UNIX domain socket will cause this to return UNIXAddress). Callers must check the type of the returned address.

Returnsthe client's address. (type: IAddress)
Present Since18.4
def isSecure(self): (source)

Return True if this request is using a secure transport.

Normally this method returns True if this request's HTTPChannel instance is using a transport that implements interfaces.ISSLTransport.

This will also return True if Request.setHost has been called with ssl=True.

ReturnsTrue if this request is secure (type: bool)
def _authorize(self): (source)

Undocumented

user = (source)

Undocumented

(type: bytes)
password = (source)

Undocumented

(type: bytes)
def getUser(self): (source)

Return the HTTP user sent with this request, if any.

If no user was supplied, return the empty string.

Returnsthe HTTP user, if any (type: bytes)
def getPassword(self): (source)

Return the HTTP password sent with this request, if any.

If no password was supplied, return the empty string.

Returnsthe HTTP password, if any (type: bytes)
def connectionLost(self, reason): (source)

There is no longer a connection for this request to respond over. Clean up anything which can't be useful anymore.

def loseConnection(self): (source)

Pass the loseConnection through to the underlying channel.

def __eq__(self, other): (source)

Determines if two requests are the same object.

ParametersotherAnother object whose identity will be compared to this instance's. (type: object)
ReturnsTrue when the two are the same object and False when not. (type: bool)
def __hash__(self): (source)

A Request is hashable so that it can be used as a mapping key.

ReturnsA int based on the instance's identity.
API Documentation for Twisted, generated by pydoctor 20.12.1 at 2021-02-28 19:53:36.