Django Rest框架在Viewset视图列表API上添加分页(对象数量限制),而不使用Django模型类

2024-09-30 06:33:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试构建一个web scraper API,在该API中,它将从网站获取数据列表并返回。我想给结果加上限制

我当前的API路径是/api/country/

我在找像这样的东西

/api/country/?limit=1

视图

class CovidCountryViewSet(viewsets.ViewSet):
    
    serializer_class = CovidCountrySerializer
    
    def list(self, request):
        summary = CovidDataSraper().fetch_summary_data()
                
        serializer = CovidCountrySerializer(
            instance=summary["data"], many=True)
        return Response(serializer.data)

序列化程序.py

class CovidCountrySerializer(serializers.Serializer):
    country = serializers.CharField(max_length=256)
    total_cases = serializers.IntegerField()
    active_cases = serializers.IntegerField()
    total_deaths = serializers.IntegerField()
    population = serializers.IntegerField()
    total_recovered = serializers.IntegerField()
    percentate_of_population_infected = serializers.DecimalField(max_digits=10, decimal_places=2, coerce_to_string=False)
    recovery_rate = serializers.DecimalField(max_digits=10, decimal_places=2, coerce_to_string=False)

型号.py

class CovidCountry:

    def __init__(self, **props):
        fields = ['country', 'total_cases', 'active_cases',
         'total_deaths', 'population', 'total_recovered']

        for field in fields:
            setattr(self, field, props.get(field, None))

url.py

router = routers.DefaultRouter()
router.register(r'covid-summary', views.CovidCountryViewSet, basename="covid")

urlpatterns = [
    path('api/', include((router.urls, 'covid'), namespace='covid'))
]

Tags: pyselfapidatasummarycountryclasstotal

热门问题