2016-09-17 1 views
1

장고 프레임 워크를 기반으로하는 웹 사이트가 있습니다. 나는 Nginx webserver (uWSGI, Django, Nginx)를 통해 웹 사이트를 운영 중이다. Accept-Ranges 헤더로 내 웹 사이트에서 mp3 파일을 스트리밍하고 싶습니다. Nginx로 mp3 파일을 제공하고 싶습니다. 내 API가 이렇게 보이도록해야합니다.Nginx를 통해 Django에서 mp3 파일을 스트리밍

http://192.168.1.105/stream/rihanna 

부분 다운로드 (Accept-Ranges)로 mp3 파일을 반환해야합니다. 내 mp3 파일이 저장됩니다에서 : 나는 이러한 구성에서 서버를 실행하고 192.168.1.105/stream/rihanna를 탐색 할 때, 장고 (404)

을 반환 /홈/고정 표시기/코드/응용 프로그램/미디어/데이터/내 Nginx에의 conf :

# mysite_nginx.conf 

# the upstream component nginx needs to connect to 
upstream django { 
server unix:/home/docker/code/app.sock; # for a file socket 
# server 127.0.0.1:8001; # for a web port socket (we'll use this first) 
} 

# configuration of the server 
server { 
# the port your site will be served on, default_server indicates that this server block 
# is the block to use if no blocks match the server_name 
listen  80 default; 
include /etc/nginx/mime.types; 
# the domain name it will serve for 
server_name .example.com; # substitute your machine's IP address or FQDN 
charset  utf-8; 

# max upload size 
client_max_body_size 75M; # adjust to taste 

# Django media 
location /media { 
    autoindex  on; 
    sendfile  on; 
    sendfile_max_chunk  1024m; 
    internal; 
    #add_header X-Static hit; 
    alias /home/docker/code/app/media/; # your Django project's media files - amend as required 
} 
location /static { 
    alias /home/docker/code/app/static/; # your Django project's static files - amend as required 
} 

# Finally, send all non-media requests to the Django server. 
location/{ 

    uwsgi_pass django; 
    include  /home/docker/code/uwsgi_params; # the uwsgi_params file you installed 
    } 
} 

내 views.py :

def stream(request, offset): 
    try: 

      mp3_path = os.getcwd() + '/media/data/' + offset + '.mp3' 
      mp3_data = open(mp3_path, "r").read() 



except: 
    raise Http404() 





response = HttpResponse(mp3_data, content_type="audio/mpeg", status=206) 
response['X-Accel-Redirect'] = mp3_path 
response['X-Accel-Buffering'] = 'no' 
response['Content-Length'] = os.path.getsize(mp3_path) 
response['Content-Dispostion'] = "attachment; filename=" + mp3_path 
response['Accept-Ranges'] = 'bytes' 

내가 Nginx에이 파일을 제공합니다. 그리고 나는 Accept-Ranges를 활성화해야합니다.

내 Settings.py :

# Build paths inside the project like this: os.path.join(BASE_DIR, ...) 
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 


# Quick-start development settings - unsuitable for production 
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ 


DEBUG = True 

ALLOWED_HOSTS = ['localhost', '127.0.0.1', '192.168.1.105', '0.0.0.0'] 


# Application definition 

INSTALLED_APPS = [ 
    'django.contrib.admin', 
    'django.contrib.auth', 
    'django.contrib.contenttypes', 
    'django.contrib.sessions', 
    'django.contrib.messages', 
    'django.contrib.staticfiles', 
] 

MIDDLEWARE = [ 
    'django.middleware.security.SecurityMiddleware', 
    'django.contrib.sessions.middleware.SessionMiddleware', 
    'django.middleware.common.CommonMiddleware', 
    'django.middleware.csrf.CsrfViewMiddleware', 
    'django.contrib.auth.middleware.AuthenticationMiddleware', 
    'django.contrib.messages.middleware.MessageMiddleware', 
    'django.middleware.clickjacking.XFrameOptionsMiddleware', 
] 

ROOT_URLCONF = 'beats.urls' 

TEMPLATES = [ 
    { 
    'BACKEND': 'django.template.backends.django.DjangoTemplates', 
    'DIRS': [os.path.join(BASE_DIR, 'templates')] 
    , 
    'APP_DIRS': True, 
    'OPTIONS': { 
     'context_processors': [ 
      'django.template.context_processors.debug', 
      'django.template.context_processors.request', 
      'django.contrib.auth.context_processors.auth', 
      'django.contrib.messages.context_processors.messages', 
      ], 
     }, 
    }, 
] 

WSGI_APPLICATION = 'beats.wsgi.application' 

STATIC_ROOT = os.path.join(BASE_DIR, 'static/') 
MEDIA_URL = os.path.join(BASE_DIR, 'media/') 




# Database 


DATABASES = { 
    'default': { 
     'ENGINE': 'django.db.backends.sqlite3', 
     'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 
    } 
} 


# Password validation 


AUTH_PASSWORD_VALIDATORS = [ 
    { 
     'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 
    }, 
    { 
     'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 
}, 
{ 
    'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 
}, 
{ 
    'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 
}, 
] 



LANGUAGE_CODE = 'en-us' 

TIME_ZONE = 'UTC' 

USE_I18N = True 

USE_L10N = True 

USE_TZ = True 



STATIC_URL = '/static/' 

내 문제가 있습니다 : 그것은 작동하지 않으며, 장고는 404 오류 웹 페이지를 반환합니다.

+1

장고는 파일을 볼 수있는 사람을 실제로 제어 할 수 있어야합니까? 그냥 정적 파일 디렉토리에 넣지 않고 Nginx가 스트리밍을 처리하게하는 경우. 당신은 훨씬 더 나은 성능을 얻을 수 있습니다. –

+0

@ AndréBorie 감사합니다. 내 관리 파일은/static/path에 있습니다. 내가 그들을 찾아보고 싶을 때, Nginx는 404를 반환합니다. 나는 정말로 왜 그런지 모릅니다. Nginx는 내 웹 사이트의 정적 경로에서도 404 오류를 반환합니다. –

답변

1

우선 Nginx 구성 파일을 사용 가능한 사이트 경로에 복사하지 않았습니다. 그리고 그것 때문에, 그것은 작동하지 않았습니다. 그리고 내 views.py에서 :

response = HttpResponse(mp3_data, content_type="audio/mpeg", status=206) 
response['X-Accel-Redirect'] = mp3_path 

이 2 줄

로 변경해야합니다

response= HttpResponse('', content_type="audio/mpeg", status=206) 
response['X-Accel-Redirect'] = '/media/data/' + offset + '.mp3' 

나는이 문제를 가지고 다른 사람을 도움이되기를 바랍니다.