Created
February 7, 2023 14:32
-
-
Save paulwababu/d8950758a6c72d9c9b3e3cb4c39c751e to your computer and use it in GitHub Desktop.
django rest framework youtube downloader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DownloadVideoAPIView(APIView): | |
def post(self, request): | |
allowed_ips = ['127.0.0.1:5500'] | |
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') | |
if x_forwarded_for: | |
return HttpResponseForbidden('Requests from proxy servers are not allowed') | |
if request.META['REMOTE_ADDR'] not in allowed_ips: | |
print(request.META['REMOTE_ADDR']) | |
return HttpResponseForbidden() | |
video_id = request.GET.get('video_id') | |
url = f"https://www.youtube.com/watch?v={video_id}" | |
yt = YouTube(url) | |
quality = request.GET.get('quality', 'highest') | |
video = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first() | |
if quality == 'highest': | |
video = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first() | |
elif quality == 'lowest': | |
video = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').first() | |
else: | |
video = yt.streams.get_by_resolution(quality) | |
file = io.BytesIO(video.download()) | |
return Response(file.getvalue(), content_type="video/mp4") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment