我正在創建一個 DRF 專案(僅限 API),其中登錄用戶可以指定他想要接收多少人隨機生成的憑據。
這是我的問題:我想從外部 API ( https://randomuser.me/api )獲取這些憑據。本網站會根據 url 的“結果”引數中指定的數量生成隨機用戶資料。前任。https://randomuser.me/api/?results=40
我的問題是:
我怎樣才能得到這些資料?我知道 JavaScript fetch() 方法可能很有用,但我實際上不知道如何將它與 Django Rest Framework 連接,然后對其進行操作。我想在用戶發送 POST 請求(僅指定要生成的用戶數)后向用戶顯示資料,并將結果保存在資料庫中,以便他稍后可以訪問它們(通過 GET 請求)。
如果您有任何想法或提示,我將不勝感激。
謝謝!
uj5u.com熱心網友回復:
以下是在 Django Rest Framework API 視圖中進行 API 呼叫的方法:
由于您想將外部 API 請求存盤在資料庫中。這是存盤用戶結果的模型示例。
模型.py
from django.conf import settings
class Credential(models.Models):
""" A user can have many generated credentials """
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
value = models.CharField()
# Here we override the save method to avoid that each user request create new credentials on top of the existing one
def __str__(self):
return f"{self.user.username} - {self.value}"
視圖.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
# Assume that you have installed requests: pip install requests
import requests
import json
class GenerateCredential(APIVIew):
""" This view make and external api call, save the result and return
the data generated as json object """
# Only authenticated user can make request on this view
permission_classes = (IsAuthenticated, )
def get(self, request, format=None):
# The url is like https://localhost:8000/api/?results=40
results = self.request.query_params.get('type')
response = {}
# Make an external api request ( use auth if authentication is required for the external API)
r = requests.get('https://randomuser.me/api/?results=40', auth=('user', 'pass'))
r_status = r.status_code
# If it is a success
if r_status = 200:
# convert the json result to python object
data = json.loads(r.json)
# Loop through the credentials and save them
# But it is good to avoid that each user request create new
# credentials on top of the existing one
# ( you can retrieve and delete the old one and save the news credentials )
for c in data:
credential = Credential(user = self.request.user, value=c)
credential.save()
response['status'] = 200
response['message'] = 'success'
response['credentials'] = data
else:
response['status'] = r.status_code
response['message'] = 'error'
response['credentials'] = {}
return Response(response)
class UserCredentials(APIView):
"""This view return the current authenticated user credentials """
permission_classes = (IsAuthenticated, )
def get(self, request, format=None):
current_user = self.request.user
credentials = Credential.objects.filter(user__id=current_user)
return Response(credentials)
注意:這些視圖假定user發出請求的人已通過身份驗證,更多資訊請點擊此處。因為我們需要用戶將檢索到的憑據保存在資料庫中。
網址.py
path('api/get_user_credentials/', views.UserCredentials.as_view()),
path('api/generate_credentials/', views.GenerateCredentials.as_view()),
.js
const url = "http://localhost:8000/api/generate_credentials/";
# const url = "http://localhost:8000/api/get_user_credentials/";
fetch(url)
.then((resp) => resp.json())
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log(error);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314022.html
