Django如何在请求中传递基本授权标头?

问题描述 投票:1回答:1

我完全是Django的初学者(来自Node / Express背景)。我需要调用使用基本授权的API。

要发出请求,我正在使用请求模块,但我不知道将身份验证标头传递到哪里。在Axios中,我通常会像这样设置默认标题:

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

我应该如何传递标题?

python django basic-authentication
1个回答
0
投票

您可以使用headers参数:

headers
© www.soinside.com 2019 - 2024. All rights reserved.