http_async_fetcher¶
Asynchronous HTTP fetching utilities with concurrent request management.
This module provides http_fetch_url() for fetching a single URL asynchronously and HttpAsyncFetcher, a class that manages concurrent HTTP fetches with automatic cleanup, work result tracking, and result iteration.
HttpAsyncFetcher
¶
Manages concurrent asynchronous HTTP fetches with work result tracking.
Provides a context manager that enqueues URLs for async fetching, tracks pending requests, and yields results as they complete. Uses AsyncManager for concurrent execution and fin_wrap for automatic cleanup.
Example
import functools
import http.server
import os
import threading
from py_misc_utils import http_async_fetcher as haf
def serve():
class H(http.server.BaseHTTPRequestHandler):
def do_GET(self):
body = os.path.basename(self.path).encode() + b'-body'
self.send_response(200)
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
srv = http.server.ThreadingHTTPServer(('127.0.0.1', 0), H)
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv
srv = serve()
try:
port = srv.server_address[1]
with haf.HttpAsyncFetcher(num_workers=2) as fetcher:
fetcher.enqueue(f'http://127.0.0.1:{port}/one.bin')
results = dict(fetcher.iter_results())
assert results == {f'http://127.0.0.1:{port}/one.bin': b'one.bin-body'}
finally:
srv.shutdown()
srv.server_close()
Source code in py_misc_utils/http_async_fetcher.py
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 | |
start()
¶
Initialize the async manager and set the working path.
Creates a temp directory if no path was specified, then starts the AsyncManager with the configured number of workers.
Source code in py_misc_utils/http_async_fetcher.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 | |
shutdown()
¶
Shut down the fetcher and clean up resources.
Closes the async manager, clears the path and pending set.
Source code in py_misc_utils/http_async_fetcher.py
197 198 199 200 201 202 203 204 205 206 | |
enqueue(*urls)
¶
Enqueue URLs for asynchronous fetching.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*urls
|
Variable number of URL strings to fetch - empty (falsy) URLs are skipped. |
()
|
Returns:
| Type | Description |
|---|---|
|
A dict mapping each enqueued URL to its work result hash. |
Source code in py_misc_utils/http_async_fetcher.py
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | |
wait(url)
¶
Wait for a specific URL's fetch to complete and return its result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
The URL string to wait for. |
required |
Returns:
| Type | Description |
|---|---|
|
The fetched work result data. |
Raises:
| Type | Description |
|---|---|
Exception
|
The error which made the fetch fail - if it failed. |
AssertionError
|
If the URL is not in the pending set (i.e. already waited for or never enqueued). |
Source code in py_misc_utils/http_async_fetcher.py
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 | |
iter_results(max_results=None, block=True, timeout=None)
¶
Iterate over completed fetch results as they become available.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_results
|
Maximum number of results to yield. Defaults to None (all). |
None
|
|
block
|
Whether to block waiting for results. Defaults to True. |
True
|
|
timeout
|
Timeout in seconds for blocking fetch. Defaults to None. |
None
|
Yields:
| Type | Description |
|---|---|
|
Tuples of (url, data) for each completed fetch - where data holds |
|
|
the fetched content, or the error object if the fetch failed. |
Source code in py_misc_utils/http_async_fetcher.py
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 | |
http_fetch_url(url, context, path=None, http_args=None)
async
¶
Asynchronously fetch a URL and save its content to a work result file.
Uses an httpx AsyncClient obtained from the provided context to GET the URL, writes the response content to a work result path, and handles errors by writing them to the work result system.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
The URL to fetch. |
required | |
context
|
AsyncContext providing an httpx.AsyncClient through its get() method. Mandatory - the HttpAsyncFetcher class supplies it automatically, using the context owned by each worker process. |
required | |
path
|
Optional base path for work results. Defaults to None - which fails, as a work results folder is required. |
None
|
|
http_args
|
Optional keyword arguments for the httpx GET request (default: no extra arguments). |
None
|
Returns:
| Type | Description |
|---|---|
|
The work result file path where the content was saved. |
Example
import asyncio
import http.server
import os
import tempfile
import threading
import httpx
from py_misc_utils import http_async_fetcher as haf
from py_misc_utils import work_results as wres
class NotFoundHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(404)
self.send_header('Content-Length', '0')
self.end_headers()
def log_message(self, *args):
pass
class ClientCtx:
async def get(self, name, ctor):
return httpx.AsyncClient()
srv = http.server.ThreadingHTTPServer(('127.0.0.1', 0), NotFoundHandler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
url = 'http://127.0.0.1:{}/nope'.format(srv.server_address[1])
wpath = asyncio.run(
haf.http_fetch_url(url, context=ClientCtx(), path=tempfile.mkdtemp(),
http_args={}))
err = wres.load_work(wpath=wpath)
assert err.is_instance(httpx.HTTPStatusError)
srv.shutdown()
srv.server_close()
Source code in py_misc_utils/http_async_fetcher.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | |