()
| 6 | |
| 7 | |
| 8 | async def main() -> None: |
| 9 | # Set default headers on the client. They are sent on every request. |
| 10 | http_client = ImpitHttpClient(headers={'X-Api-Key': 'secret'}) |
| 11 | |
| 12 | crawler = HttpCrawler(http_client=http_client, max_requests_per_crawl=10) |
| 13 | |
| 14 | @crawler.router.default_handler |
| 15 | async def request_handler(context: HttpCrawlingContext) -> None: |
| 16 | # `httpbin.org/headers` echoes the received request headers back. |
| 17 | response = (await context.http_response.read()).decode() |
| 18 | context.log.info(f'{context.request.unique_key}: {response}') |
| 19 | |
| 20 | # Add a header for this request only. It merges with the client defaults. |
| 21 | request = Request.from_url( |
| 22 | 'https://httpbin.org/headers', |
| 23 | headers=HttpHeaders({'Accept': 'application/json'}), |
| 24 | # Both requests target the same URL. Without a distinct `unique_key`, |
| 25 | # deduplication would drop this one. |
| 26 | unique_key='set-headers-example', |
| 27 | ) |
| 28 | |
| 29 | await crawler.run(['https://httpbin.org/headers', request]) |
| 30 | |
| 31 | |
| 32 | if __name__ == '__main__': |
no test coverage detected