暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Python发起Http请求你不知道的事

Python都知道 2022-10-03
510

前言

哈喽,大家好,我是知道!相信很多人都是用Python开发或者做小工具时经常会做进行Http请求,不论是接口测试,爬虫调用,都会用到。今天知道就带大家盘一盘几种常用的http请求库。

requests库

在python中,发送http大多使用最多最靓眼的那个崽是requests,因为他使用起来非常方便,代码非常简洁,爬虫常用, 而且封装起来后使用更为简单。

在不借助其他第三方库的情况下,requests 只能发送同步请求。

下面是几种常用的请求方式:

# 导入requests包
import requests

# get 请求
requests.get(url, params)

# post 请求
requests.post(url, data)
# 文件上传
upload_files = {'file': open('file.xls''rb')}
requests.post(url, file=upload_files)  
# 设置header
headers = {'User-Agent''Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36'}
requests.post(url, headers=headers)
# 设置cookie
cookies = {'token''123'}
requests.post(url, cookies=cookies)

常用请求参数:

  • url: url地址
  • params:url参数,字典格式,使用此参数会自动拼接到url地址中
  • data: 请求body中的数据,字典或字符串格式
  • headers: 请求头信息,字典格式
  • cookies: 字典格式,可以通过携带cookies绕过登录
  • files: 字典格式,用于混合表单(form-data)中上传文件
  • timeout: 超时时间(防止请求一直没有响应,最长等待时间),数字格式,单位为秒

常用返回参数:

  • res.status_code: HTTP状态码,如200
  • res.reason: HTTP状态码含义,如 OK
  • res.headers: HTTP响应头信息
  • res.text:获取返回结果,按req.encoding解码
  • res.encoding: 获取当前使用的编码格式
  • res.apparent_encoding:文本真正的编码格式
  • res.cookies: 响应的cookieJar对象,可以通过req.cookies.get(key)来获取响应cookies中某个key对应的值
  • res.json(): (注意,有括号),响应的json对象(字典)格式,慎用!如果响应文本不是合法的json文本,或报错

aiohttp库

在不借助其他第三方库的情况下,aiohttp只能发送异步请求。

目前支持异步请求的方式有 async/await+asyncio+requests 组合构成,也可以使用aiohttp.aiohttp是一个为Python提供异步HTTP客户端、服务端编程,基于asyncio的异步库。aiohttp 同样是可以设置请求方式,请求头,cookie,代理,上传文件等功能的。

# post 请求
payload = {
        "data""hello world"
    }
async with aiohttp.ClientSession() as session:
 async with session.post(url, json=payload) as resp:
  print(resp.status)
# get请求
# 创建使用session
async with aiohttp.ClientSession() as session:
 async with session.get(url) as resp:
  print(resp.status)
  res = await resp.text()
  return res

# 上传文件
files = {'file': open('report.xls''rb')}
async with aiohttp.ClientSession() as sess:
 async with sess.post(url, data=files) as resp:
  print(resp.status)
  print(await resp.text())

# 设置header, cookie
headers = {'User-Agent''Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36'}
cookies = {'token''123'}
async with aiohttp.ClientSession(headers=headers, cookies=cookies) as session:
 async with session.get(url) as resp:
  print(resp.status)
  res = await resp.text()
  return res

异步的请求,对接口返回数据在其他地方没有太强的依赖,异步的作用更多是用于提高效率,节省同步等待时间。

httpx库

在不借助其他第三方库的情况下,httpx既能发送同步请求,又能发送异步请求。

httpx是Python新一代的网络请求库,它包含以下特点:

  • 基于Python3的功能齐全的http请求模块
  • 既能发送同步请求,也能发送异步请求
  • 支持HTTP/1.1和HTTP/2
  • 能够直接向WSGI应用程序或者ASGI应用程序发送请求
  • 安装 httpx需要Python3.6+(使用异步请求需要Python3.8+)

httpx是Python新一代的网络请求库, 功能和requests基本都一致,但是requests在没有第三方库的支持下只能发同步请求, 但是httpx不仅可以发同步请求,还可以异步,这个是比requests要好的。因为和requests差不多,那么requests能支持设置的,那么httpx也同样可以支持

安装:

pip install httpx

下面是几种常用的请求方式:

#导入httpx包
import httpx

data = {
    'name''zhangsan',
    'age'25
}

# get请求
httpx.get(url,params=data)
# post请求
httpx.post(url, data=data)

# 设置header,cookie,timeout
headers = {'User-Agent''Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36'}
cookies = {'token''123'}
httpx.get(url, headers=headers, cookies=cookies, timeout=10.0)

# 使用client发送(同步)请求
with httpx.Client() as client:
   response = client.get(url)

在同步请求下,httpx与requests使用方法基本相同。

异步操作需要使用async/await语句来进行异步操作,使用异步client比使用多线程发送请求更加高效,更能体现明显的性能优势。

import asyncio
import httpx

async def main():
    # 异步请求AsyncClient
    async with httpx.AsyncClient() as client:
        response = await client.get(url)
        print(response)

if __name__ == '__main__':
    # python3.7+ 支持写法
    # asyncio.run(main())
    # python3.6及以下版本写法
    loop = asyncio.get_event_loop()
    result = loop.run_until_complete(asyncio.gather(main()))
    loop.close()

同步请求使用httpx.client(), 异步请求使用httpx.AsyncClient(), 然后其他的一些基本用法都大体相似。可以说,如果你对requests熟练,那么对于aiohttp以及httpx也是很快就能上手理解的。

总结

今天主要带大家看了一下python发http请求的第三方库

  • requests
  • aiohttp
  • httpx

其中各有优劣势,具体使用哪种还要根据场景和环境来去选择。

感谢您的观看,如果想了解更多可以关注本公众号,我们会继续分享更多有趣的知识。

PSPython都知道技术交流群(技术交流、摸鱼、白嫖课程为主)又不定时开放了,感兴趣的朋友,可以在下方公号内回复:666,即可进入。


老规矩,道友们还记得么,右下角的 “在看” 点一下如果感觉文章内容不错的话,记得分享朋友圈让更多的人知道!



文章转载自Python都知道,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论