uwsgi啟動Django應用
uWSGI是一個Web服務器,它實現了WSGI協議、uwsgi、http等協議。
WSGI / uwsgi / uWSGI 三者區別:
WSGI是一種通信協議,Flask,webpy,Django、CherryPy等等都自帶WSGI,不過性能都不好。
uwsgi同WSGI一樣是一種通信協議。
uWSGI是實現了uwsgi和WSGI兩種協議的Web服務器。
自己配置
uwsgi.ini
# mysite_uwsgi.ini file [uwsgi] # Django-related settings # the base directory (full path) # 指定運行目錄 chdir = /home/log_collect_statistics # Django's wsgi file # 載入wsgi-file # wsgi-file=log_collect_statistics/uwsgi.ini #項目目錄下的uwsgi.ini module= log_collect_statistics.wsgi:application home = /opt/python buffer-size = 65536 # process-related settings # master # 允許主進程存在 master = true # maximum number of worker processes # 開啟的進程數量 # workers 開啟的進程數量,等同於processes(官網的說法是spawn the specified number of workers / processes) processes = 4 # the socket (use the full path to be safe # 地址和端口號,例如:socket = 127.0.0.1:50000 socket = :8080 #http= 192.168.8.192:8081 #http-socket = 192.168.8.192:8081 #http://60.205.211.11 172.17.36.8 # ... with appropriate permissions - may be needed # chmod-socket = 664 # clear environment on exit #http-socket = 172.17.36.8:8081 enable-threads = true # 當服務器退出的時候自動清理環境,刪除unix socket文件和pid文件(try to remove all of the generated file/sockets) vacuum = true # 存放進程編號的文件 pidfile=uwsgi.pid # 日志文件,因為uwsgi可以脫離終端在后台運行,日志看不見。我們以前的runserver是依賴終端的 # 使進程在后台運行,並將日志打到指定的日志文件或者udp服務器(daemonize uWSGI)。實際上最常用的,還是把運行記錄輸出到一個本地文件上 daemonize=logs/uwsgi.log # 以固定的文件大小(單位KB),切割日志文件。 例如:log-maxsize = 50000000 就是50M一個日志文件。 log-maxsize = 50000000 # 不記錄請求信息的日志。只記錄錯誤以及uWSGI內部消息到日志中。如果不開啟這項,那么你的日志中會大量出現請求記錄 disable-logging = true
nginx.conf
upstream django { server 127.0.0.1:8080; # 8081 } server { listen 18000; server_name localhost; #charset koi8-r; charset utf-8; access_log logs/django.access.log main; location / { #root html; #index index.html index.htm; include uwsgi_params; uwsgi_pass django; uwsgi_read_timeout 2; } location /static/{ alias /home/log_collect_statistics/all_static; expires 30d; autoindex on; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
settings.py
""" Django settings for log_collect_statistics project. Generated by 'django-admin startproject' using Django 2.1.15. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '--1k(694cyc_6s7r=7!hp25km_2*hp^j$b&hm(3%+ydq68_se4' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # 允許所有域名訪問 ALLOWED_HOSTS = ["*"] # Application definition # App列表 INSTALLED_APPS = [ 'django.contrib.admin', # 內置后台管理系統 'django.contrib.auth', # 內置用戶認證系統 'django.contrib.contenttypes', # 記錄項目中所有的model元數組(Django 的 ORM框架) 'django.contrib.sessions', # session會話功能, 用於標識當前訪問網站用戶身份,記錄像相關用戶信息 'django.contrib.messages', # 消息提示功能 'django.contrib.staticfiles', # 查詢靜態資源路徑 'app.apps.AppConfig', 'user.apps.UserConfig', ] # 中間件 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', # 內置的安全機制,保護用戶與網站的通信安全 'django.contrib.sessions.middleware.SessionMiddleware', # 會話session功能 'django.middleware.locale.LocaleMiddleware', # 使用中文 'django.middleware.common.CommonMiddleware', # 處理請求信息,規范化請求內容 'django.middleware.csrf.CsrfViewMiddleware', # 開啟CSRF防護功能 'django.contrib.auth.middleware.AuthenticationMiddleware', # 開啟內置的用戶認證系統 'django.contrib.messages.middleware.MessageMiddleware', # 開啟內置的信息提示功能 'django.middleware.clickjacking.XFrameOptionsMiddleware', # 防止惡意程序點擊劫持 'log_collect_statistics.middlewares.cors.Mymiddle', 'log_collect_statistics.middlewares.ExceptionLoggingMiddleware.ExceptionLoggingMiddleware', ] ROOT_URLCONF = 'log_collect_statistics.urls' # 模板配置 TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', # 定義模板引擎,用於識別模板里面的變量和指令 'DIRS': [os.path.join(BASE_DIR, 'templates'), ], # 設置模板所在路徑 'APP_DIRS': True, # 是否在APP里面查找模板文件 'OPTIONS': { # 用於填充在RequestContext中上下文的調用函數,一般情況不做任何修改 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'log_collect_statistics.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases # 數據庫配置 if DEBUG: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # 鏈接數據庫的類型 'NAME': 'log_collect', # 鏈接數據庫的名字 'HOST': '192.168.10.5', # 數據庫主機地址 'PORT': 3306, # 數據庫端口 'USER': 'wzy', # 數據庫用戶名 'PASSWORD': 'root1234', # 數據庫密碼 }, 'my_sqlite3': { 'ENGINE': 'django.db.backends.sqlite3', # 鏈接數據庫的類型 'NAME': os.path.join(BASE_DIR, 'sqlite3'), # 鏈接數據庫的名字 } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' # 時區配置 # TIME_ZONE = 'UTC' TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_L10N = True USE_TZ = True # 配置自定義用表 MyUser AUTH_USER_MODEL = 'user.MyUser' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ # 默認靜態文件在app的static目錄下 是app列表中django.contrib.staticfiles實現的 STATIC_URL = '/static/' # 在服務器上部署,實現服務器和項目之間的映射,主要是收集整個項目的靜態資源,並存放在一個新的文件夾,然后由該文件與服務器之間構建映射關系 # 主要用於項目部署 # STATIC_ROOT = os.path.join(BASE_DIR, 'all_static'), # 將靜態文件配置在系統根目錄下 STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] # rabbitMq 的配置信息 if DEBUG: RABBIT_HOST = '192.168.10.10' QUEUE_TOPIC = 'logs' RABBIT_USERNAME = 'wzy' RABBIT_PASSWORD = 'root1234' else: RABBIT_HOST = '192.168.10.10' QUEUE_TOPIC = 'logs' RABBIT_USERNAME = 'wzy' RABBIT_PASSWORD = 'root1234' LOG_ROOT = os.path.join(BASE_DIR, 'logs') + os.sep # 日志存儲路徑 if DEBUG: # 日志記錄 LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '%(asctime)s [%(name)s:%(lineno)d][%(module)s:%(funcName)s] [%(levelname)s]- %(message)s'}, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': LOG_ROOT + 'all.log', 'maxBytes': 1024*1024*5, # 文件大小 'backupCount': 10, # 備份份數 'formatter': 'standard', }, 'info': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': LOG_ROOT + 'info.log', 'maxBytes': 1024*1024*5, # 文件大小 'backupCount': 10, # 備份份數 'formatter': 'standard', }, 'error': { 'level': 'WARNING', 'class': 'logging.handlers.RotatingFileHandler', 'filename': LOG_ROOT + 'error.log', 'maxBytes': 1024*1024*5, # 文件大小 'backupCount': 10, # 備份份數 'formatter': 'standard', }, }, # 字別的模塊中使用使用 import logging logger = logging.getLogger('django') getLogger 中的變量為 以下配置中內容 'loggers': { 'django': { 'handlers': ['file', 'console'], 'propagate': True, }, 'inf': { 'handlers': ['info', 'console'], 'level': 'INFO', 'propagate': True, }, 'err': { 'handlers': ['error', 'console'], 'level': 'WARNING', 'propagate': True, }, # 查看數據庫執行代碼 'django.db.backends': { 'handlers': ['console', ], 'propagate': True, 'level': 'DEBUG', }, }, } else: # 日志記錄 LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '%(asctime)s [%(name)s:%(lineno)d][%(module)s:%(funcName)s] [%(levelname)s]- %(message)s'}, }, 'handlers': { 'console': { 'level': 'INFO', # DEBUG 'class': 'logging.StreamHandler', }, 'file': { 'level': 'INFO', # DEBUG 'class': 'logging.handlers.RotatingFileHandler', 'filename': LOG_ROOT + 'all.log', 'maxBytes': 1024 * 1024 * 5, # 文件大小 'backupCount': 10, # 備份份數 'formatter': 'standard', }, 'info': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': LOG_ROOT + 'info.log', 'maxBytes': 1024 * 1024 * 5, # 文件大小 'backupCount': 10, # 備份份數 'formatter': 'standard', }, 'error': { 'level': 'WARNING', 'class': 'logging.handlers.RotatingFileHandler', 'filename': LOG_ROOT + 'error.log', 'maxBytes': 1024 * 1024 * 5, # 文件大小 'backupCount': 10, # 備份份數 'formatter': 'standard', }, }, # 字別的模塊中使用使用 import logging logger = logging.getLogger('django') getLogger 中的變量為 以下配置中內容 'loggers': { 'django': { 'handlers': ['file', 'console'], 'propagate': True, }, 'inf': { 'handlers': ['info', 'console'], 'level': 'INFO', 'propagate': True, }, 'err': { 'handlers': ['error', 'console'], 'level': 'WARNING', 'propagate': True, }, # 查看數據庫執行代碼 'django.db.backends': { 'handlers': ['console', ], 'propagate': True, 'level': 'DEBUG', }, }, }
1.安裝uWSGI
pip install uwsgi
2.查找安裝的uwsgi位置
find / -name uwsgi
3.建立一個軟連接
ln -r uwsgilujing /usr/bin/uwsgi
4.在應用目錄,也就是manage.py所在目錄下

vi uwsgi.ini[uwsgi]
#使用nginx連接時使用,Django程序所在服務器地址
# socket=ip:80
#直接做web服務器使用,Django程序所在服務器地址
http=ip:80 注意:我用的騰訊雲服務器,ip填寫的是內網地址,不然報錯bind(): Cannot assign requested address [core/socket.c line 769]
#項目目錄
chdir=/root/program/WxFindInfo/mysite/
#項目中wsgi.py文件的目錄,相對於項目目錄
wsgi-file=mysite/wsgi.py
# 進程數
processes=4
# 線程數
threads=2
# uwsgi服務器的角色
master=True
# 存放進程編號的文件
pidfile=uwsgi.pid
# 日志文件,因為uwsgi可以脫離終端在后台運行,日志看不見。我們以前的runserver是依賴終端的
daemonize=uwsgi.log
5.啟動uWSGI服務器
uwsgi --ini uwsgi.ini
6.停止
uwsgi --stop uwsgi.pid/kill -9 pid
7.重啟
uwsgi --reload uwsgi.pid
# mysite_uwsgi.ini file [uwsgi] # Django-related settings # the base directory (full path) chdir = /root/logsystem # Django's wsgi file #module = myshop.wsgi #testd����Ŀ���ƣ���testd.wsgi������ô�漲��д����û������ļ� module= logsystem.wsgi:application #static-map = /static=/root/logsystem/all_static_collect buffer-size = 65536 # process-related settings # master master = true # maximum number of worker processes processes = 2 # the socket (use the full path to be safe socket = 127.0.0.1:8081 #http= 192.168.8.192:8081 #http-socket = 192.168.8.192:8081 #http://60.205.211.11 172.17.36.8 # ... with appropriate permissions - may be needed # chmod-socket = 664 # clear environment on exit #http-socket = 172.17.36.8:8081 enable-threads = true mule = common/dbutil.py vacuum = true
user root; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for"'; #access_log logs/access.log main; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; #gzip on; upstream django { #server unix:///path/to/your/mysite/mysite.sock; # server 127.0.0.1:8080; # 8081 } server { listen 80; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location / { #root html; #index index.html index.htm; include /usr/local/nginx/conf/uwsgi_params; uwsgi_pass django; } location /static/{ alias /root/logsystem/static_collect/; expires 30d; autoindex on; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # #location ~ \.php$ { # root html; # fastcgi_pass 127.0.0.1:9000; # fastcgi_index index.php; # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; # include fastcgi_params; #} # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { # deny all; #} } # another virtual host using mix of IP-, name-, and port-based configuration # #server { # listen 8000; # listen somename:8080; # server_name somename alias another.alias; # location / { # root html; # index index.html index.htm; # } #} # HTTPS server # #server { # listen 443 ssl; # server_name localhost; # ssl_certificate cert.pem; # ssl_certificate_key cert.key; # ssl_session_cache shared:SSL:1m; # ssl_session_timeout 5m; # ssl_ciphers HIGH:!aNULL:!MD5; # ssl_prefer_server_ciphers on; # location / { # root html; # index index.html index.htm; # } #} }