aiohttp封装http请求

  1. import aiohttp
  2. import json
  3. from sanic.response import stream
  4. async def post(url, data, headers=None):
  5. async with aiohttp.ClientSession(headers=headers) as session:
  6. result = await session.post(url, data=data)
  7. return await result.json()
  8. async def post_text_plain(url, data, headers=None):
  9. async with aiohttp.ClientSession(headers=headers) as session:
  10. result = await session.post(url, data=data)
  11. return await result.text()
  12. async def get(url, headers=None, **kwargs):
  13. async with aiohttp.ClientSession(headers=headers) as session:
  14. result = await session.get(url, data=kwargs)
  15. return await result.json()
  16. async def put(url, data, headers=None):
  17. async with aiohttp.ClientSession(headers=headers) as session:
  18. result = await session.put(url, data=data)
  19. return await result.json()



#python脚本代码中调用:

import asyncio
loop = asyncio.get_event_loop()
result = loop.run_until_complete(post(url,json.dumps(data),headers={"Content-Type": "application/json"}))
loop.close()

你可能感兴趣的:(aiohttp封装http请求)