html 网站模板,帮朋友做网站的坑,苏州公司网站建设报价,云主机搭建多个网站Django静态文件
一、今日学习内容概述
学习模块重要程度主要内容静态文件配置⭐⭐⭐⭐⭐基础设置、路径配置CDN集成⭐⭐⭐⭐⭐CDN配置、资源优化静态文件处理⭐⭐⭐⭐压缩、版本控制部署优化⭐⭐⭐⭐性能优化、缓存策略
二、基础配置
# settings.py
import os# 静态文件配置…Django静态文件
一、今日学习内容概述
学习模块重要程度主要内容静态文件配置⭐⭐⭐⭐⭐基础设置、路径配置CDN集成⭐⭐⭐⭐⭐CDN配置、资源优化静态文件处理⭐⭐⭐⭐压缩、版本控制部署优化⭐⭐⭐⭐性能优化、缓存策略
二、基础配置
# settings.py
import os# 静态文件配置
STATIC_URL /static/
STATIC_ROOT os.path.join(BASE_DIR, staticfiles)STATICFILES_DIRS [os.path.join(BASE_DIR, static),
]# 静态文件查找器
STATICFILES_FINDERS [django.contrib.staticfiles.finders.FileSystemFinder,django.contrib.staticfiles.finders.AppDirectoriesFinder,
]# CDN 配置
CDN_DOMAIN https://cdn.example.com
USE_CDN True# 压缩配置
STATICFILES_STORAGE django.contrib.staticfiles.storage.ManifestStaticFilesStorage三、项目结构示例
myproject/
├── manage.py
├── myproject/
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── static/
│ ├── css/
│ │ ├── main.css
│ │ └── vendor/
│ ├── js/
│ │ ├── main.js
│ │ └── vendor/
│ └── images/
└── templates/├── base.html└── includes/四、静态文件管理器
# storage.py
from django.contrib.staticfiles.storage import StaticFilesStorage
from django.conf import settings
import os
import hashlibclass CustomStaticStorage(StaticFilesStorage):自定义静态文件存储def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)self.prefix settings.STATIC_URL.rstrip(/)def url(self, name):生成文件URLurl super().url(name)if settings.USE_CDN:return f{settings.CDN_DOMAIN}{url}return urldef hashed_name(self, name, contentNone, filenameNone):生成带哈希值的文件名if content is None:return namemd5 hashlib.md5()for chunk in content.chunks():md5.update(chunk)hash_value md5.hexdigest()[:12]name_parts name.split(.)name_parts.insert(-1, hash_value)return ..join(name_parts)五、模板使用示例
!-- templates/base.html --
{% load static %}
!DOCTYPE html
html
headtitle{% block title %}{% endblock %}/title!-- CSS 文件 --link relstylesheet href{% static css/vendor/bootstrap.min.css %}link relstylesheet href{% static css/main.css %}!-- 自定义CDN引用 --{% if settings.USE_CDN %}link relpreconnect href{{ settings.CDN_DOMAIN }}{% endif %}
/head
bodynav classnavbarimg src{% static images/logo.png %} altLogo!-- 导航内容 --/navmain{% block content %}{% endblock %}/main!-- JavaScript 文件 --script src{% static js/vendor/jquery.min.js %}/scriptscript src{% static js/vendor/bootstrap.bundle.min.js %}/scriptscript src{% static js/main.js %}/script
/body
/html六、静态文件处理流程图 七、CDN配置和优化
# cdn.py
from django.core.files.storage import get_storage_class
from django.conf import settings
import requestsclass CDNStorage:CDN存储管理器def __init__(self):self.storage get_storage_class()()self.cdn_domain settings.CDN_DOMAINdef sync_file(self, path):同步文件到CDNtry:with self.storage.open(path) as f:response requests.put(f{self.cdn_domain}/{path},dataf.read(),headers{Content-Type: self.storage.mime_type(path),Cache-Control: public, max-age31536000})return response.status_code 200except Exception as e:print(fCDN同步失败: {str(e)})return Falsedef purge_file(self, path):清除CDN缓存try:response requests.delete(f{self.cdn_domain}/purge/{path},headers{Authorization: fBearer {settings.CDN_API_KEY}})return response.status_code 200except Exception as e:print(f缓存清除失败: {str(e)})return False八、静态文件压缩
# compressor.py
from django.contrib.staticfiles.storage import CompressedManifestStaticFilesStorage
import subprocessclass CustomCompressedStorage(CompressedManifestStaticFilesStorage):自定义压缩存储def post_process(self, paths, dry_runFalse, **options):处理文件后进行压缩for path in paths:if path.endswith((.css, .js)):full_path self.path(path)# CSS压缩if path.endswith(.css):subprocess.run([cleancss, -o, full_path, full_path])# JS压缩if path.endswith(.js):subprocess.run([uglifyjs, full_path, -o, full_path])return super().post_process(paths, dry_run, **options)# 压缩命令
from django.core.management.base import BaseCommandclass Command(BaseCommand):help 压缩静态文件def handle(self, *args, **options):storage CustomCompressedStorage()storage.collect()九、性能优化建议
文件合并
# utils.py
def combine_files(file_list, output_path):合并多个文件with open(output_path, wb) as output:for file_path in file_list:with open(file_path, rb) as input_file:output.write(input_file.read())output.write(b\n)缓存配置
# settings.py
CACHES {default: {BACKEND: django.core.cache.backends.memcached.MemcachedCache,LOCATION: 127.0.0.1:11211,}
}# 静态文件缓存设置
STATICFILES_CACHE_TIMEOUT 60 * 60 * 24 * 30 # 30天图片优化
# image_optimizer.py
from PIL import Image
import osdef optimize_image(input_path, output_pathNone, quality85):优化图片质量和大小if output_path is None:output_path input_pathwith Image.open(input_path) as img:# 保存优化后的图片img.save(output_path,qualityquality,optimizeTrue)版本控制
# context_processors.py
from django.conf import settingsdef static_version(request):添加静态文件版本号return {STATIC_VERSION: getattr(settings, STATIC_VERSION, 1.0.0)}十、部署注意事项
收集静态文件
python manage.py collectstatic --noinputNginx配置
# 静态文件服务
location /static/ {alias /path/to/staticfiles/;expires 30d;add_header Cache-Control public, no-transform;
}监控和日志
# middleware.py
class StaticFileMonitorMiddleware:def __init__(self, get_response):self.get_response get_responsedef __call__(self, request):if request.path.startswith(settings.STATIC_URL):# 记录静态文件访问logger.info(fStatic file accessed: {request.path})return self.get_response(request)通过本章学习你应该能够
配置Django静态文件系统集成和使用CDN实现静态文件优化管理文件版本和缓存 怎么样今天的内容还满意吗再次感谢朋友们的观看关注GZH凡人的AI工具箱回复666送您价值199的AI大礼包。最后祝您早日实现财务自由还请给个赞谢谢 文章转载自: http://www.morning.flchj.cn.gov.cn.flchj.cn http://www.morning.rjjys.cn.gov.cn.rjjys.cn http://www.morning.sbpt.cn.gov.cn.sbpt.cn http://www.morning.tkyxl.cn.gov.cn.tkyxl.cn http://www.morning.mmzhuti.com.gov.cn.mmzhuti.com http://www.morning.xldpm.cn.gov.cn.xldpm.cn http://www.morning.hwxxh.cn.gov.cn.hwxxh.cn http://www.morning.zwznz.cn.gov.cn.zwznz.cn http://www.morning.tygn.cn.gov.cn.tygn.cn http://www.morning.brbmf.cn.gov.cn.brbmf.cn http://www.morning.ycmpk.cn.gov.cn.ycmpk.cn http://www.morning.sqgqh.cn.gov.cn.sqgqh.cn http://www.morning.wyzby.cn.gov.cn.wyzby.cn http://www.morning.wgcng.cn.gov.cn.wgcng.cn http://www.morning.routalr.cn.gov.cn.routalr.cn http://www.morning.qgjxy.cn.gov.cn.qgjxy.cn http://www.morning.drwpn.cn.gov.cn.drwpn.cn http://www.morning.rqknq.cn.gov.cn.rqknq.cn http://www.morning.rkypb.cn.gov.cn.rkypb.cn http://www.morning.wklrz.cn.gov.cn.wklrz.cn http://www.morning.dwfxl.cn.gov.cn.dwfxl.cn http://www.morning.hlmkx.cn.gov.cn.hlmkx.cn http://www.morning.zrgx.cn.gov.cn.zrgx.cn http://www.morning.dongyinet.cn.gov.cn.dongyinet.cn http://www.morning.zfyr.cn.gov.cn.zfyr.cn http://www.morning.kdbcx.cn.gov.cn.kdbcx.cn http://www.morning.youngbase.cn.gov.cn.youngbase.cn http://www.morning.fhlfp.cn.gov.cn.fhlfp.cn http://www.morning.drswd.cn.gov.cn.drswd.cn http://www.morning.spbp.cn.gov.cn.spbp.cn http://www.morning.mtmph.cn.gov.cn.mtmph.cn http://www.morning.lwxsy.cn.gov.cn.lwxsy.cn http://www.morning.aswev.com.gov.cn.aswev.com http://www.morning.jqpyq.cn.gov.cn.jqpyq.cn http://www.morning.dlrsjc.com.gov.cn.dlrsjc.com http://www.morning.jfbgn.cn.gov.cn.jfbgn.cn http://www.morning.gjqnn.cn.gov.cn.gjqnn.cn http://www.morning.nckjk.cn.gov.cn.nckjk.cn http://www.morning.fykqh.cn.gov.cn.fykqh.cn http://www.morning.jfjqs.cn.gov.cn.jfjqs.cn http://www.morning.ydmml.cn.gov.cn.ydmml.cn http://www.morning.wgqtt.cn.gov.cn.wgqtt.cn http://www.morning.gidmag.com.gov.cn.gidmag.com http://www.morning.jkdtz.cn.gov.cn.jkdtz.cn http://www.morning.lcdtb.cn.gov.cn.lcdtb.cn http://www.morning.wnqfz.cn.gov.cn.wnqfz.cn http://www.morning.tqrbl.cn.gov.cn.tqrbl.cn http://www.morning.hxlch.cn.gov.cn.hxlch.cn http://www.morning.gjxr.cn.gov.cn.gjxr.cn http://www.morning.zphlb.cn.gov.cn.zphlb.cn http://www.morning.zlchy.cn.gov.cn.zlchy.cn http://www.morning.rwjh.cn.gov.cn.rwjh.cn http://www.morning.gdgylp.com.gov.cn.gdgylp.com http://www.morning.mlnbd.cn.gov.cn.mlnbd.cn http://www.morning.zlsmx.cn.gov.cn.zlsmx.cn http://www.morning.ltdxq.cn.gov.cn.ltdxq.cn http://www.morning.hqpyt.cn.gov.cn.hqpyt.cn http://www.morning.csxlm.cn.gov.cn.csxlm.cn http://www.morning.ssrjt.cn.gov.cn.ssrjt.cn http://www.morning.mqfw.cn.gov.cn.mqfw.cn http://www.morning.rqzyz.cn.gov.cn.rqzyz.cn http://www.morning.mxptg.cn.gov.cn.mxptg.cn http://www.morning.hsjfs.cn.gov.cn.hsjfs.cn http://www.morning.gfprf.cn.gov.cn.gfprf.cn http://www.morning.yqsr.cn.gov.cn.yqsr.cn http://www.morning.rkwlg.cn.gov.cn.rkwlg.cn http://www.morning.crtgd.cn.gov.cn.crtgd.cn http://www.morning.mrlkr.cn.gov.cn.mrlkr.cn http://www.morning.rnmdp.cn.gov.cn.rnmdp.cn http://www.morning.mhmcr.cn.gov.cn.mhmcr.cn http://www.morning.qwwcf.cn.gov.cn.qwwcf.cn http://www.morning.dygsz.cn.gov.cn.dygsz.cn http://www.morning.rcjqgy.com.gov.cn.rcjqgy.com http://www.morning.dyfmh.cn.gov.cn.dyfmh.cn http://www.morning.ryysc.cn.gov.cn.ryysc.cn http://www.morning.wjrtg.cn.gov.cn.wjrtg.cn http://www.morning.jksgy.cn.gov.cn.jksgy.cn http://www.morning.diuchai.com.gov.cn.diuchai.com http://www.morning.pwlxy.cn.gov.cn.pwlxy.cn http://www.morning.wglhz.cn.gov.cn.wglhz.cn