iweb.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  1. # -*- test-case-name: twisted.web.test -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Interface definitions for L{twisted.web}.
  6. @var UNKNOWN_LENGTH: An opaque object which may be used as the value of
  7. L{IBodyProducer.length} to indicate that the length of the entity
  8. body is not known in advance.
  9. """
  10. from typing import TYPE_CHECKING, Callable, List, Optional
  11. from zope.interface import Attribute, Interface
  12. from twisted.cred.credentials import IUsernameDigestHash
  13. from twisted.internet.defer import Deferred
  14. from twisted.internet.interfaces import IPushProducer
  15. from twisted.web.http_headers import Headers
  16. if TYPE_CHECKING:
  17. from twisted.web.template import Flattenable, Tag
  18. class IRequest(Interface):
  19. """
  20. An HTTP request.
  21. @since: 9.0
  22. """
  23. method = Attribute("A L{bytes} giving the HTTP method that was used.")
  24. uri = Attribute(
  25. "A L{bytes} giving the full encoded URI which was requested (including"
  26. " query arguments)."
  27. )
  28. path = Attribute(
  29. "A L{bytes} giving the encoded query path of the request URI (not "
  30. "including query arguments)."
  31. )
  32. args = Attribute(
  33. "A mapping of decoded query argument names as L{bytes} to "
  34. "corresponding query argument values as L{list}s of L{bytes}. "
  35. "For example, for a URI with C{foo=bar&foo=baz&quux=spam} "
  36. "for its query part, C{args} will be C{{b'foo': [b'bar', b'baz'], "
  37. "b'quux': [b'spam']}}."
  38. )
  39. prepath = Attribute(
  40. "The URL path segments which have been processed during resource "
  41. "traversal, as a list of L{bytes}."
  42. )
  43. postpath = Attribute(
  44. "The URL path segments which have not (yet) been processed "
  45. "during resource traversal, as a list of L{bytes}."
  46. )
  47. requestHeaders = Attribute(
  48. "A L{http_headers.Headers} instance giving all received HTTP request "
  49. "headers."
  50. )
  51. content = Attribute(
  52. "A file-like object giving the request body. This may be a file on "
  53. "disk, an L{io.BytesIO}, or some other type. The implementation is "
  54. "free to decide on a per-request basis."
  55. )
  56. responseHeaders = Attribute(
  57. "A L{http_headers.Headers} instance holding all HTTP response "
  58. "headers to be sent."
  59. )
  60. def getHeader(key):
  61. """
  62. Get an HTTP request header.
  63. @type key: L{bytes} or L{str}
  64. @param key: The name of the header to get the value of.
  65. @rtype: L{bytes} or L{str} or L{None}
  66. @return: The value of the specified header, or L{None} if that header
  67. was not present in the request. The string type of the result
  68. matches the type of C{key}.
  69. """
  70. def getCookie(key):
  71. """
  72. Get a cookie that was sent from the network.
  73. @type key: L{bytes}
  74. @param key: The name of the cookie to get.
  75. @rtype: L{bytes} or L{None}
  76. @returns: The value of the specified cookie, or L{None} if that cookie
  77. was not present in the request.
  78. """
  79. def getAllHeaders():
  80. """
  81. Return dictionary mapping the names of all received headers to the last
  82. value received for each.
  83. Since this method does not return all header information,
  84. C{requestHeaders.getAllRawHeaders()} may be preferred.
  85. """
  86. def getRequestHostname():
  87. """
  88. Get the hostname that the HTTP client passed in to the request.
  89. This will either use the C{Host:} header (if it is available; which,
  90. for a spec-compliant request, it will be) or the IP address of the host
  91. we are listening on if the header is unavailable.
  92. @note: This is the I{host portion} of the requested resource, which
  93. means that:
  94. 1. it might be an IPv4 or IPv6 address, not just a DNS host
  95. name,
  96. 2. there's no guarantee it's even a I{valid} host name or IP
  97. address, since the C{Host:} header may be malformed,
  98. 3. it does not include the port number.
  99. @returns: the requested hostname
  100. @rtype: L{bytes}
  101. """
  102. def getHost():
  103. """
  104. Get my originally requesting transport's host.
  105. @return: An L{IAddress<twisted.internet.interfaces.IAddress>}.
  106. """
  107. def getClientAddress():
  108. """
  109. Return the address of the client who submitted this request.
  110. The address may not be a network address. Callers must check
  111. its type before using it.
  112. @since: 18.4
  113. @return: the client's address.
  114. @rtype: an L{IAddress} provider.
  115. """
  116. def getClientIP():
  117. """
  118. Return the IP address of the client who submitted this request.
  119. This method is B{deprecated}. See L{getClientAddress} instead.
  120. @returns: the client IP address or L{None} if the request was submitted
  121. over a transport where IP addresses do not make sense.
  122. @rtype: L{str} or L{None}
  123. """
  124. def getUser():
  125. """
  126. Return the HTTP user sent with this request, if any.
  127. If no user was supplied, return the empty string.
  128. @returns: the HTTP user, if any
  129. @rtype: L{str}
  130. """
  131. def getPassword():
  132. """
  133. Return the HTTP password sent with this request, if any.
  134. If no password was supplied, return the empty string.
  135. @returns: the HTTP password, if any
  136. @rtype: L{str}
  137. """
  138. def isSecure():
  139. """
  140. Return True if this request is using a secure transport.
  141. Normally this method returns True if this request's HTTPChannel
  142. instance is using a transport that implements ISSLTransport.
  143. This will also return True if setHost() has been called
  144. with ssl=True.
  145. @returns: True if this request is secure
  146. @rtype: C{bool}
  147. """
  148. def getSession(sessionInterface=None):
  149. """
  150. Look up the session associated with this request or create a new one if
  151. there is not one.
  152. @return: The L{Session} instance identified by the session cookie in
  153. the request, or the C{sessionInterface} component of that session
  154. if C{sessionInterface} is specified.
  155. """
  156. def URLPath():
  157. """
  158. @return: A L{URLPath<twisted.python.urlpath.URLPath>} instance
  159. which identifies the URL for which this request is.
  160. """
  161. def prePathURL():
  162. """
  163. At any time during resource traversal or resource rendering,
  164. returns an absolute URL to the most nested resource which has
  165. yet been reached.
  166. @see: {twisted.web.server.Request.prepath}
  167. @return: An absolute URL.
  168. @rtype: L{bytes}
  169. """
  170. def rememberRootURL():
  171. """
  172. Remember the currently-processed part of the URL for later
  173. recalling.
  174. """
  175. def getRootURL():
  176. """
  177. Get a previously-remembered URL.
  178. @return: An absolute URL.
  179. @rtype: L{bytes}
  180. """
  181. # Methods for outgoing response
  182. def finish():
  183. """
  184. Indicate that the response to this request is complete.
  185. """
  186. def write(data):
  187. """
  188. Write some data to the body of the response to this request. Response
  189. headers are written the first time this method is called, after which
  190. new response headers may not be added.
  191. @param data: Bytes of the response body.
  192. @type data: L{bytes}
  193. """
  194. def addCookie(
  195. k,
  196. v,
  197. expires=None,
  198. domain=None,
  199. path=None,
  200. max_age=None,
  201. comment=None,
  202. secure=None,
  203. ):
  204. """
  205. Set an outgoing HTTP cookie.
  206. In general, you should consider using sessions instead of cookies, see
  207. L{twisted.web.server.Request.getSession} and the
  208. L{twisted.web.server.Session} class for details.
  209. """
  210. def setResponseCode(code, message=None):
  211. """
  212. Set the HTTP response code.
  213. @type code: L{int}
  214. @type message: L{bytes}
  215. """
  216. def setHeader(k, v):
  217. """
  218. Set an HTTP response header. Overrides any previously set values for
  219. this header.
  220. @type k: L{bytes} or L{str}
  221. @param k: The name of the header for which to set the value.
  222. @type v: L{bytes} or L{str}
  223. @param v: The value to set for the named header. A L{str} will be
  224. UTF-8 encoded, which may not interoperable with other
  225. implementations. Avoid passing non-ASCII characters if possible.
  226. """
  227. def redirect(url):
  228. """
  229. Utility function that does a redirect.
  230. The request should have finish() called after this.
  231. """
  232. def setLastModified(when):
  233. """
  234. Set the C{Last-Modified} time for the response to this request.
  235. If I am called more than once, I ignore attempts to set Last-Modified
  236. earlier, only replacing the Last-Modified time if it is to a later
  237. value.
  238. If I am a conditional request, I may modify my response code to
  239. L{NOT_MODIFIED<http.NOT_MODIFIED>} if appropriate for the time given.
  240. @param when: The last time the resource being returned was modified, in
  241. seconds since the epoch.
  242. @type when: L{int} or L{float}
  243. @return: If I am a C{If-Modified-Since} conditional request and the time
  244. given is not newer than the condition, I return
  245. L{CACHED<http.CACHED>} to indicate that you should write no body.
  246. Otherwise, I return a false value.
  247. """
  248. def setETag(etag):
  249. """
  250. Set an C{entity tag} for the outgoing response.
  251. That's "entity tag" as in the HTTP/1.1 I{ETag} header, "used for
  252. comparing two or more entities from the same requested resource."
  253. If I am a conditional request, I may modify my response code to
  254. L{NOT_MODIFIED<http.NOT_MODIFIED>} or
  255. L{PRECONDITION_FAILED<http.PRECONDITION_FAILED>}, if appropriate for the
  256. tag given.
  257. @param etag: The entity tag for the resource being returned.
  258. @type etag: L{str}
  259. @return: If I am a C{If-None-Match} conditional request and the tag
  260. matches one in the request, I return L{CACHED<http.CACHED>} to
  261. indicate that you should write no body. Otherwise, I return a
  262. false value.
  263. """
  264. def setHost(host, port, ssl=0):
  265. """
  266. Change the host and port the request thinks it's using.
  267. This method is useful for working with reverse HTTP proxies (e.g. both
  268. Squid and Apache's mod_proxy can do this), when the address the HTTP
  269. client is using is different than the one we're listening on.
  270. For example, Apache may be listening on https://www.example.com, and
  271. then forwarding requests to http://localhost:8080, but we don't want
  272. HTML produced by Twisted to say 'http://localhost:8080', they should
  273. say 'https://www.example.com', so we do::
  274. request.setHost('www.example.com', 443, ssl=1)
  275. """
  276. class INonQueuedRequestFactory(Interface):
  277. """
  278. A factory of L{IRequest} objects that does not take a ``queued`` parameter.
  279. """
  280. def __call__(channel):
  281. """
  282. Create an L{IRequest} that is operating on the given channel. There
  283. must only be one L{IRequest} object processing at any given time on a
  284. channel.
  285. @param channel: A L{twisted.web.http.HTTPChannel} object.
  286. @type channel: L{twisted.web.http.HTTPChannel}
  287. @return: A request object.
  288. @rtype: L{IRequest}
  289. """
  290. class IAccessLogFormatter(Interface):
  291. """
  292. An object which can represent an HTTP request as a line of text for
  293. inclusion in an access log file.
  294. """
  295. def __call__(timestamp, request):
  296. """
  297. Generate a line for the access log.
  298. @param timestamp: The time at which the request was completed in the
  299. standard format for access logs.
  300. @type timestamp: L{unicode}
  301. @param request: The request object about which to log.
  302. @type request: L{twisted.web.server.Request}
  303. @return: One line describing the request without a trailing newline.
  304. @rtype: L{unicode}
  305. """
  306. class ICredentialFactory(Interface):
  307. """
  308. A credential factory defines a way to generate a particular kind of
  309. authentication challenge and a way to interpret the responses to these
  310. challenges. It creates
  311. L{ICredentials<twisted.cred.credentials.ICredentials>} providers from
  312. responses. These objects will be used with L{twisted.cred} to authenticate
  313. an authorize requests.
  314. """
  315. scheme = Attribute(
  316. "A L{str} giving the name of the authentication scheme with which "
  317. "this factory is associated. For example, C{'basic'} or C{'digest'}."
  318. )
  319. def getChallenge(request):
  320. """
  321. Generate a new challenge to be sent to a client.
  322. @type request: L{twisted.web.http.Request}
  323. @param request: The request the response to which this challenge will
  324. be included.
  325. @rtype: L{dict}
  326. @return: A mapping from L{str} challenge fields to associated L{str}
  327. values.
  328. """
  329. def decode(response, request):
  330. """
  331. Create a credentials object from the given response.
  332. @type response: L{str}
  333. @param response: scheme specific response string
  334. @type request: L{twisted.web.http.Request}
  335. @param request: The request being processed (from which the response
  336. was taken).
  337. @raise twisted.cred.error.LoginFailed: If the response is invalid.
  338. @rtype: L{twisted.cred.credentials.ICredentials} provider
  339. @return: The credentials represented by the given response.
  340. """
  341. class IBodyProducer(IPushProducer):
  342. """
  343. Objects which provide L{IBodyProducer} write bytes to an object which
  344. provides L{IConsumer<twisted.internet.interfaces.IConsumer>} by calling its
  345. C{write} method repeatedly.
  346. L{IBodyProducer} providers may start producing as soon as they have an
  347. L{IConsumer<twisted.internet.interfaces.IConsumer>} provider. That is, they
  348. should not wait for a C{resumeProducing} call to begin writing data.
  349. L{IConsumer.unregisterProducer<twisted.internet.interfaces.IConsumer.unregisterProducer>}
  350. must not be called. Instead, the
  351. L{Deferred<twisted.internet.defer.Deferred>} returned from C{startProducing}
  352. must be fired when all bytes have been written.
  353. L{IConsumer.write<twisted.internet.interfaces.IConsumer.write>} may
  354. synchronously invoke any of C{pauseProducing}, C{resumeProducing}, or
  355. C{stopProducing}. These methods must be implemented with this in mind.
  356. @since: 9.0
  357. """
  358. # Despite the restrictions above and the additional requirements of
  359. # stopProducing documented below, this interface still needs to be an
  360. # IPushProducer subclass. Providers of it will be passed to IConsumer
  361. # providers which only know about IPushProducer and IPullProducer, not
  362. # about this interface. This interface needs to remain close enough to one
  363. # of those interfaces for consumers to work with it.
  364. length = Attribute(
  365. """
  366. C{length} is a L{int} indicating how many bytes in total this
  367. L{IBodyProducer} will write to the consumer or L{UNKNOWN_LENGTH}
  368. if this is not known in advance.
  369. """
  370. )
  371. def startProducing(consumer):
  372. """
  373. Start producing to the given
  374. L{IConsumer<twisted.internet.interfaces.IConsumer>} provider.
  375. @return: A L{Deferred<twisted.internet.defer.Deferred>} which stops
  376. production of data when L{Deferred.cancel} is called, and which
  377. fires with L{None} when all bytes have been produced or with a
  378. L{Failure<twisted.python.failure.Failure>} if there is any problem
  379. before all bytes have been produced.
  380. """
  381. def stopProducing():
  382. """
  383. In addition to the standard behavior of
  384. L{IProducer.stopProducing<twisted.internet.interfaces.IProducer.stopProducing>}
  385. (stop producing data), make sure the
  386. L{Deferred<twisted.internet.defer.Deferred>} returned by
  387. C{startProducing} is never fired.
  388. """
  389. class IRenderable(Interface):
  390. """
  391. An L{IRenderable} is an object that may be rendered by the
  392. L{twisted.web.template} templating system.
  393. """
  394. def lookupRenderMethod(
  395. name: str,
  396. ) -> Callable[[Optional[IRequest], "Tag"], "Flattenable"]:
  397. """
  398. Look up and return the render method associated with the given name.
  399. @param name: The value of a render directive encountered in the
  400. document returned by a call to L{IRenderable.render}.
  401. @return: A two-argument callable which will be invoked with the request
  402. being responded to and the tag object on which the render directive
  403. was encountered.
  404. """
  405. def render(request: Optional[IRequest]) -> "Flattenable":
  406. """
  407. Get the document for this L{IRenderable}.
  408. @param request: The request in response to which this method is being
  409. invoked.
  410. @return: An object which can be flattened.
  411. """
  412. class ITemplateLoader(Interface):
  413. """
  414. A loader for templates; something usable as a value for
  415. L{twisted.web.template.Element}'s C{loader} attribute.
  416. """
  417. def load() -> List["Flattenable"]:
  418. """
  419. Load a template suitable for rendering.
  420. @return: a L{list} of flattenable objects, such as byte and unicode
  421. strings, L{twisted.web.template.Element}s and L{IRenderable} providers.
  422. """
  423. class IResponse(Interface):
  424. """
  425. An object representing an HTTP response received from an HTTP server.
  426. @since: 11.1
  427. """
  428. version = Attribute(
  429. "A three-tuple describing the protocol and protocol version "
  430. "of the response. The first element is of type L{str}, the second "
  431. "and third are of type L{int}. For example, C{(b'HTTP', 1, 1)}."
  432. )
  433. code = Attribute("The HTTP status code of this response, as a L{int}.")
  434. phrase = Attribute("The HTTP reason phrase of this response, as a L{str}.")
  435. headers = Attribute("The HTTP response L{Headers} of this response.")
  436. length = Attribute(
  437. "The L{int} number of bytes expected to be in the body of this "
  438. "response or L{UNKNOWN_LENGTH} if the server did not indicate how "
  439. "many bytes to expect. For I{HEAD} responses, this will be 0; if "
  440. "the response includes a I{Content-Length} header, it will be "
  441. "available in C{headers}."
  442. )
  443. request = Attribute("The L{IClientRequest} that resulted in this response.")
  444. previousResponse = Attribute(
  445. "The previous L{IResponse} from a redirect, or L{None} if there was no "
  446. "previous response. This can be used to walk the response or request "
  447. "history for redirections."
  448. )
  449. def deliverBody(protocol):
  450. """
  451. Register an L{IProtocol<twisted.internet.interfaces.IProtocol>} provider
  452. to receive the response body.
  453. The protocol will be connected to a transport which provides
  454. L{IPushProducer}. The protocol's C{connectionLost} method will be
  455. called with:
  456. - L{ResponseDone}, which indicates that all bytes from the response
  457. have been successfully delivered.
  458. - L{PotentialDataLoss}, which indicates that it cannot be determined
  459. if the entire response body has been delivered. This only occurs
  460. when making requests to HTTP servers which do not set
  461. I{Content-Length} or a I{Transfer-Encoding} in the response.
  462. - L{ResponseFailed}, which indicates that some bytes from the response
  463. were lost. The C{reasons} attribute of the exception may provide
  464. more specific indications as to why.
  465. """
  466. def setPreviousResponse(response):
  467. """
  468. Set the reference to the previous L{IResponse}.
  469. The value of the previous response can be read via
  470. L{IResponse.previousResponse}.
  471. """
  472. class _IRequestEncoder(Interface):
  473. """
  474. An object encoding data passed to L{IRequest.write}, for example for
  475. compression purpose.
  476. @since: 12.3
  477. """
  478. def encode(data):
  479. """
  480. Encode the data given and return the result.
  481. @param data: The content to encode.
  482. @type data: L{str}
  483. @return: The encoded data.
  484. @rtype: L{str}
  485. """
  486. def finish():
  487. """
  488. Callback called when the request is closing.
  489. @return: If necessary, the pending data accumulated from previous
  490. C{encode} calls.
  491. @rtype: L{str}
  492. """
  493. class _IRequestEncoderFactory(Interface):
  494. """
  495. A factory for returing L{_IRequestEncoder} instances.
  496. @since: 12.3
  497. """
  498. def encoderForRequest(request):
  499. """
  500. If applicable, returns a L{_IRequestEncoder} instance which will encode
  501. the request.
  502. """
  503. class IClientRequest(Interface):
  504. """
  505. An object representing an HTTP request to make to an HTTP server.
  506. @since: 13.1
  507. """
  508. method = Attribute(
  509. "The HTTP method for this request, as L{bytes}. For example: "
  510. "C{b'GET'}, C{b'HEAD'}, C{b'POST'}, etc."
  511. )
  512. absoluteURI = Attribute(
  513. "The absolute URI of the requested resource, as L{bytes}; or L{None} "
  514. "if the absolute URI cannot be determined."
  515. )
  516. headers = Attribute(
  517. "Headers to be sent to the server, as "
  518. "a L{twisted.web.http_headers.Headers} instance."
  519. )
  520. class IAgent(Interface):
  521. """
  522. An agent makes HTTP requests.
  523. The way in which requests are issued is left up to each implementation.
  524. Some may issue them directly to the server indicated by the net location
  525. portion of the request URL. Others may use a proxy specified by system
  526. configuration.
  527. Processing of responses is also left very widely specified. An
  528. implementation may perform no special handling of responses, or it may
  529. implement redirect following or content negotiation, it may implement a
  530. cookie store or automatically respond to authentication challenges. It may
  531. implement many other unforeseen behaviors as well.
  532. It is also intended that L{IAgent} implementations be composable. An
  533. implementation which provides cookie handling features should re-use an
  534. implementation that provides connection pooling and this combination could
  535. be used by an implementation which adds content negotiation functionality.
  536. Some implementations will be completely self-contained, such as those which
  537. actually perform the network operations to send and receive requests, but
  538. most or all other implementations should implement a small number of new
  539. features (perhaps one new feature) and delegate the rest of the
  540. request/response machinery to another implementation.
  541. This allows for great flexibility in the behavior an L{IAgent} will
  542. provide. For example, an L{IAgent} with web browser-like behavior could be
  543. obtained by combining a number of (hypothetical) implementations::
  544. baseAgent = Agent(reactor)
  545. decode = ContentDecoderAgent(baseAgent, [(b"gzip", GzipDecoder())])
  546. cookie = CookieAgent(decode, diskStore.cookie)
  547. authenticate = AuthenticateAgent(
  548. cookie, [diskStore.credentials, GtkAuthInterface()])
  549. cache = CacheAgent(authenticate, diskStore.cache)
  550. redirect = BrowserLikeRedirectAgent(cache, limit=10)
  551. doSomeRequests(cache)
  552. """
  553. def request(
  554. method: bytes,
  555. uri: bytes,
  556. headers: Optional[Headers] = None,
  557. bodyProducer: Optional[IBodyProducer] = None,
  558. ) -> Deferred[IResponse]:
  559. """
  560. Request the resource at the given location.
  561. @param method: The request method to use, such as C{b"GET"}, C{b"HEAD"},
  562. C{b"PUT"}, C{b"POST"}, etc.
  563. @param uri: The location of the resource to request. This should be an
  564. absolute URI but some implementations may support relative URIs
  565. (with absolute or relative paths). I{HTTP} and I{HTTPS} are the
  566. schemes most likely to be supported but others may be as well.
  567. @param headers: The headers to send with the request (or L{None} to
  568. send no extra headers). An implementation may add its own headers
  569. to this (for example for client identification or content
  570. negotiation).
  571. @param bodyProducer: An object which can generate bytes to make up the
  572. body of this request (for example, the properly encoded contents of
  573. a file for a file upload). Or, L{None} if the request is to have
  574. no body.
  575. @return: A L{Deferred} that fires with an L{IResponse} provider when
  576. the header of the response has been received (regardless of the
  577. response status code) or with a L{Failure} if there is any problem
  578. which prevents that response from being received (including
  579. problems that prevent the request from being sent).
  580. """
  581. class IPolicyForHTTPS(Interface):
  582. """
  583. An L{IPolicyForHTTPS} provides a policy for verifying the certificates of
  584. HTTPS connections, in the form of a L{client connection creator
  585. <twisted.internet.interfaces.IOpenSSLClientConnectionCreator>} per network
  586. location.
  587. @since: 14.0
  588. """
  589. def creatorForNetloc(hostname, port):
  590. """
  591. Create a L{client connection creator
  592. <twisted.internet.interfaces.IOpenSSLClientConnectionCreator>}
  593. appropriate for the given URL "netloc"; i.e. hostname and port number
  594. pair.
  595. @param hostname: The name of the requested remote host.
  596. @type hostname: L{bytes}
  597. @param port: The number of the requested remote port.
  598. @type port: L{int}
  599. @return: A client connection creator expressing the security
  600. requirements for the given remote host.
  601. @rtype: L{client connection creator
  602. <twisted.internet.interfaces.IOpenSSLClientConnectionCreator>}
  603. """
  604. class IAgentEndpointFactory(Interface):
  605. """
  606. An L{IAgentEndpointFactory} provides a way of constructing an endpoint
  607. used for outgoing Agent requests. This is useful in the case of needing to
  608. proxy outgoing connections, or to otherwise vary the transport used.
  609. @since: 15.0
  610. """
  611. def endpointForURI(uri):
  612. """
  613. Construct and return an L{IStreamClientEndpoint} for the outgoing
  614. request's connection.
  615. @param uri: The URI of the request.
  616. @type uri: L{twisted.web.client.URI}
  617. @return: An endpoint which will have its C{connect} method called to
  618. issue the request.
  619. @rtype: an L{IStreamClientEndpoint} provider
  620. @raises twisted.internet.error.SchemeNotSupported: If the given
  621. URI's scheme cannot be handled by this factory.
  622. """
  623. UNKNOWN_LENGTH = "twisted.web.iweb.UNKNOWN_LENGTH"
  624. __all__ = [
  625. "IUsernameDigestHash",
  626. "ICredentialFactory",
  627. "IRequest",
  628. "IBodyProducer",
  629. "IRenderable",
  630. "IResponse",
  631. "_IRequestEncoder",
  632. "_IRequestEncoderFactory",
  633. "IClientRequest",
  634. "UNKNOWN_LENGTH",
  635. ]