簡體   English   中英

將Django中的媒體文件視為可搜索的文件(帶有HTTP PartialResponse)

[英]Serve media files in Django as seekable (with HTTP PartialResponse)

我知道與其他服務器(例如Apache)一起提供這些視頻文件會更容易,但是我現在不能使用它。

我在使用Django(使用那些FileField模型)的media文件夾中有一些上傳的視頻。 現在,我已經設置了一種流式傳輸這些視頻的方法,但是問題是,該視頻沒有找到。

可以通過實現某種實現HTTP PARTIAL RESPONSE的流響應( 也許是這樣 ,但我不確定並且不知道如何做)來解決。 有什么辦法實現呢?

我正在使用此處指定的媒體文件(請參閱MEDIA_ROOT和MEDIA_URL部分。)

我的settings.py-

MEDIA_ROOT = os.path.join(BASE_DIR, "media/")
MEDIA_URL = "media/"
...
'context_processors': [
            'django.template.context_processors.media',
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
]

我的urls.py-

urlpatterns = [...]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,
                      document_root=settings.MEDIA_ROOT)

最終在此模塊django-ranged-response的幫助下解決了這個問題。 (使用pip install django-ranged-response安裝它)。

然后,在我的應用程序的urls.py -

urlpatterns = [
    ...
url(r'^videos/(?P<video_file>[0-9a-zA-Z _!@$|:;&*()"\'.,<>+=`-]+)/$',
    views.video_stream, name='v_stream'),
]

views.py文件中-

import os, mimetypes
from django.http import HttpResponseNotFound
from ranged_response import RangedFileResponse

...

def video_stream(request, video_file):
    _file = FILE_PATH + video_file
    if not os.path.isfile(_file):
        return HttpResponseNotFound()
    response = RangedFileResponse(
        request, open(_file, 'rb'),
        content_type=mimetypes.guess_type(_file)[0]
    )
    response['Content-Length'] = os.path.getsize(_file)
    return response

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM