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
但我一直没有执行成功过。

The android.os.NetworkOnMainThreadException exception

The android.os.NetworkOnMainThreadException exception

Android与Web Server交换数据 碰到异常The android.os.NetworkOnMainThreadException exception

原始代码

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        myBtn = (Button) this.findViewById(R.id.myBtn);
        myText = (TextView) this.findViewById(R.id.myText);

        myBtn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {                        
                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet("http://localhost:8080/data.jsp");
                HttpResponse response;
                try {
                    response = client.execute(request);
                    // Get the response
                    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                    StringBuilder textView = new StringBuilder();

                    String line = "";
                    while ((line = rd.readLine()) != null) {
                        textView.append(line);
                    }
                    myText.setText(textView); //使用远程数据
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

     <Button 
        android:id="@+id/myBtn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Click Me" />

     <TextView
        android:id="@+id/myText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Hello Rick!!!" />

</LinearLayout>

启动本地Tomcat,访问地址:http://localhost:8080/data.jsp
data.jsp

Hello Android!!!!

<%
    System.out.println("Request from client!!!");
%>

期望:点击按钮“Click Me”,TextView由 “Hello Rick!!!” —> “Hello Android!!!!”,万万没想到,抛出了异常!!!

Google到解决方案http://www.lucazanini.eu/en/2012/android/the-android-os-networkonmainthreadexception-exception/

加权限,同时加了代码。
改动如下:

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

Activity.java

StrictMode.ThreadPolicy policy = new
                StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
                StrictMode.setThreadPolicy(policy);

结果后台没有抛出异常,但是没有任何反应,这个纠结了很久。。。。
后来发现: http://localhost:8080/data.jsp,不能使用localhost和127.0.0.1
只能使用机器内网IP:192.168.1.106,然后成功了。
解决地址:http://stackoverflow.com/questions/5495534/java-net-connectexception-localhost-127-0-0-18080-connection-refused

测试结果

http://xhope.top/wp-content/uploads/2016/01/Video_2016-01-30_230438.gif

Django初体验

Django初体验

教程:http://www.runoob.com/django/django-tutorial.html

省略安装过程

Python下有许多款不同的 Web 框架。Django是重量级选手中最有代表性的一位。许多成功的网站和APP都基于Django。
Django是一个开放源代码的Web应用框架,由Python写成。
Django遵守BSD版权,初次发布于2005年7月, 并于2008年9月发布了第一个正式版本1.0 。
Django采用了MVC的软件设计模式,即模型M,视图V和控制器C。
  1. 创建工程
django-admin startproject mysite

生成目录结构

    |-mysite
        |-urls.py
        |-settings.py
        |-wsgi.py
        |-__init__.py
     |-manage.py   

启动服务

D:\workspace\mysite>python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
December 27, 2015 - 21:27:18
Django version 1.9, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
  1. 添加模块
django startapp blog

生成目录结构

    |-blog
        |-__init__.py
        |-admin.py
        |-apps.py
        |-models.py
        |-tests.py
        |-view.py
    |-mysite
        |-urls.py
        |-settings.py
        |-wsgi.py
        |-__init__.py
     |-manage.py   

a. 配置模块 settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog'
]

b. 配置数据库

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'rtest',
        'USER': 'rick',
        'PASSWORD': 'jkxyx@05',
        'HOST':'192.168.1.105',
        'PORT':'3306',
    }
}

c. 添加模板文件夹

'DIRS': [BASE_DIR+"/templates"],
  1. 编写blog模块

a. 创建实体类Article
models.py

from __future__ import unicode_literals
from django.db import models
# Create your models here.

class Article(models.Model):
    title = models.CharField(max_length=20)
    author = models.CharField(max_length=20)
    content = models.CharField(max_length=20)

执行脚本自动创建数据库

D:\workspace\mysite>python manage.py makemigrations
No changes detected
D:\workspace\mysite>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, blog, contenttypes, auth, sessions
Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying blog.0001_initial... OK
  Applying sessions.0001_initial... OK

b. 创建视图
views.py

from django.shortcuts import render
from django.http import HttpResponse
from blog.models import Article

def hello(request):

    list = Article.objects.all()
    #print list
    #for art in list:
    #    print art.title
    context = {}
    context['object_list'] = list
    return render(request, 'hello.html', context)

hello.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>hello</title>
</head>
<body>
    <h2>book list</h2>
    <ul>
    {% for article in object_list %}
        <li>{{ article.author }} - {{ article.title }}</li>
    {% endfor %}
    </ul>
</body>
</html>

urls.py

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^hello/', hello),
]

数据库插入测试数据
http://xhope.top/wp-content/uploads/2015/12/11.png

访问地址:http://127.0.0.1:8000/hello/
http://xhope.top/wp-content/uploads/2015/12/2.png

Oracle物化视图权限问题

  • 用户A想刷新用户B的物化视图,必须拥有ALTER ANY MATERIALIZED VIEW 的权限
create tablespace users datafile 'c:\users.dbf' size 10M;

-- we'll create a user that will own the table and materialized view
create user user_a identified by user_a
quota unlimited on users;

-- grant him the privileges necessary for this test
grant create session, create table, create materialized view to user_a;

-- create the user that will be able to refresh user_a's mview
create user user_b identified by user_b;

grant create session, alter any materialized view to user_b;

-- now connect as user_a to create the objects
connect user_a/user_a

-- connected as user_a we create the table and the mview
create table a_table (x int primary key);
create materialized view a_mview as select * from a_table;

-- connect as user_b and refresh it
connect user_b/user_b
begin
dbms_mview.refresh('USER_A.A_MVIEW','c');
end;
/

http://www.itpub.net/thread-715807-1-1.html

Python中的继承

class Person(object):
    def __init__(self,name):
        self.__name = name
        print('Person: Constructor called')

    def getName(self):
        return self.__name

class Nation(object):
            """docstring for Chinese"""
            def __init__(self, nation):
                self.__nation = nation
                print('Nation: Constructor called')

            def getNation(self):
                return self.__nation



class Student(Person, Nation):
    def __init__(self, nation, name, score):
        print('Student: Constructor called')
        #super(Student, self).__init__(name) #super() only support single extend
        #super().__init__(name)

        Person.__init__(self,name) # 'ClassName.__init__(self)' support multiple extend
        Nation.__init__(self,nation)

        self.__score = score

    def getScore(self):
        return self.__score

person = Student('China','Rick',100)

print(person.getNation())
print(person.getName())                
print(person.getScore())