Python发送digest认证的请求:requests.auth.HTTPDigestAuth/httpx.DigestAuth

近日在做摄像头接口的调试,需要用到Digest认证,经过试验,代码如下:

一、同步版(pip install requests)

python 复制代码
import requests
from requests.auth import HTTPDigestAuth

host = 'https://192.168.0.2'
path = '/api/xxx'
path2 = '/another/api'

AUTH = ('username', 'password')
r = requests.get(host+path, verify=False, auth=HTTPDigestAuth(*AUTH))
print(r.status_code)
print(r.text)

payload = {'a': 1}
r2 = requests.put(host+path2, verify=False, auth=HTTPDigestAuth(*AUTH), json=payload)
print(r2.status_code)
print(r2.json())

二、异步协程版(pip install httpx)

python 复制代码
import asyncio
from httpx import AsyncClient, DigestAuth

host = 'https://192.168.0.2'
path = '/api/xxx'
path2 = '/another/api'

AUTH = ('username', 'password')


async def main():
    async with AsyncClient(base_url=host, verify=False, auth=DigestAuth(*AUTH)):
        r = await client.get(path)
        payload = {'a': 1}
        r2 = await client.put(path2, json=payload)
    print(r.status_code)
    print(r.text)

    print(r2.status_code)
    print(r2.json())


if __name__ == '__main__':
    asyncio.run(main())

封装成工具类之后的代码如下

python 复制代码
import os

import requests
from httpx import AsyncClient, DigestAuth

AUTH = (os.environ["API_USER"], os.environ["API_PASS"])


class HttpClient:
    PATH_GET = "/get-sth"
    PATH_PUT = "/put"

    @staticmethod
    def sync_request(method: str, host: str, path: str, **kw) -> requests.Response:
        url = host.rstrip("/") + path
        return requests.request(
            method, url, verify=False, auth=requests.auth.HTTPDigestAuth(*AUTH), **kw
        )

    @classmethod
    def sync_get(cls, host: str, params=None, path: str | None = None) -> dict:
        if path is None:
            path = cls.PATH_GET
        r = cls.sync_request("GET", host, path, params=params)
        r.raise_for_status()
        return r.json()

    @classmethod
    def sync_put(cls, payload: dict, host: str, path: str | None = None) -> dict:
        if path is None:
            path = cls.PATH_PUT
        r = cls.sync_request("PUT", host, path, json=payload)
        r.raise_for_status()
        return r.json()

    @staticmethod
    def async_client(host: str) -> AsyncClient:
        return AsyncClient(base_url=host, verify=False, auth=DigestAuth(*AUTH))

    @classmethod
    async def get(cls, host: str, params=None, path: str | None = None) -> dict:
        async with cls.async_client(host) as client:
            r = await client.get(path or cls.PATH_GET, params=params)
            return r.json()

    @classmethod
    async def put(cls, payload: dict, host: str, path: str | None = None) -> dict:
        async with cls.async_client(host) as client:
            r = await client.put(path or cls.PATH_PUT, json=payload)
            return r.json()
相关推荐
秃头佛爷9 分钟前
Python学习大纲总结及注意事项
开发语言·python·学习
深度学习lover1 小时前
<项目代码>YOLOv8 苹果腐烂识别<目标检测>
人工智能·python·yolo·目标检测·计算机视觉·苹果腐烂识别
API快乐传递者2 小时前
淘宝反爬虫机制的主要手段有哪些?
爬虫·python
阡之尘埃4 小时前
Python数据分析案例61——信贷风控评分卡模型(A卡)(scorecardpy 全面解析)
人工智能·python·机器学习·数据分析·智能风控·信贷风控
丕羽7 小时前
【Pytorch】基本语法
人工智能·pytorch·python
bryant_meng8 小时前
【python】Distribution
开发语言·python·分布函数·常用分布
m0_594526309 小时前
Python批量合并多个PDF
java·python·pdf
工业互联网专业9 小时前
Python毕业设计选题:基于Hadoop的租房数据分析系统的设计与实现
vue.js·hadoop·python·flask·毕业设计·源码·课程设计
钱钱钱端9 小时前
【压力测试】如何确定系统最大并发用户数?
自动化测试·软件测试·python·职场和发展·压力测试·postman
慕卿扬9 小时前
基于python的机器学习(二)—— 使用Scikit-learn库
笔记·python·学习·机器学习·scikit-learn