在 Ubuntu 14.x 搭建 Nginx Uwsgi Django 环境之(三):连接 nginx 和 uwsgi

xiaoxiao2021-02-27  320

1、编写django_wsgi.py文件,将其放在与文件manage.py同一个目录下。

注意: 编写文件时需要注意语句os.environ.setdefault。比如,如果你的项目为mydjangosite,则你的语句应该是 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mydjangosite.settings") #!/usr/bin/env python # coding:utf-8 import os import sys DJANGO_PATH = '/disk1/pythonVirtualEnv/python3.4.3/lib/python3.4/site-packages' print("DJANGO_PATH", DJANGO_PATH) sys.path.append(DJANGO_PATH) import django from django.core.handlers.wsgi import WSGIHandler from imp import reload reload(sys) #sys.setdefaultencoding('utf8') no need for python3.x os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mydjangosite.settings") django.setup() application = WSGIHandler() 这一步踩了好多坑,网上好多这个文件都是python2.x版本的,到3.x还需要改,上面的这个文件就是基于3.x的文件 出现的错误找不到django模块,可以通过sys.path.append(DJANGO_PATH)将路径加入 sys.setdefaultencoding('utf8')这个语句在2.x才有,3.x是不需要的 django.setup()这个函数3.x才需要,而且必须在在os.environ.setdefault之后调用

2、连接django和uwsgi,实现简单的WEB服务器

我们假设你的Django项目的地址是/home/ubuntu/mydjangosite 然后,就可以执行以下命令: uwsgi --http-socket :8003 --chdir /home/ubuntu/mydjangosite --module django_wsgi 功能通过浏览器就能访问服务器的8003端口了

3、配置uwsgi:在/home/ubuntu/mydjangosite创建文件 uwsgi.ini

这个配置文件是uwsgi单独对外提供http服务的配置文件,用这个配置文件的话nginx是无法和它连接成功的,因为nginx和uwsgi需要用非标准的uwsgi协议

[uwsgi]

http-socket =  :8011 chdir = /home/ubuntu/mydjangosite module = django_wsgi daemonize = django_wsgi.log

<processes>1</processes>

下面这个配置文件是和nginx连接时用的:

[uwsgi] socket = /home/ubuntu/mydjangosite/uwsgi.sock #socket = :8011 chdir = /home/ubuntu/mydjangosite module = django_wsgi daemonize = django_uwsgi.log chmod-sokcet = 666 #wsgi-file = django_wsgi.py #plugin = python #process = 2 #threads = 2 #stats = 127.0.0.1:8011

4、配置nginx参数

upstream django {     server unix:/home/ubuntu/mydjangosite/uwsgi.sock; # for a file socket     # server 127.0.0.1:8011; # for a web port socket (we'll use this first) } # configuration of the server server {     # the port your site will be served on     listen      801;     # the domain name it will serve for     server_name www.biseg.cc biseg.cc; # substitute your machine's IP address or FQDN     charset     utf-8;     # Django media     location /media  {         alias /home/ubuntu/mydjangosite/myjangosite/media;     }     location /static {         alias /home/ubuntu/mydjangosite/myjangosite/static;     }     # Finally, send all non-media requests to the Django server.     location / {         uwsgi_pass  django;         include     uwsgi_params;     } }

5、启动ngixn, sudo service nginx start

启动uwsgi, 切换到目录/home/ubuntu/mydjangosite uwsgi --ini uwsgi.ini

启动nginx, sudo service nginx start

这是通过浏览器访问 网站的801端口就能看到提示 “Congratulations on your first Django-powered page.”

配置基本都是按照下面这两个教程来的 https://uwsgi-docs.readthedocs.org/en/latest/tutorials/Django_and_nginx.html https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/uwsgi/
转载请注明原文地址: https://www.6miu.com/read-7185.html

最新回复(0)