我需要向b.com/rest/foo发出请求,以便为我的应用程序获取json数据。我想这样做是为了保护凭据,而不是在每个页面上公开它们。
我发现https://stackoverflow.com/a/65672890/2193381上的Consume an API in Django REST, server side, and serve it ,client side, in Angular和相应的答案是一个很好的起点。
我创建了一个本地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的数据。
我需要做哪些更改才能使其正常工作?
发布于 2021-04-05 19:31:46
我刚刚浏览了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:
passhttps://stackoverflow.com/questions/66938118
复制相似问题