猿问

Django Rest Framework url 调度器

我正在尝试与 SWAPI API 进行交互。


我想要一个获取所有电影的视图(films/)和一个获取一个(film/id)的视图。


当我点击http://127.0.0.1:8000/api/films/?id=4它进入get_films功能。


我正在使用 Django==1.11 和 Django Rest Framework==3.9.0 。


我的 urs.py:


urlpatterns = [

    url(r'films/',views.get_films,name="get-films"),

    url(r'films/(?P<id>[0-9])/',views.get_film,name="get-film"),

]

我的意见.py:


MAX_RETRIES = 5 

API_URL= "https://swapi.co/api/" 


@api_view(['GET', 'POST'])

def get_films(request):

    request_url = API_URL + "films"

    print(request_url)

    if request.method == "GET":

        attempt_num = 0  # keep track of how many times we've retried

        while attempt_num < MAX_RETRIES:

            r = requests.get(request_url, timeout=10)

            if r.status_code == 200:

                data = r.json()

                return Response(data, status=status.HTTP_200_OK)

            else:

                attempt_num += 1

                # You can probably use a logger to log the error here

                time.sleep(5)  # Wait for 5 seconds before re-trying

        return Response({"error": "Request failed"}, status=r.status_code)

    else:

        return Response({"error": "Method not allowed"}, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET', 'POST'])

def get_film(self, request):

    print('entered')

    request_url = API_URL + "films/" + request.query_params.get('id')

    if request.method == "GET":

        attempt_num = 0  # keep track of how many times we've retried

        while attempt_num < MAX_RETRIES:

            r = requests.get(request_url, timeout=10)

            if r.status_code == 200:

                data = r.json()

                return Response(data, status=status.HTTP_200_OK)

            else:

                attempt_num += 1

                # You can probably use a logger to log the error here

                time.sleep(5)  # Wait for 5 seconds before re-trying

        return Response({"error": "Request failed"}, status=r.status_code)

    else:

        return Response({"error": "Method not allowed"}, status=status.HTTP_400_BAD_REQUEST)


MMMHUHU
浏览 233回答 2
2回答

慕仙森

urlpatterns事情的顺序。尝试更改网址的顺序。它可能与第一个匹配并且没有到达第二个。
随时随地看视频慕课网APP

相关分类

Python
我要回答