Я пытаюсь взаимодействовать с API SWAPI.
Мне нужен вид, который выбирает все фильмы (films/
) и один, который выбирает один (film/id
).
Когда я нажимаю http://127.0.0.1:8000/api/films/?id=4
, он входит в функцию get_films
.
Я использую Django == 1.11 и Django Rest Framework == 3.9.0.
my 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"),
]
my views.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)