我完全是 Django 的初学者(来自 Node/Express 背景)。我需要调用使用基本授权的 API。
为了发出请求,我正在使用请求模块,但我不知道在哪里传递身份验证 header 。在 Axios 中,我通常设置默认 header ,如下所示:
import axios from 'axios'
const token = `Basic ${Buffer.from(`${process.env.API_USERNAME}:${process.env.API_PASSWORD}`).toString('base64')}`;
axios.defaults.baseURL = process.env.API_URL;
axios.defaults.headers.common['Authorization'] = token;
我在 Django 中的服务:
from base64 import b64encode
import requests
import environ
environ.Env.read_env()
endpoint = 'some url'
credentials = f"{env('API_USERNAME')}:{env('API_PASSWORD')}"
encodedCredentials = str(b64encode(credentials.encode("utf-8")), "utf-8")
auth = f'"Authorization": "Basic {encodedCredentials}"'
def get_api_data():
return requests.get(endpoint).json()
我应该如何传递 header ?
最佳答案
如果 api 使用 token 身份验证,您可以使用 headers
使用请求 header 传递 token 的参数:
return requests.get(endpoint, headers={"Authorization": f"Basic {encodedCredentials}"}).json()
或者您可以直接使用 auth
传递登录名和密码论据:
return requests.get(endpoint, auth=("login", "password")).json()
关于python - Django 如何在请求中传递基本授权 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60137620/