runserver启动方式
一般来说,使用runserver方式启动方式,对静态文件的加载无需做什么处理,Django会自动对路由进行处理。但是在将debug=False
后会发现会出现静态文件丢失的现象。
这是因为在debug=False
后,django.contrib.staticfiles
会自动关闭,Django不会再自动搜索静态文件,若想要继续使用Django对静态文件进行路由,可以参考官方文档的做法,在urls.py中添加静态路由。
# settings.py
# e.g.
STATIC_URL = "/static/"
STATIC_ROOT = "/var/www/example.com/static/"
# urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
这种方式的使用需要提前将所有的静态文件搜集到指定的STATIC_ROOT
目录下,可以使用python manage.py collectstatic
将静态文件收集到STATIC_ROOT
目录下。
在开发过程中,也可以使用django.views.static.serve()
视图来对静态文件进行路由。
# settings.py
# e.g.
STATIC_URL = "/static/"
STATIC_ROOT = "/var/www/example.com/static/"
# urls.py
from django.conf import settings
from django.views import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
url(r'^static/(?P<path>.*)$', static.serve, {'document_root': settings.STATIC_ROOT}, name='static'),
]
这种方法一般可以用于用户对上传静态文件路由
另外要注意两种方法的导入
from django.conf.urls.static import static
和from django.views import static
的路径不一样。(不要问为什么会特别提一下,都是泪~~~)
uWsgi启动
uWsgi默认是不处理静态文件的,但是可以在uwsgi.ini中使用static-map
属性来实现对静态文件的路由。
[uwsgi]
# ... 其他的一些配置 ...
# 让uWSGI支持静态文件
static-map = /static=/srv/django/static
和上面的一样要提前收集所有静态文件到指定的static-map目录下
uWsgi + Nginx启动方式 (推荐)
之前说到了,uWsgi默认是不处理静态文件。除了使用上面介绍的方式,还可以使用nginx处理静态文件。
server
{
listen 80;
# 域名 e.g. cc.example.xyz
server_name cc.example.xyz;
location /static {
# 静态文件路由指定路由文件所在目录
# e.g. 静态文件在 /proj/static
alias /proj/static;
}
location / {
include uwsgi_params;
uwsgi_pass 0.0.0.0:8001;
}
#禁止访问的文件或目录
location ~ ^/(\.user.ini|\.htaccess|\.git|\.svn|\.project|LICENSE|README.md)
{
return 404;
}
access_log /data/log/nginx/cc.example.xyz.log;
error_log /data/log/nginx/cc.example.xyz.error.log;
}
[uwsgi]
# ... 其他的一些配置 ...
socket = 0.0.0.0:8001
module = conf.wsgi
如uwsgi启动的8001端口,nginx 设置
uwsgi_pass 0.0.0.0:8001;
,另外记得是socket如果http好像不行
更多笔记可以访问我的blog网站