uwsgi部署Django

uwsgi部署Django

此处省去安装Django的步骤,可以参考Django初体验

项目开发

  • 创建项目
cd /var/www/
django-admin.py startproject xhope
cd /xhope

|-- xhope
|   |-- __init__.py
|   |-- settings.py
|   |-- urls.py
|   `-- wsgi.py
`-- manage.py

初始化目录如上所示。

  • 添加项目功能

a. 在settings.py添加模块blog,同时配置mysql数据库

b. 添加视图views.py

from django.http import HttpResponse
import json
from blog.models import wp_posts
from PyJSONSerialization import dump #别人写的插件 Object-->Json String
from django.shortcuts import render

def listPosts(request):

    request.encoding='utf-8'
    if 'post_title' in request.GET:
        post_title =  request.GET['post_title'].encode('utf-8')
    else:
        post_title = ''

    #print post_title
    posts = wp_posts.objects.filter(post_status='publish',post_type='post',post_title__contains='%s'%(post_title)).order_by("-id")

    '''
    print isinstance(posts, list)

    postsArr = [];
    for post in posts:
        postsArr.append(post)

    print dump(postsArr)
    '''
    context = {}
    context['posts'] = posts
    context['post_title'] = post_title
    return render(request, 'list.html', context)

c. 添加模型 models.py

from __future__ import unicode_literals
from django.db import models
import json

# Create your models here.
class wp_posts(models.Model):
    class Meta:
        db_table = "wp_posts"

    post_date = models.DateField
    post_title = models.CharField(max_length=20)
    post_status = models.CharField(max_length=20)
    post_type = models.CharField(max_length=20)

    id = models.AutoField

d. 配置访问路径urls.py

from django.conf.urls import *
from blog.views import listPosts

urlpatterns = patterns("",
    ('^listPosts/$', listPosts),
)

f. 模板文件 list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>list</title>
    <style>
        ul, li {
            border: 0;
            margin: 0;
            padding:0;
        }

        li {
            font-size: 13px;
            font-family: "黑体";
            padding: 2px;
        }
    </style>
</head>
<body>
    <form action="http://121.42.151.190:8000/listPosts/">
        <input type="text" name="post_title" value="{{post_title}}" /><button>查询</button>
    </form>

    <ul>
        {% for post in posts %}
        <li>{{ post.post_title }}</li>
        {% endfor %}
    </ul>
</body>
</html>

测试运行

python manage.py runserver 0.0.0.0:8000

访问地址:http://121.42.151.190:8000/listPosts

uWSGI部署Django

uwsgi --http :8000 --chdir /var/www/xhope/ --wsgi-file /var/www/xhope/xhope/wsgi.py --daemonize=/var/www/xhope/uwsgi9090.log

访问地址:http://121.42.151.190:8000/listPosts

Django Nginx+uwsgi 安装配置 参照http://www.runoob.com/django/django-nginx-uwsgi.html
但我一直没有执行成功过。