An non-blocking HTTP client. Example usage:: async def f(): http_client = AsyncHTTPClient() try: response = await http_client.fetch("http://www.google.com") except Exception as e: print("Error: %s" % e) els
| 138 | |
| 139 | |
| 140 | class AsyncHTTPClient(Configurable): |
| 141 | """An non-blocking HTTP client. |
| 142 | |
| 143 | Example usage:: |
| 144 | |
| 145 | async def f(): |
| 146 | http_client = AsyncHTTPClient() |
| 147 | try: |
| 148 | response = await http_client.fetch("http://www.google.com") |
| 149 | except Exception as e: |
| 150 | print("Error: %s" % e) |
| 151 | else: |
| 152 | print(response.body) |
| 153 | |
| 154 | The constructor for this class is magic in several respects: It |
| 155 | actually creates an instance of an implementation-specific |
| 156 | subclass, and instances are reused as a kind of pseudo-singleton |
| 157 | (one per `.IOLoop`). The keyword argument ``force_instance=True`` |
| 158 | can be used to suppress this singleton behavior. Unless |
| 159 | ``force_instance=True`` is used, no arguments should be passed to |
| 160 | the `AsyncHTTPClient` constructor. The implementation subclass as |
| 161 | well as arguments to its constructor can be set with the static |
| 162 | method `configure()` |
| 163 | |
| 164 | All `AsyncHTTPClient` implementations support a ``defaults`` |
| 165 | keyword argument, which can be used to set default values for |
| 166 | `HTTPRequest` attributes. For example:: |
| 167 | |
| 168 | AsyncHTTPClient.configure( |
| 169 | None, defaults=dict(user_agent="MyUserAgent")) |
| 170 | # or with force_instance: |
| 171 | client = AsyncHTTPClient(force_instance=True, |
| 172 | defaults=dict(user_agent="MyUserAgent")) |
| 173 | |
| 174 | .. versionchanged:: 5.0 |
| 175 | The ``io_loop`` argument (deprecated since version 4.1) has been removed. |
| 176 | |
| 177 | """ |
| 178 | |
| 179 | _instance_cache = None # type: Dict[IOLoop, AsyncHTTPClient] |
| 180 | |
| 181 | @classmethod |
| 182 | def configurable_base(cls) -> Type[Configurable]: |
| 183 | return AsyncHTTPClient |
| 184 | |
| 185 | @classmethod |
| 186 | def configurable_default(cls) -> Type[Configurable]: |
| 187 | from tornado.simple_httpclient import SimpleAsyncHTTPClient |
| 188 | |
| 189 | return SimpleAsyncHTTPClient |
| 190 | |
| 191 | @classmethod |
| 192 | def _async_clients(cls) -> Dict[IOLoop, "AsyncHTTPClient"]: |
| 193 | attr_name = "_async_client_dict_" + cls.__name__ |
| 194 | if not hasattr(cls, attr_name): |
| 195 | setattr(cls, attr_name, weakref.WeakKeyDictionary()) |
| 196 | return getattr(cls, attr_name) |
| 197 |
no outgoing calls