Django custom static view-no need to bring its own static

1 Why not use the built-in static

When using the built-in static, there is no problem if you start it with python3 manage.py runserver, but once it is deployed to gunicorn, the static will be inaccessible. I found many ways, but I didn’t solve it. Finally, I decided to view it myself. Write a static view to specifically return static files

2 Match the static route in urls.py

from django.urls import re_path
from app1 import views # 导入你的app的视图

urlpatterns = [
	# 匹配静态路由
    re_path('^static/.*$', views.static), 
    ...
    ]

3 Add processing functions to the view of your app

# 返回静态文件
from django.http import StreamingHttpResponse
from MVonline1.settings import BASE_DIR # 你的设置
from wsgiref.util import FileWrapper
import mimetypes
def static(req):
    path =  BASE_DIR + req.path_info 
    content_type, encoding = mimetypes.guess_type(path)
    resp = StreamingHttpResponse(FileWrapper(open(path, 'rb')), content_type=content_type)
    resp['Cache-Control']="max-age=8640000"  
    # 静态文件最好加上这句让浏览器缓存,不然会重复请求
    return resp

Annotate the built-in staticfiles in setting.py


INSTALLED_APPS = [
    .....
    # 'django.contrib.staticfiles',  # 取消自带的static
    # 你的app
    'app1',
    
]

Search for STATIC in the setting and see if there are
comments like STATIC_ROOT, STATIC_URL, STATIC

5 Finally, just use /static/XXX to access your static directory

Your static directory should be placed under the root directory BASE_URL, at the same level as manage.py, of course, you can also modify the sentence of the static view function to adjust

path =  BASE_DIR + req.path_info

But it is still recommended to put it in the root directory
so that any app of yours can get static files through /static/, for
example in html

<script src="/static/app1/jquery.min.js">

In this way, you can easily access the static directory how to deploy it where and what you use. As for whether it will reduce efficiency and overload the server, I have not considered.

6 Everyone is welcome to give their opinions, leave comments, likes and critics

Guess you like

Origin blog.csdn.net/u014126257/article/details/105991336