uwsgi启动Django应用

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;
    #    }
    #}

}
原文地址:https://www.cnblogs.com/xiao-xue-di/p/13719359.html