zoukankan      html  css  js  c++  java
  • [Django基础] gunicorn启动django时静态文件的加载

    目前在用nginx+gunicorn对django进行部署

    当我用gunicorn -w 4 -b 127.0.0.1:8080 myproject.wsig:application启动django时访问主页却发现所有static文件夹下的静态文件都找不到,部分如下:

    Not Found: /static/js/app.min.js
    Not Found: /static/js/custom.js
    Not Found: /static/img/user1.jpg
    Not Found: /static/plugins/bootstrap/js/bootstrap.min.js
    Not Found: /static/plugins/morris/raphael-2.1.0.min.js
    Not Found: /static/plugins/jquery-ui-1.11.0.custom/jquery-ui.js
    Not Found: /static/js/sb-admin.js
    Not Found: /static/js/app.min.js

    用python manage.py runserver启动时是没有问题的(可以见上一篇文章django解决静态文件依赖问题以及前端引入方式),

    搜了一下午终于找到了解决方法(详见),即在urls中添加以下代码

    from django.contrib.staticfiles.urls import staticfiles_urlpatterns
    
    # ... the rest of your URLconf goes here ...
    
    urlpatterns += staticfiles_urlpatterns()

    ---------------------------------------------不知道要分割啥的分割线------------------------------------------
    看一下源码,该方法返回一个static类

    from django.conf import settings
    from django.conf.urls.static import static
    from django.contrib.staticfiles.views import serve
    
    urlpatterns = []
    
    def staticfiles_urlpatterns(prefix=None):
        """
        Helper function to return a URL pattern for serving static files.
        """
        if prefix is None:
            prefix = settings.STATIC_URL #这里 static_url = '/static/'
        return static(prefix, view=serve)
    
    # Only append if urlpatterns are empty
    if settings.DEBUG and not urlpatterns:
        urlpatterns += staticfiles_urlpatterns()

    再看一下这个static

    def static(prefix, view=serve, **kwargs):
        """
        Helper function to return a URL pattern for serving files in debug mode.
    
        from django.conf import settings
        from django.conf.urls.static import static
    
        urlpatterns = [
            # ... the rest of your URLconf goes here ...
        ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
        """
        # No-op if not in debug mode or an non-local prefix
        if not settings.DEBUG or (prefix and '://' in prefix):
            return []
        elif not prefix:
            raise ImproperlyConfigured("Empty static prefix not permitted")
       #
    Serve static files below a given point in the directory structure.
      return [ url(r'^%s(?P<path>.*)$' % re.escape(prefix.lstrip('/')), view, kwargs=kwargs), ]

    这里view=server就不细看了,其中心思想即把目录结构中的静态文件挂载到一个给定的路径上,这样前端html中的link或者src属性就能根据这一路径找到目标文件。

    DONE.

  • 相关阅读:
    JavaScript算法学习:获取字符串最后一位方法及判断是否以指定字符串开始或结尾
    前端基础知识学习笔记
    JavaScript算法练习:找出字符串中最长的单词并输出其长度
    HTML+CSS学习笔记
    Mint-ui中loadmore(上拉加载下拉刷新)组件在ios中滑动会触发点击事件的解决方法
    JavaScript中的DOM,BOM详细介绍;
    web前端面试题目整理
    Charles https乱码处理
    String类的三个参数的构造方法
    java.net包中的URL类
  • 原文地址:https://www.cnblogs.com/halleluyah/p/9647014.html
Copyright © 2011-2022 走看看