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())

简单shell字符菜单模拟

  • menu.sh
#!/bin/bash
#menu.sh


function menu() {
    title="My Menu"
    url="www.xhope.top"
    time=`date +%Y-%m-%d`
    cat << eof
#############################################
                 `echo -e "\033[32;40m$title\033[0m"`
#############################################
*   1) Add a user
*   2) Set password for user
*   3) Delete a user
*   4) Print disk space
*   5) Print men space
*   6) Quit
*   7) Return main menu
#############################################
$url                   $time
#############################################
eof
}
  • index.sh
#!/bin/bash
#index.sh

. menu.sh  #include menu.sh
clear

menu #call menu function

while [[ true ]]; do

    read -p "Please type a  option:" option
    #echo $option

    case $option in
        1 )
            read -p "Please type username:" username
            useradd $username &>/dev/null
            if [[ $? -eq 0 ]]; then
                echo "user $username is created successfully"
            else
                echo "user $username is created failed"
            fi
        ;;
        2 )
            read -p "Please type pass username:" name
            read -p "Please type password:" pass

            echo $pass | passwd --stdin $name &>/dev/null

            if [[ $? -eq 0 ]]; then
                echo "user $username password set successfully"
            else
                echo "user $username password set failed failed"
            fi
        ;;
        3 )
            read -p "Please type username:" username
            userdel -r $username &>/dev/null
            if [[ $? -eq 0 ]]; then
                echo "user $username is deleted successfully"
            else
                echo "user $username is deleted failed"
            fi
        ;;
        4 )
            str=`df -Th`
            echo -e "\033[30;47m$str\033[0m"
        ;;
        5 )
            str=`free`
            echo -e "\033[30;47m$str\033[0m" 
        ;;
        6 )
        echo -e "\033[30;47mQuit successfully!!\033[0m"
        break
        ;;
        7 )
            clear
            menu
        ;;
    esac
done

  • Shell界面
    http://xhope.top/wp-content/uploads/2015/12/1.png

Javascript面向对象编程

对象的封装、继承、模块开发示例

//extends
var module = (function(window) {
'use strict';
    var Person = function(name, age) {
        this._name = name;
        this._age = age;
        console.log('Person is constructor executed...');
    };

    Person.prototype.getName = function() {
        return this._name;
    };

    Person.prototype.getAge = function() {
        return this._age;
    };

    // console.log(Person.prototype.constructor === Person); //true
    // console.log(Person.prototype.constructor.prototype === Person.prototype); //true
    // console.log(Person.prototype.constructor.prototype.constructor.prototype === Person.prototype); //true
    /********************Student extends Person*****************/

    var Student = function(name, age, score) {
        Person.call(this, name, age);  // 调用父类构造函数
        this._score = score;
        console.log('Student is constructor executed...');

    };


    Student.prototype = Object.create(Person.prototype); //new Person();
    Student.prototype.constructor = Student;    //其实并没有什么用处,历史遗留的产物,默认指向自己

    Student.prototype.getScore = function() {
        return this._score;
    }

    var stu = new Student('Rick', 23, 98);
/*
    console.log(stu.getName());
    console.log(stu.getAge());
    console.log(stu.getScore());*/

    return stu;

})(window);

console.log(module.getName());

JQuery插件模板
http://xhope.top/?p=499

参考网站:JavaScript 六种继承方式