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.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM