【问题标题】:Django passthrough API request to hide credentialsDjango passthrough API 请求隐藏凭据
【发布时间】:2021-04-04 04:54:11
【问题描述】:

我需要向 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的数据。

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

【问题讨论】:

  • 你应该检查这个。 stackoverflow.com/q/52396510/9310776
  • 谢谢。我检查了一下。它需要一个 DRF mixin。安装 DRF 只是为了使用 IsAuthenticated Mixin 感觉有点过分。并且还提出了一个问题——@login_required 和 IsAuthenticated 有什么区别?

标签: python django


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2018-04-21
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-29
    • 1970-01-01
    • 2020-03-25
    相关资源
    最近更新 更多