在Ubuntu上使用Nginx+uwsgi部署django

8 篇文章 0 订阅
4 篇文章 0 订阅

首先,安装nginx:sudo apt-get install nginx

然后,安装uwsgi:sudo apt-get install uwsgi uwsgi-plugin-python或者使用pip :sudo pip install uwsgi

测试uwsgi

在你的机器上写一个test.py

# test.py
def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    return "Hello World"

然后执行shell命令:

uwsgi --http :8001 --wsgi-file test.py

访问网页:

http://127.0.0.1:8001/

看在网页上是否有Hello World

如果报chdir() nosuch file or directory[core/uwsgi.c line 2581]之类的错:只要安装 apt-get install build-essential python-dev就可以了

使用 uwsgi 时都会碰到uwsgi: unrecognized option '--uwsgi-file'如 --module , --wsgi-file , --callable 等,最开 始我也碰到这样的问题, uwsgi --help 得到一大堆帮助信息(吐槽下, uWSGI 用户接口方面太不友好了,输出这么一大堆信息会吓着初学者,而且也 很难从中找到需要的帮助信息,要是你用管道加 less ,那我就无话可说了), 找了下发现的确没有这些选项,第一反应是版本对不上,后来发现相同版本也 会遇到这个问题,然后才找到问题的根源,需要在上面那些未识别选项前加上 --plugin python 来告诉 uWSGI 我在使用 python 插件,后面那些选项你 用python 插件去解析。

配置django

NOTE:

请保证你的django项目是正常使用的。可以使用

python manage.py runserver 0.0.0.0:8002

来测试一下你的django项目是否能正常跑起来。

请保证你的django程序已经关闭。

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

注意: 编写文件时需要注意语句os.environ.setdefault。比如,如果你的项目为mysite,则你的语句应该是 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#!/usr/bin/env python
# coding: utf-8

import os
import sys

# 将系统的编码设置为UTF8
reload(sys)
sys.setdefaultencoding('utf8')

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

from django.core.handlers.wsgi import WSGIHandler
application = WSGIHandler()

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

我们假设你的Django项目的地址是/home/work/src/sites/testdjango1/testdjango/mysite,

然后,就可以执行以下命令:

uwsgi --http :8000 --chdir /home/work/src/sites/testdjango1/testdjango/mysite --module django_wsgi

这样,你就可以在浏览器中访问你的Django程序了。所有的请求都是经过uwsgi传递给Django程序的

另外,为了实现Nginx与uWSGI的连接,两者之间将采用soket来通讯方式。

在本节中,我们将使用uWSGI配置文件的方式来改进uWSGI的启动方式。

假定你的程序目录是 /home/work/src/sites/testdjango1/testdjango/mysite

我们将要让Nginx采用8077端口与uWSGI通讯,请确保此端口没有被其它程序采用。

新建一个XML文件:

djangochina_socket.xml,将它放在 /home/work/src/sites/testdjango1/testdjango/mysite 目录下:

<uwsgi>
    <socket>:8077</socket>
    <chdir>/home/work/src/sites/testdjango1/testdjango/mysite</chdir>
    <module>django_wsgi</module>
    <processes>4</processes> <!-- 进程数 --> 
    <daemonize>uwsgi.log</daemonize>
</uwsgi>

在上面的配置中,我们使用 uwsgi.log 来记录日志,开启4个进程来处理请求。

这样,我们就配置好uWSGI了。

配置Nginx

我们假设你将会把Nginx程序日志放到你的目录/home/work/var/test/logs/下,请确保该目录存在。

我们假设你的Django的static目录是/home/work/src/sites/testdjango1/testdjango/collectedstatic/ , media目录是/home/work/src/sites/testdjango1/testdjango/public/media/,请确保这些目录存在。

我们假设你的域名是 www.you.com (在调试时你可以设置成你的机器IP)

我们假设你的域名端口是 80(在调试时你可以设置一些特殊端口如 8070)

基于上面的假设,我们为conf/nginx.conf添加以下配置

server {

        listen   80;
        server_name www.you.com;
        access_log /home/work/var/test/logs/access.log;
        error_log /home/work/var/test/logs/error.log;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
         include        uwsgi_params;
         uwsgi_pass     127.0.0.1:8077;
        }

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

        location /static/ {
            alias  /home/work/src/sites/testdjango1/testdjango/collectedstatic/;
            index  index.html index.htm;
        }

        location /media/ {
            alias  /home/work/src/sites/testdjango1/testdjango/public/media/;
        }
    }

在上面的设置后,可以让Nginx来处理静态文件(/static/ 和 /media/ )。非静态文件请求Nginx会发给 socket 8077,然后让uWSGI来进行处理。

Nginx+uWSGI+Django的实现方式

在完成上面配置后,需要按以下步骤来做:

  1. 重启Nginx服务器,以使Nginx的配置生效。

    nginx -s  reload
    

    重启后检查Nginx日志是否有异常。

  2. 启动uWSGI服务器

    cd /home/work/src/sites/testdjango1/testdjango/mysite
    
    uwsgi -x djangochina_socket.xml
    

    检查日志 uwsgi.log 是否有异常发现。

  3. 访问服务

    基于上面的假设你的域名是www.you.com

    因此,我们访问 www.you.com,如果发现程序与 单独使用Django启动的程序一模一样时,就说明成功啦!

  4. 如果打不开网页,可能是端口被占用,或者防火墙的问题

  5. 关闭服务的方法

    将uWSGi进程杀死即可。

  6. 遇到的错误

  7. uwsgi+django报错django.core.exceptions.AppRegistryNotReady

  8. 来源:http://www.aaini.com/

    File “/usr/lib/python2.7/site-packages/django/core/handlers/wsgi.py”, line 187, in __call__
    response = self.get_response(request)
    File “/usr/lib/python2.7/site-packages/django/core/handlers/base.py”, line 199, in get_response
    response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
    File “/usr/lib/python2.7/site-packages/django/core/handlers/base.py”, line 236, in handle_uncaught_exception
    return debug.technical_500_response(request, *exc_info)
    File “/usr/lib/python2.7/site-packages/django/views/debug.py”, line 91, in technical_500_response
    html = reporter.get_traceback_html()
    File “/usr/lib/python2.7/site-packages/django/views/debug.py”, line 350, in get_traceback_html
    return t.render(c)
    File “/usr/lib/python2.7/site-packages/django/template/base.py”, line 148, in render
    return self._render(context)
    File “/usr/lib/python2.7/site-packages/django/template/base.py”, line 142, in _render
    return self.nodelist.render(context)
    File “/usr/lib/python2.7/site-packages/django/template/base.py”, line 844, in render
    bit = self.render_node(node, context)
    File “/usr/lib/python2.7/site-packages/django/template/debug.py”, line 80, in render_node
    return node.render(context)
    File “/usr/lib/python2.7/site-packages/django/template/debug.py”, line 90, in render
    output = self.filter_expression.resolve(context)
    File “/usr/lib/python2.7/site-packages/django/template/base.py”, line 624, in resolve
    new_obj = func(obj, *arg_vals)
    File “/usr/lib/python2.7/site-packages/django/template/defaultfilters.py”, line 769, in date
    return format(value, arg)
    File “/usr/lib/python2.7/site-packages/django/utils/dateformat.py”, line 343, in format
    return df.format(format_string)
    File “/usr/lib/python2.7/site-packages/django/utils/dateformat.py”, line 35, in format
    pieces.append(force_text(getattr(self, piece)()))
    File “/usr/lib/python2.7/site-packages/django/utils/dateformat.py”, line 268, in r
    return self.format(‘D, j M Y H:i:s O’)
    File “/usr/lib/python2.7/site-packages/django/utils/dateformat.py”, line 35, in format
    pieces.append(force_text(getattr(self, piece)()))
    File “/usr/lib/python2.7/site-packages/django/utils/encoding.py”, line 85, in force_text
    s = six.text_type(s)
    File “/usr/lib/python2.7/site-packages/django/utils/functional.py”, line 144, in __text_cast
    return func(*self.__args, **self.__kw)
    File “/usr/lib/python2.7/site-packages/django/utils/translation/__init__.py”, line 83, in ugettext
    return _trans.ugettext(message)
    File “/usr/lib/python2.7/site-packages/django/utils/translation/trans_real.py”, line 325, in ugettext
    return do_translate(message, ‘ugettext’)
    File “/usr/lib/python2.7/site-packages/django/utils/translation/trans_real.py”, line 306, in do_translate
    _default = translation(settings.LANGUAGE_CODE)
    File “/usr/lib/python2.7/site-packages/django/utils/translation/trans_real.py”, line 209, in translation
    default_translation = _fetch(settings.LANGUAGE_CODE)
    File “/usr/lib/python2.7/site-packages/django/utils/translation/trans_real.py”, line 189, in _fetch
    “The translation infrastructure cannot be initialized before the ”
    django.core.exceptions.AppRegistryNotReady: The translation infrastructure cannot be initialized before the apps registry is ready. Check that you don’t make non-lazy gettext calls at import time.

    参照网上用uwsgi+nginx配置python环境时,报了这么个错,google发现是WSGI application的问题,好象是因为django升级,配置有所变化。

    原来:

    import django.core.handlers.wsgi

    application = django.core.handlers.wsgi.WSGIHandler()

    改成:

    from django.core.wsgi import get_wsgi_application

    application = get_wsgi_application()

    重启一下uwsgi。

    网上找来的解决办法,希望有帮助。

    后补:也可能是python版本和django版本不兼容问题,重新安装django并选定安装的版本就可以了

参考链接:http://www.linuxidc.com/Linux/2015-04/116397.htm


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值