我有一個帶有 Vuejs 前端的非常標準的 Django 應用程式。
我有不同的環境(preprod/ dev),其中我有檔案上傳/下載功能。
對于檔案,一切正常,因為它們是通過附件 ( Content-Disposition: attachment) 中的標準 API 視圖回傳的。但是,當涉及到影像時,例如個人資料圖片,就會出現問題。
在開發(DEBUG=True)中,我有這個:
from django.conf import settings
from django.conf.urls.static import static
from django.urls import include, path
from backend.applications.base.views.authentication_views import LoginAPIView, LogoutAPIView
urlpatterns = [
path("api/login", LoginAPIView.as_view()),
path("api/logout", LogoutAPIView.as_view()),
path("api/base/", include("backend.applications.base.urls")),
path("api/contact/", include("backend.applications.contact.urls")),
path("api/helpdesk/", include("backend.applications.helpdesk.urls")),
path("api/inventory/", include("backend.applications.inventory.urls")),
] static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # For serving media files when DEBUG=True
并正確提供影像(開發模式下沒有 nginx,只有前端和后端開發服務器django's runserver)。
然而,我的 preprod 是由一個為我構建的 vuejs 前端提供服務的 nginx 容器和一個包含我的 Django ( DEBUG=False) 應用程式的后端容器組成的(它在gunicorn這個時候運行,如下所示:) gunicorn backend.wsgi:application --bind 0.0.0.0:8000 --access-logfile="-"。
在嘗試提供影像之前,我有這個 nginx 配置:
http {
client_max_body_size 5M;
upstream backend_api {
server backend:8000;
# 'backend' is the name of the backend service in my docker-compose config
}
server {
listen 80;
include /etc/nginx/mime.types;
root /usr/share/nginx/html;
index index.html;
location = /favicon.ico {
access_log off;
log_not_found off;
}
location /api {
proxy_pass http://backend_api;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_redirect off;
}
location / {
try_files $uri $uri/ /index.html;
}
}
}
然后我認為/media請求也應該傳遞給后端,我改變了
location /api
進入
location ~ ^/(api|media)/ {
我的/apiURL 仍然得到正確處理,但/mediaURL 由 404 回答:
(嘗試在看板視圖中加載我的用戶的個人資料圖片)。
直接在我的瀏覽器中直接嘗試http://localhost/media/base/users/8/picture.jpg也不起作用:

從這里我不知道該怎么做才能解決這個問題。如果缺少某些內容,請提及,我會更新帖子。
uj5u.com熱心網友回復:
Django 不使用 runserver 提供靜態和媒體檔案,為此您需要 WhiteNoise。請參閱http://whitenoise.evans.io/en/stable/ Whitenoise 但不適合提供用戶上傳的媒體檔案。見http://whitenoise.evans.io/en/stable/django.html#serving-media-files
(可選地,跳過白噪聲,并通過 NGINX 托管靜態/媒體檔案。)
您真的不應該使用py manage.py runserver. 這是不安全的。請參閱為什么不在 Django 中使用“runserver”進行生產?和https://docs.djangoproject.com/en/dev/ref/django-admin/#runserver
改用 Gunicorn 之類的東西。
請參閱https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/gunicorn/
(或女服務員,windows 替代品)
https://pypi.org/project/django-waitress/
要使用 nginx 托管靜態/媒體檔案,請將其粘貼到您的 nginx conf 中:
location /media {
alias /PATH/TO/DIRECTORY; #Absolute path.
}
在您的 settings.py 中,將媒體根目錄設定為同一目錄。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/505160.html
標籤:django nginx nginx-反向代理 django 媒体
上一篇:如何在Ansible中的Playbook和Role之間回圈
下一篇:單個映射指令中的多個變數
