cineclub-site/server/myapi/views/tmdb_views.py

61 lines
2.1 KiB
Python
Raw Normal View History

from datetime import timedelta
2022-05-30 00:18:09 +02:00
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
2022-06-10 00:18:56 +02:00
from tmdbv3api import TMDb, Search, Movie
from myapi.models import Film
from myapi.serializers import FilmSerializer
2022-06-10 00:18:56 +02:00
from ulm_cine_club_api.settings.base import TMDB_API_KEY
2022-05-30 00:18:09 +02:00
tmdb = TMDb()
2022-06-10 00:18:56 +02:00
tmdb.api_key = TMDB_API_KEY
2022-05-30 00:18:09 +02:00
tmdb.language = "fr"
class TmdbViewSet(viewsets.ViewSet):
2022-06-10 00:21:06 +02:00
@action(methods=["GET"], detail=False)
2022-05-30 00:18:09 +02:00
def search(self, request):
2022-06-10 00:21:06 +02:00
query = request.query_params["query"]
2022-05-30 00:18:09 +02:00
search = Search()
2022-06-10 00:21:06 +02:00
tmdb_results = search.movies({"query": query})
res = [
{
2022-05-30 00:18:09 +02:00
"id": film["id"],
"release_date": film["release_date"],
"title": film["title"],
2022-06-10 00:21:06 +02:00
"poster_path": film["poster_path"],
}
for film in tmdb_results
]
2022-05-30 00:18:09 +02:00
return Response(res)
@action(methods=["GET"], detail=True)
def fill(self, request, pk=None):
tmdb_movie = Movie().details(pk, "images,credits,keywords")
internal_movie = Film(
title=tmdb_movie["title"],
imdb_id=tmdb_movie["imdb_id"],
tmdb_id=tmdb_movie["id"],
synopsis=tmdb_movie["overview"],
poster_link=tmdb_movie["poster_path"],
duration=timedelta(minutes=tmdb_movie["runtime"]),
release_year=tmdb_movie["release_date"][:4],
director=next(person["name"] for person in tmdb_movie["credits"]["crew"] if person["job"] == "Director"),
actors=[person["name"] for person in tmdb_movie["credits"]["cast"][:5]],
origin_country=", ".join(
short_country_name(country["name"]) for country in tmdb_movie["production_countries"]
), # TODO iso to French name
is_in_color=not any(keyword["id"] == 12999 for keyword in tmdb_movie["keywords"]["keywords"])
)
serializer = FilmSerializer(internal_movie)
return Response(serializer.data)
def short_country_name(country_name: str):
if country_name == "United States of America":
return "USA"
return country_name