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

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

一、同步版(pip install requests)

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)

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())

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

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()

相关推荐

  1. Okhttp 发送https请求,忽略ssl认证

    2024-05-04 18:04:02       31 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-04 18:04:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-04 18:04:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-05-04 18:04:02       87 阅读
  4. Python语言-面向对象

    2024-05-04 18:04:02       96 阅读

热门阅读

  1. [UUCTF 2022 新生赛]ezsql

    2024-05-04 18:04:02       31 阅读
  2. C#装箱拆箱是怎么回事

    2024-05-04 18:04:02       32 阅读
  3. Linux如何查看JDK的安装路径

    2024-05-04 18:04:02       28 阅读
  4. 【代码随想录】day49

    2024-05-04 18:04:02       36 阅读
  5. C++ 仿函数

    2024-05-04 18:04:02       33 阅读
  6. 切比雪夫滤波器

    2024-05-04 18:04:02       174 阅读
  7. 谈谈TCP Socket中写数据的函数---write、send 、sendv

    2024-05-04 18:04:02       33 阅读
  8. Rust : 声明宏在不同K线bar类型中的应用

    2024-05-04 18:04:02       37 阅读
  9. FileOutputStream

    2024-05-04 18:04:02       34 阅读