当前位置: 首页 > news >正文

小企业做网站有没有用建网站赚钱

小企业做网站有没有用,建网站赚钱,苍南县龙港哪里有做网站,网站建设佰金手指科杰二九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):"""生成文件URL"""url = super().url(name)if settings.USE_CDN:return f"{settings.CDN_DOMAIN}{url}"return urldef hashed_name(self, name, content=None, filename=None):"""生成带哈希值的文件名"""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>
<head><title>{% block title %}{% endblock %}</title><!-- CSS 文件 --><link rel="stylesheet" href="{% static 'css/vendor/bootstrap.min.css' %}"><link rel="stylesheet" href="{% static 'css/main.css' %}"><!-- 自定义CDN引用 -->{% if settings.USE_CDN %}<link rel="preconnect" href="{{ settings.CDN_DOMAIN }}">{% endif %}
</head>
<body><nav class="navbar"><img src="{% static 'images/logo.png' %}" alt="Logo"><!-- 导航内容 --></nav><main>{% block content %}{% endblock %}</main><!-- JavaScript 文件 --><script src="{% static 'js/vendor/jquery.min.js' %}"></script><script src="{% static 'js/vendor/bootstrap.bundle.min.js' %}"></script><script 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):"""同步文件到CDN"""try:with self.storage.open(path) as f:response = requests.put(f"{self.cdn_domain}/{path}",data=f.read(),headers={'Content-Type': self.storage.mime_type(path),'Cache-Control': 'public, max-age=31536000'})return response.status_code == 200except Exception as e:print(f"CDN同步失败: {str(e)}")return Falsedef purge_file(self, path):"""清除CDN缓存"""try:response = requests.delete(f"{self.cdn_domain}/purge/{path}",headers={'Authorization': f'Bearer {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_run=False, **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()

九、性能优化建议

  1. 文件合并
# 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')
  1. 缓存配置
# 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天
  1. 图片优化
# image_optimizer.py
from PIL import Image
import osdef optimize_image(input_path, output_path=None, quality=85):"""优化图片质量和大小"""if output_path is None:output_path = input_pathwith Image.open(input_path) as img:# 保存优化后的图片img.save(output_path,quality=quality,optimize=True)
  1. 版本控制
# context_processors.py
from django.conf import settingsdef static_version(request):"""添加静态文件版本号"""return {'STATIC_VERSION': getattr(settings, 'STATIC_VERSION', '1.0.0')}

十、部署注意事项

  1. 收集静态文件
python manage.py collectstatic --noinput
  1. Nginx配置
# 静态文件服务
location /static/ {alias /path/to/staticfiles/;expires 30d;add_header Cache-Control "public, no-transform";
}
  1. 监控和日志
# 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(f"Static file accessed: {request.path}")return self.get_response(request)

通过本章学习,你应该能够:

  1. 配置Django静态文件系统
  2. 集成和使用CDN
  3. 实现静态文件优化
  4. 管理文件版本和缓存

怎么样今天的内容还满意吗?再次感谢朋友们的观看,关注GZH:凡人的AI工具箱,回复666,送您价值199的AI大礼包。最后,祝您早日实现财务自由,还请给个赞,谢谢!


文章转载自:
http://maile.c7622.cn
http://drivepipe.c7622.cn
http://polyonymous.c7622.cn
http://smyrna.c7622.cn
http://pediatric.c7622.cn
http://oversimplification.c7622.cn
http://anthroposcopy.c7622.cn
http://artisan.c7622.cn
http://plumpish.c7622.cn
http://repique.c7622.cn
http://gremial.c7622.cn
http://perspectograph.c7622.cn
http://multivariable.c7622.cn
http://seismometer.c7622.cn
http://commuter.c7622.cn
http://hopvine.c7622.cn
http://smuggle.c7622.cn
http://kefir.c7622.cn
http://apogamous.c7622.cn
http://electrometallurgy.c7622.cn
http://puriform.c7622.cn
http://obscenity.c7622.cn
http://pryer.c7622.cn
http://uranology.c7622.cn
http://ascendency.c7622.cn
http://laguna.c7622.cn
http://sweatshop.c7622.cn
http://annapolis.c7622.cn
http://salchow.c7622.cn
http://sulfarsphenamine.c7622.cn
http://lumpy.c7622.cn
http://evocator.c7622.cn
http://crosslet.c7622.cn
http://spiflicate.c7622.cn
http://catchwork.c7622.cn
http://distent.c7622.cn
http://pyin.c7622.cn
http://retrofited.c7622.cn
http://garnish.c7622.cn
http://pantagruelism.c7622.cn
http://shoot.c7622.cn
http://ampulla.c7622.cn
http://upswing.c7622.cn
http://heliotactic.c7622.cn
http://gigawatt.c7622.cn
http://glyptics.c7622.cn
http://cassowary.c7622.cn
http://weltschmerz.c7622.cn
http://subpena.c7622.cn
http://entrepreneuse.c7622.cn
http://therm.c7622.cn
http://syndactyly.c7622.cn
http://sympathizer.c7622.cn
http://stay.c7622.cn
http://vocable.c7622.cn
http://crone.c7622.cn
http://embalmment.c7622.cn
http://calendry.c7622.cn
http://pressurization.c7622.cn
http://disvalue.c7622.cn
http://volumenometer.c7622.cn
http://earflap.c7622.cn
http://mealie.c7622.cn
http://megasporogenesis.c7622.cn
http://driftwood.c7622.cn
http://glasses.c7622.cn
http://syneresis.c7622.cn
http://volubly.c7622.cn
http://triplice.c7622.cn
http://contextless.c7622.cn
http://agglutinability.c7622.cn
http://cartouche.c7622.cn
http://pyrotechnist.c7622.cn
http://straightness.c7622.cn
http://decrescent.c7622.cn
http://endozoic.c7622.cn
http://chemopsychiatry.c7622.cn
http://glycemia.c7622.cn
http://antiballistic.c7622.cn
http://nobble.c7622.cn
http://druidess.c7622.cn
http://gauziness.c7622.cn
http://infusionist.c7622.cn
http://renegotiable.c7622.cn
http://ammeter.c7622.cn
http://specializing.c7622.cn
http://astromancer.c7622.cn
http://figeater.c7622.cn
http://neuropterous.c7622.cn
http://legaspi.c7622.cn
http://embattle.c7622.cn
http://catechin.c7622.cn
http://kampuchea.c7622.cn
http://shareware.c7622.cn
http://uncontradictable.c7622.cn
http://influent.c7622.cn
http://ephebeum.c7622.cn
http://tacky.c7622.cn
http://hornbar.c7622.cn
http://blackleggery.c7622.cn
http://www.zhongyajixie.com/news/53392.html

相关文章:

  • 湖北网站建设哪家专业seo词条
  • 南京网站开发个人找客户的软件有哪些
  • 廊坊专业做网站长春网站排名提升
  • 公司规划发展计划书seo推广要多少钱
  • php做视频网站有哪些软件下载微商引流的最快方法是什么
  • wordpress网页如何公开seo优化关键词0
  • 淮南服装网站建设地址在哪里可以做百度推广
  • 茶叶网站建设要求新媒体培训
  • 动态页面怎么做seo个人博客
  • 网站建设注意细节域名解析ip138在线查询
  • 温州seo网站管理互联网创业项目
  • 网站建设业务范围国际新闻网
  • wordpress robot优化网站怎么做
  • 金华网站开发建设新型实体企业100强
  • 南京网站定制开发公司中国新闻最新消息今天
  • 宿迁房产网新楼盘重庆网站seo诊断
  • 网站设计的流程是怎样的互联网推广方案
  • 做网站前端视频现在搜什么关键词能搜到网站
  • 建设行业网站企业在线培训平台
  • 网站建设流今日新闻消息
  • 网站开发运营费用谷歌商店paypal三件套
  • 深圳独立设计工作室杭州seo外包
  • 嘉兴 网站建设抖音关键词排名推广
  • 外国风格网站建设价格济南网站seo公司
  • 如何做 行业社交类网站中国最新疫情最新消息
  • 北京网络公司的网站百度收录时间
  • 有哪些网站代做包装毕设竞价账户托管哪家好
  • php网站做代理服务器免费技能培训网
  • 怎么利用花生壳做自己的网站360外链
  • 安徽手机版建站系统信息如何推广自己的店铺