httpbase.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import json
  2. import httpx
  3. class HttpBase:
  4. @staticmethod
  5. async def http_stream(url, data, headers, timeout=300):
  6. async with httpx.AsyncClient(timeout=timeout) as client:
  7. async with client.stream("POST", url, json=data, headers=headers) as response:
  8. if response.status_code == 200:
  9. try:
  10. async for answer in response.aiter_text():
  11. yield answer
  12. except GeneratorExit as e:
  13. print(e)
  14. return
  15. else:
  16. yield f"Error: {response.status_code}"
  17. @staticmethod
  18. async def http_post(url, data, headers, timeout=300):
  19. async with httpx.AsyncClient(timeout=timeout) as client:
  20. response = await client.post(url, json=data, headers=headers)
  21. return response
  22. @staticmethod
  23. async def http_get(url, params, headers, timeout=300):
  24. async with httpx.AsyncClient(timeout=timeout) as client:
  25. response = await client.get(url, params=params, headers=headers)
  26. return response
  27. @staticmethod
  28. async def get_headers(token):
  29. return {
  30. 'Content-Type': 'application/json',
  31. 'Authorization': f'Bearer {token}'
  32. }