2017-07-22 25 views
0

我知道用Apache等其他服務器提供這些視頻文件會更容易,但現在我無法使用它。將Django中的媒體文件作爲可搜索的服務(使用HTTP PartialResponse)

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

這可以通過實施某種類型的流式響應(maybe this,但我不確定並且不知道該怎麼辦)來解決,它實現了HTTP PARTIAL RESPONSE。任何方式來實現這一點?

我使用的媒體文件規定here

我的settings.py(見MEDIA_ROOT,MEDIA_URL部分。) -

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) 

回答

1

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

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

urlpatterns = [ 
    ... 
url(r'^videos/(?P<video_file>[0-9a-zA-Z [email protected]$|:;&*()"\'.,<>+=`-]+)/$', 
    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