这可能是一个愚蠢的问题,但在文档中它说:
Serving files uploaded by a user during development.¶
During development, you can serve user-uploaded media files from MEDIA_ROOT using the
django.contrib.staticfiles.views.serve()
view.This is not suitable for production use! For some common deployment strategies, see Deploying static files.
For example, if your MEDIA_URL is defined as /media/, you can do this by adding the following snippet to your urls.py:
from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
这是否意味着生产使用 + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
不应该使用或应该使用?
我的理解是你不应该使用 django.contrib.staticfiles.views.serve()
但我不确定这是否不一样
最佳答案
django.contrib.staticfiles.views.serve()
不应用于部署。
首先,调用views.serve()
anywhere 只有在 DEBUG = True
时才有效, 并会引发 Http404
如果在 DEBUG = False
时使用,就像部署您的应用程序时一样。然而,在开发中使用它的好处是您不必运行 collectstatic
。/收集静态文件:您可以从静态或媒体根目录中提取它们,而无需四处移动。
它也有些不安全:views.serve()
将使用 mimetype
猜测其服务的文件的内容类型模块,它将依赖于您正在开发的平台的映射文件:由于特定环境中的 mimetype 模块,生产中的行为可能不同。
文档有更多关于 django.contrib.staticfiles.views.serve()
的信息.
现在谈到生产,提供静态/媒体文件并不是 Django 的 WSGI 能为您做好的事情。 Django 是为提供应用程序内容而编写的,在提供静态/用户上传内容方面表现不佳。如果您期望中等负载,请使用单独的服务器,例如 Apache或 Nginx与网络服务器结合使用 uWSGI更具可持续性并且可以处理更多。 This doc有关如何设置这些的更多详细信息/解释更多。
关于django - 在 django 开发期间提供用户上传的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31756907/