Django空页单独加载需要2秒

时间:2015-07-20 10:25:44

标签: django nginx

我正在使用谷歌计算引擎上的nginx进行我的django项目。

我的观看文件是,

from django.shortcuts import render_to_response

def home(request):
    return render_to_response('html/index.html',RequestContext(request))    

和我的模板文件index.html

<html>
<head>
<title> Home </title>
</head>
<body>
Wel come to my new project
</body>
</html>

单独调用此页面需要2.75秒才能完全加载到我的服务器上。

FFTB需要1.8秒(等待时间) 此延迟是否存在任何配置问题?

我的设置文件

"""
Django settings for audiotube project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os


#Base root is for outside of the project structure
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

rsa_private_key = BASE_DIR + "/lib/rsa/id_rsa"

#Package root is for inside the project
PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '46=+9k)k25rb(b9&&wy9y_xtn3rx2stl#%+0-5o-$-un9o&4hn'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True


TEMPLATE_DEBUG = True
THUMBNAIL_DEBUG = True


ALLOWED_HOSTS = ['localhost','example.com', '*']


# Application definition

INSTALLED_APPS = (
    #This is for the site name and inbuild framework
    'django.contrib.sites',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app0',
    'app1',
    'ckeditor',
    'social.apps.django_app.default',
    'sorl.thumbnail',
    'compressor',
    'template_timings_panel',

)
COMPRESS_ENABLED = True

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    # other finders..
    'compressor.finders.CompressorFinder',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',    
)

ROOT_URLCONF = 'mysite.urls'

WSGI_APPLICATION = 'mysite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydb',
        'USER': 'root',
        'PASSWORD': 'password',
        'HOST': 'hostingaddre',
        'PORT': '',
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = None

USE_I18N = True

USE_L10N = True

USE_TZ = True

SITE_ID = 1

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_ROOT = '/home/mysite/staticfiles/'


STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = [
    os.path.join(PACKAGE_ROOT, "static"),
]

MEDIA_ROOT = os.path.join(PACKAGE_ROOT, "site_media", "media")

MEDIA_URL = '/media/'

# List of callables that know how to import templates from various sources.



TEMPLATE_DIRS = [
    os.path.join("templates"),
]


#Template context processors



TEMPLATE_CONTEXT_PROCESSORS = (
    "django.core.context_processors.request",
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.core.context_processors.tz",
    "django.contrib.messages.context_processors.messages",
    'social.apps.django_app.context_processors.backends',
    'social.apps.django_app.context_processors.login_redirect',
)


# This two setting needed for downloading CKEDITOR

CKEDITOR_JQUERY_URL = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'

CKEDITOR_UPLOAD_PATH = "uploads/"

CKEDITOR_IMAGE_BACKEND = "pillow"

CKEDITOR_CONFIGS = {
    'default': {
        'toolbar': 'UltraFull',
        'height': 300,
        'toolbar_UltraFull': [
            ['Font', 'FontSize', 'Format'],
            ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat'],
            [
                'NumberedList', 'BulletedList', '-',
                'Outdent', 'Indent', '-',
                'Blockquote', '-',
                'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'
            ],
            ['Link', 'Unlink', 'Anchor'],
            ['Image', 'Flash', 'Table', 'HorizontalRule', 'PageBreak', 'Smiley', 'SpecialChar'],
            ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'],
            ['TextColor', 'BGColor'],
            ['Maximize', 'Source'],
        ],        
        'toolbarCanCollapse': False,
    },
    'awesome_ckeditor': {
        'toolbar': 'UltraFull',
        'height': 300,
        'toolbar_UltraFull': [
            ['Font', 'FontSize', 'Format'],
            ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat'],
            [
                'NumberedList', 'BulletedList', '-',
                'Outdent', 'Indent', '-',
                'Blockquote', '-',
                'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'
            ],
            ['Link', 'Unlink', 'Anchor'],
            ['Image', 'Flash', 'Table', 'HorizontalRule', 'PageBreak', 'Smiley', 'SpecialChar'],
            ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'],
            ['TextColor', 'BGColor'],
            ['Maximize', 'Source'],
        ],        
        'toolbarCanCollapse': False,
    },
}



AUTHENTICATION_BACKENDS = (
    'users.backends.EmailAuthBackend',
    'social.backends.facebook.FacebookOAuth2',
    'social.backends.google.GoogleOAuth2',
    'social.backends.twitter.TwitterOAuth',
    'django.contrib.auth.backends.ModelBackend',
    )
SOCIAL_AUTH_FACEBOOK_KEY ="XXXXXXXXXXXXX"
SOCIAL_AUTH_FACEBOOK_SECRET ="XXXXXXXXXXXXX"
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY ="XXXXXXXXXXXXX"
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = "XXXXXXXXXXXXX"
SOCIAL_AUTH_FORCE_EMAIL_VALIDATION = True



EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

SITE_URL="http://example.com:8000/"


'''
#Use this for exception handling
SOCIAL_AUTH_PIPELINE = (
    'social.pipeline.social_auth.associate_by_email',

)
'''

SOCIAL_AUTH_PIPELINE = (
    'social.pipeline.social_auth.social_details',
    'social.pipeline.social_auth.social_uid',
    'social.pipeline.social_auth.auth_allowed',
    'social.pipeline.social_auth.social_user',
    'social.pipeline.user.get_username',
    'users.pipeline.require_email',
    #'social.pipeline.mail.mail_validation',
    'social.pipeline.user.create_user',
    'users.pipeline.save_profile',
    'social.pipeline.social_auth.associate_user',
    'social.pipeline.social_auth.load_extra_data',
    'social.pipeline.user.user_details',
    #'social.pipeline.debug.debug'
)

# login redirect urls
LOGIN_URL = "/signin"
LOGIN_REDIRECT_URL = "/dashboard"
DOMAIN = "http://example.com:8000"



if DEBUG:
    INTERNAL_IPS = ('127.0.0.1',)
    MIDDLEWARE_CLASSES += (
        'debug_toolbar.middleware.DebugToolbarMiddleware',
    )

    INSTALLED_APPS += (
        'debug_toolbar',
    )

    DEBUG_TOOLBAR_PANELS = (
    'template_timings_panel.panels.TemplateTimings.TemplateTimings',
        'debug_toolbar.panels.version.VersionDebugPanel',
        'debug_toolbar.panels.timer.TimerDebugPanel',
    'debug_toolbar.panels.sql.SQLPanel',
        #'debug_toolbar.panels.settings_vars.SettingsVarsDebugPanel',
        'debug_toolbar.panels.headers.HeaderDebugPanel',
        #'debug_toolbar.panels.profiling.ProfilingDebugPanel',
        'debug_toolbar.panels.request_vars.RequestVarsDebugPanel',
        'debug_toolbar.panels.sql.SQLDebugPanel',
        'debug_toolbar.panels.template.TemplateDebugPanel',
        'debug_toolbar.panels.cache.CacheDebugPanel',
        'debug_toolbar.panels.signals.SignalDebugPanel',
        #'debug_toolbar.panels.logger.LoggingPanel',
    )

    DEBUG_TOOLBAR_CONFIG = {
        'INTERCEPT_REDIRECTS': False,
    }


PREPEND_WWW = True

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': '/var/tmp/django_cache',
    }
}


TEMPLATE_LOADERS = (
    ('django.template.loaders.cached.Loader', (
       'django.template.loaders.filesystem.Loader',
       'django.template.loaders.app_directories.Loader',
   )),
)

在example.com中,在/ etc / nginx / site-enabled和site-available

server {

    listen   80;
    server_name myservername.com;
    client_max_body_size 4G;


    error_page 502 =200 @maintenance;

    location @maintenance {
        root /path/to/static/offline/files;
        try_files $uri /index.html =503;
    }
   location /static/ {

       alias  /home/sim/5vs/staticfiles/;

    }

    location /media/ {
       alias  /home/sim/5vs/myproject/myproject/site_media/media/;
       expires 30d;
    }
    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;


    }
}                                 
nginx.conf文件中的

user root;
worker_processes 4;
pid /run/nginx.pid;

events {
    worker_connections 768;
    # multi_accept on;
}

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;



    gzip on;
    gzip_disable "msie6";


    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

您能告诉我为什么需要很长时间以及我的配置有什么问题。

使用Profiler

总时间:1.89419 s 文件:/home/staging/live/users/views.py 功能:第93行的comesoon_view

Line#命中每次命中时间%时间线内容

93                                           def comingsoon_view(request):
94         1            2      2.0      0.0     temp = {}
95         1      1894189 1894189.0    100.0    return render(request, 'pages/comingsoon.html',temp)

1 个答案:

答案 0 :(得分:0)

用户使用带有DEBUG = True设置的调试服务器来运行django项目。它启用了DEBUG工具栏 - 这真的很慢。这个设置是正常的时间。如果你禁用它 - 我认为一切都会好的。

如果您仍然遇到麻烦 - 我建议您检查django调试服务器响应时间(python manage.py runserver)。如果它更快,那么问题是nginx配置,或者,如果相同 - 你应该用lineprofiler检查时间。

如果是生产配置 - 请勿在生产中使用调试服务器。您应该使用gunicorn或类似的东西来运行django项目。