【问题标题】:How to get data from external API to Django Rest Framework如何从外部 API 获取数据到 Django Rest Framework
【发布时间】:2021-10-10 08:11:36
【问题描述】:

我正在创建一个 DRF 项目(仅限 API),其中登录用户可以指定他希望接收多少人随机生成的凭据。

这是我的问题: 我想从外部 API (https://randomuser.me/api) 获取这些凭据。 该网站会生成 url 的“结果”参数中指定数量的随机用户数据。 前任。 https://randomuser.me/api/?results=40

我的问题是:

我什至如何获得这些数据?我知道 JavaScript fetch() 方法可能很有用,但我实际上并不知道如何将它与 Django Rest Framework 连接,然后对其进行操作。 我想在用户发送 POST 请求后向用户显示数据(仅指定要生成的用户数)并将结果保存在数据库中,以便他稍后可以访问它们(通过 GET 请求)。

如果您有任何想法或提示,我将不胜感激。

谢谢!

【问题讨论】:

    标签: django api rest django-rest-framework


    【解决方案1】:

    以下是在 Django Rest Framework API 视图中进行 API 调用的方法:

    因为您想将外部 API 请求存储在数据库中。这是存储用户结果的模型示例。

    models.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}"
    

    views.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 已通过身份验证,more infos here。因为我们需要用户保存检索到的凭据 在数据库中。

    urls.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);
    });
    

    【讨论】:

      猜你喜欢
      • 2022-01-24
      • 2018-05-24
      • 1970-01-01
      • 2015-02-14
      • 1970-01-01
      • 2017-10-30
      • 2019-11-19
      • 1970-01-01
      • 2017-07-06
      相关资源
      最近更新 更多