A blocking HTTP client. This interface is provided to make it easier to share code between synchronous and asynchronous applications. Applications that are running an `.IOLoop` must use `AsyncHTTPClient` instead. Typical usage looks like this:: http_client = httpclient.HTT
| 57 | |
| 58 | |
| 59 | class HTTPClient: |
| 60 | """A blocking HTTP client. |
| 61 | |
| 62 | This interface is provided to make it easier to share code between |
| 63 | synchronous and asynchronous applications. Applications that are |
| 64 | running an `.IOLoop` must use `AsyncHTTPClient` instead. |
| 65 | |
| 66 | Typical usage looks like this:: |
| 67 | |
| 68 | http_client = httpclient.HTTPClient() |
| 69 | try: |
| 70 | response = http_client.fetch("http://www.google.com/") |
| 71 | print(response.body) |
| 72 | except httpclient.HTTPError as e: |
| 73 | # HTTPError is raised for non-200 responses; the response |
| 74 | # can be found in e.response. |
| 75 | print("Error: " + str(e)) |
| 76 | except Exception as e: |
| 77 | # Other errors are possible, such as IOError. |
| 78 | print("Error: " + str(e)) |
| 79 | http_client.close() |
| 80 | |
| 81 | .. versionchanged:: 5.0 |
| 82 | |
| 83 | Due to limitations in `asyncio`, it is no longer possible to |
| 84 | use the synchronous ``HTTPClient`` while an `.IOLoop` is running. |
| 85 | Use `AsyncHTTPClient` instead. |
| 86 | |
| 87 | """ |
| 88 | |
| 89 | def __init__( |
| 90 | self, |
| 91 | async_client_class: "Optional[Type[AsyncHTTPClient]]" = None, |
| 92 | **kwargs: Any, |
| 93 | ) -> None: |
| 94 | # Initialize self._closed at the beginning of the constructor |
| 95 | # so that an exception raised here doesn't lead to confusing |
| 96 | # failures in __del__. |
| 97 | self._closed = True |
| 98 | self._io_loop = IOLoop(make_current=False) |
| 99 | if async_client_class is None: |
| 100 | async_client_class = AsyncHTTPClient |
| 101 | |
| 102 | # Create the client while our IOLoop is "current", without |
| 103 | # clobbering the thread's real current IOLoop (if any). |
| 104 | async def make_client() -> "AsyncHTTPClient": |
| 105 | await gen.sleep(0) |
| 106 | assert async_client_class is not None |
| 107 | return async_client_class(**kwargs) |
| 108 | |
| 109 | self._async_client = self._io_loop.run_sync(make_client) |
| 110 | self._closed = False |
| 111 | |
| 112 | def __del__(self) -> None: |
| 113 | self.close() |
| 114 | |
| 115 | def close(self) -> None: |
| 116 | """Closes the HTTPClient, freeing any resources used.""" |
no outgoing calls