基于WhiteNoise的Python静态文件服务方案 2025-02-05 Python 暂无评论 18 次阅读 1.Install WhiteNoise as described: ``` pip install WhiteNoise ``` 2.Create the STATIC_ROOT variable and add WhiteNoise to your MIDDLEWARE variable in settings.py: ``` #settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', #add whitenoise 'django.contrib.sessions.middleware.SessionMiddleware', ... ] #... STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') ##specify static root ``` 3.Then, modify your wsgi.py file as explained in Johnny's answer: ``` #wsgi.py from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise application = get_wsgi_application() application = DjangoWhiteNoise(application) ``` 4.After that, deploy your changes to your server (with git or whatever you use). 5.Finally, run the collectstatic option from your manage.py on your server. This will copy all files from your static folders into the STATIC_ROOT directory we specified before: ``` $ python manage.py collectstatic ``` You will now see a new folder named staticfiles that contains such elements. After following these steps you can now run your server and will be able to see your static files while in Production mode. Update: In case you had version < 4 the changelog indicates that it's no longer necessary to declare the WSGI_APPLICATION = 'projectName.wsgi.application' on your settings.py file. 参考来源 https://stackoverflow.com/questions/5836674/why-does-debug-false-setting-make-my-django-static-files-access-fail# 供参考 ``` STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') ``` WhiteNoise:Python静态文件服务的极简方案 Radically simplified static file serving for Python web apps 项目地址: https://gitcode.com/gh_mirrors/wh/whitenoise 白噪声(WhiteNoise)是一个专为简化Python网络应用中的静态文件服务而设计的开源项目。该工具通过几行配置即可使你的应用自给自足地处理静态资源,无需依赖如Nginx、Amazon S3等外部服务,尤其适用于Heroku、OpenShift等平台即服务(PaaS)环境。它优化了与CDN的集成,确保即使在高流量场景下也能保持性能,而不牺牲其简单性。WhiteNoise支持任何WSGI兼容的应用,且对Django有特别的自动化配置支持。 主要编程语言 Python:作为核心编程语言,WhiteNoise充分利用Python的灵活性来实现高效静态文件管理。 核心功能 自动配置:特别为Django提供无缝集成,简化配置过程。 压缩服务:自动处理GZip和Brotli格式的压缩内容,正确管理和响应Accept-Encoding头部。 长效缓存:为不变的内容设置远期缓存头,提升客户端缓存效率。 安全性:遵循最佳实践,确保安全的静态文件分发。 最近更新的功能 由于未提供具体的更新日志细节,无法精确列出最近的更新点。通常,开源项目的更新可能涉及性能优化、新特性添加、安全修复或改进与其他库的兼容性。对于`https://github.com/evansd/whitenoise.git`这个特定项目,访问其GitHub页面上的“Commits”、“Releases”标签可以获取最新版本的具体更新信息,包括任何错误修正、新增功能或性能改进。开发者应查看项目仓库的最新更新记录以了解详细情况。 WhiteNoise以其易用性和对性能的关注,成为众多Python Web应用中静态文件管理的优选解决方案,不仅减少了部署复杂度,也保障了应用的健壮性和扩展性。无论是初创项目还是大型企业级应用,WhiteNoise都是一个值得考虑的选择。 原文链接:https://blog.csdn.net/gitblog_01061/article/details/143556705 标签: django 本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。