用于隐藏凭据的 Django 直通 API 请求

时间:2021-04-04 04:54:11

标签: python django

我需要向 b.com/rest/foo 发出请求以获取我的应用程序的 json 数据。我想这样做是为了保护凭据,而不是在每个页面上都公开它们。

我发现 Consume an API in Django REST, server side, and serve it ,client side, in Angularhttps://stackoverflow.com/a/65672890/2193381 上的相应答案是一个很好的起点。

我创建了一个本地 url 来复制外部服务器将返回的数据,然后尝试了以下操作

import requests
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.cache import never_cache


@never_cache
@login_required
def fakedata(request, item):
    return JsonResponse({'item': item})


def getdata(request, item):
    url = f"http://localhost:8080/rest/{item}"

    username = os.getenv('SITE_USERNAME', None)
    password = os.getenv('SITE_PASSWORD', None)

    userpass = dict(username=username, password=password)

    data = requests.get(
        url,
        auth=requests.auth.HTTPBasicAuth(**userpass),
    )

    if data is not None and data.status_code == 200:
        try:
            return JsonResponse(data.json(), safe=False)
        except ValueError:
            print("!JSON")
            return JsonResponse({})

    print("!data")
    return JsonResponse({})
urlpatterns = [
    path('rest/<str:item>', fakedata),
    path('foo/<str:item>', getdata),
]

当我测试它

python manage.py runserver 8080

并调用 http://localhost:8080/foo/a,我将返回登录页面的 html,而不是我期望的来自 http://localhost:8080/rest/a 的数据。

我需要进行哪些更改才能使其正常工作?

1 个答案:

答案 0 :(得分:0)

我刚刚浏览了 Django 文档,发现 this 有用且有效。

您可以首先使用 authenticate() 方法对用户进行身份验证,然后使用 request 登录并通过传递 fakedata() 调用您的 request 函数:

from django.contrib.auth import authenticate, login
user = authenticate(request, **userpass)
if user is not None:
    login(request, user)
    data = fakedata(request, item)
else:
    pass