Python第十三天 django 1.6 導入模板 定義數據模型 訪問數據庫 GET和POST方法 SimpleCMDB項目 urllib模塊 urllib2模塊 httplib模塊 django和

Python第十三天   django 1.6   導入模板   定義數據模型   訪問數據庫   GET和POST方法    SimpleCMDB項目   urllib模塊   urllib2模塊  httplib模塊  django和web服務器整合  wsgi模塊   gunicorn模塊

 

 

目錄html

Pycharm使用技巧(轉載)前端

Python第一天  安裝  shell  文件node

Python次日  變量  運算符與表達式  input()與raw_input()區別  字符編碼  python轉義符  字符串格式化python

Python第三天 序列  5種數據類型  數值  字符串  列表  元組  字典mysql

Python第四天   流程控制   if else條件判斷   for循環 while循環nginx

Python第五天   文件訪問    for循環訪問文件    while循環訪問文件   字符串的startswith函數和split函數web

Python第六天   類型轉換正則表達式

Python第七天   函數  函數參數   函數變量   函數返回值  多類型傳值    冗餘參數   函數遞歸調用   匿名函數   內置函數   列表表達式/列表重寫sql

Python第八天  模塊   包   全局變量和內置變量__name__    Python pathshell

Python第九天  面向對象  類定義   類的屬性    類的方法    內部類   垃圾回收機制   類的繼承 裝飾器

Python第十天   print >> f,和fd.write()的區別    stdout的buffer  標準輸入 標準輸出  標準錯誤   重定向 輸出流和輸入流

Python第十一天    異常處理  glob模塊和shlex模塊    打開外部程序和subprocess模塊  subprocess類  Pipe管道  operator模塊   sorted函數   生成器  walk模塊   hashlib模塊

Python第十二天     收集主機信息     正則表達式  無名分組   有名分組

Python第十三天   django 1.6   導入模板   定義數據模型   訪問數據庫   GET和POST方法    SimpleCMDB項目   urllib模塊   urllib2模塊  httplib模塊  django和web服務器整合  wsgi模塊   gunicorn模塊

Python第十四天 序列化  pickle模塊  cPickle模塊  JSON模塊  API的兩種格式

Python第十五天  datetime模塊 time模塊   thread模塊  threading模塊  Queue隊列模塊  multiprocessing模塊  paramiko模塊  fabric模塊  

 

 

翻譯項目

http://python.usyiyi.cn/translate/django_182/index.html

 

前端模板:(SmartAdmin)http://www.cnblogs.com/smartbooks/archive/2012/12/03/2799416.html

 

如今主流使用django 1.6

https://docs.djangoproject.com/en/1.7/faq/install/

 

MVC
M:models.py
V:templates 和views.py
C:urls.py

 

 

Django
Django的安裝
https://docs.djangoproject.com/en/1.6/

一、pip 安裝方式
pip install django==1.6.5

easy_install django

查看是否安裝成功
pip list

二、源碼安裝方式
下載tar.gz包
django的源碼包
https://pypi.python.org/pypi/Django
python setup.py install
中文文檔:
http://djangobook.py3k.cn/2.0/


# 驗證django版本
import django
print(django.get_version())
1.5.5

 

django-admin.py
/usr/bin/django-admin.py
/usr/lib/python2.6/site-packages/django/bin/django-admin.py

 


 

建立工程

首先建立一個工程目錄:
cd /data/www/
#web爲項目名,在當前目錄下會新建一個web目錄
django-admin.py startproject web
settings.py當前工程的配置文件
urls.py:urls配置文件,MVC裏面的C
__init__.py 說明當前是一個包,python能夠引入這個目錄下的模塊

 

# 修改時區和語言
vim settings.py
TIME_ZONE = 'Asia/Shanghai'
LANGUAGE_CODE = 'zh-cn'

cat /etc/sysconfig/clock
ZONE="Asia/Shanghai"

 


啓動服務:

cd /data/www/web/
python manage.py runserver 0.0.0.0:8880

 

 

 

 


django目錄結構
項目-》應用

項目文件夾裏面能夠包含多個應用,跟visual studio裏面的解決方案下面有多個application同樣,最好只建立一個應用,由於一個應用對應一個數據庫

 

添加應用
添加一個應用,記住,應用必定要建立在項目文件夾下

cd /data/www/web/
python manage.py startapp blog
或者:
django-admin.py startapp blog

 

[root@VM_centos web]# ll
total 12
drwxr-xr-x 2 root root 4096 Feb 11 21:00 blog
-rwxr-xr-x 1 root root  246 Feb 11 10:56 manage.py
drwxr-xr-x 2 root root 4096 Feb 11 11:14 web


在項目文件夾裏的setting.py
cd /data/www/web/

1. 添加應用:setting.py
INSTALLED_APPS = (
'blog',
2.修改url配置文件urls.py:用戶請求的url轉給誰去處理
url(r'^blog/index/$', 'blog.views.index'),
blog:blog目錄
views:blog目錄下的views.py
index:寫在views.py 裏面的index函數

3.修改應用視圖文件:讓views.py文件的index方法來處理此請求:
cd  /data/www/web/blog/
vim views.py

from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    return HttpResponse('<h1>hello django</h1>')

# Create your views here.


訪問:http://192.168.10.2:8880/blog/index

 

 

 


 

 

導入模板
cd /data/www/web
mkdir blog/templates
templates:名字不能改

cd blog/templates
vim index.html
<h1> hello </h1>

cd /data/www/web/blog/
vim views.py
修改視圖文件views.py
from django.template import loader, Context
1. 建立模板對象,把對應的模板文件導入,自動在templates目錄下找到index.html文件
loader.get_template('index.html')
2. 生成Context對象, 空的字典
c = Context({})
3. return HttpResponse(t.render(c))

from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader, Context

# Create your views here.

def index(request):
t = loader.get_template('index.html')
c = Context({})
return HttpResponse(t.render(c))

 




定義數據模型
Django定義數據模型在App中的models.py文件,數據庫的表名稱以類的形式來定義:
vim models.py

from django.db import models
# Create your models here.
class Host(models.Model):
    hostname = models.CharField(max_length=50)
    ipaddr = models.IPAddressField()

def __unicode__(self):
    return self.hostname


python manage.py validate //查看models.py的語法和邏輯是否正確,返回0 errors found正確


管理數據

python manage.py validate


初始化模型到數據庫,每一個應用對應一個數據庫,每一個數據庫都有下面的權限表:

sqlite> .tables
auth_group
auth_user_user_permissions
auth_group_permissions
blog_host
auth_permission
django_admin_log
auth_user
django_content_type
auth_user_groups
django_session


python manage.py syncdb
執行的時候會提示輸入django管理界面的用戶名和密碼(也就是django自帶的管理平臺的用戶名和密碼http://192.168.6.3:8880/admin,這個用戶名密碼會保存到auth_user表裏)

打開django管理界面
http://192.168.10.2:8880/admin

確保數據庫引擎已經設置好
vim settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

執行python manage.py syncdb以後會生成db.sqlite3文件
[root@VM_centos web]# ll
total 48
drwxr-xr-x 2 root root 4096 Feb 13 13:55 blog
-rw-r--r-- 1 root root 34816 Feb 13 14:04 db.sqlite3
-rwxr-xr-x 1 root root 246 Feb 11 10:56 manage.py
drwxr-xr-x 2 root root 4096 Feb 13 14:01 web

 

換數據庫

https://docs.djangoproject.com/en/1.10/ref/settings/

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'cmdb',
'USER': 'root',
'PASSWORD': '123456',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}

須要安裝python的mysql驅動

yum install -y MySQL-python.x86_64

 

 

 

經過admin頁面管理數據:
cd /data/www/web/blog
vim vim admin.py
把表在admin.py裏註冊,admin才能識別

from django.contrib import admin
from blog.models import Host
或
from blog.models import *  導入全部的類

# Register your models here.

若是要顯示列,須要定義list_display列表:
class HostAdmin(admin.ModelAdmin):
    list_display = ['hostname','ipaddr']



admin.site.register(Host, HostAdmin)

 

 


訪問數據庫

 

訪問數據庫(一)

如何訪問數據,交互式方法:
python manage.py shell
from blog.models import Host //導入表
顯示數據:
node = Host.objects.all()
node.values()
增長數據:
n1 = Host(hostname=‘node1',ipaddr=‘1.1.1.1')
或:
n1 = Host()
n1.hostname = ‘node1’
n1.ipaddr = ‘1.1.1.1’
n1.save() //寫到表裏


訪問數據庫(二)

經過視圖文件views.py來訪問數據
1.在urls.py文件裏定義urls訪問路徑
vim urls.py
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'web.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),

url(r'^admin/', include(admin.site.urls)),
url(r'^blog/index/$', 'blog.views.index'),
url(r'^db/$', 'blog.views.db'),
)


2. 在views.py裏定義訪問方法
vim views.py
from django.template import loader,Context
from blog.models import Host
from django.shortcuts import render
from django.http import HttpResponse

def index(request):
return HttpResponse('<h1>hello django</h1>')

def db(req):
h=Host()
h.hostname='test'
h.ip='192.168.2.3'
h.save()
return HttpResponse('OK')

 

request,req:表示客戶端向服務器端的請求,HttpRequest對象


訪問數據庫(三)

定義API
1. urls.py 定義訪問路徑
2. views.py 定義訪問方法 (API)
def collect(request):
if request.POST: 或 request.method == 'POST'
hostname = request.POST.get('hostname')
ipaddr = request.POST.get('ipaddr')
host = Host()
host.hostname = hostname
host.ipaddr = ipaddr
host.save()
return HttpResponse('OK')
else:
return HttpResponse('not data')


註釋掉csrf,讓django識別curl
vim settings.py
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

curl -d hostname='node05' -d ip='192.168.10.2' http://192.168.1.5:8000/db/


GET和POST方法

HttpRequest
request.POST.get('hostname')
或:
request.POST['hostname']

request.GET.get('hostname')
或:
request.GET['hostname']


傳遞數據
POST方法:
curl -d hostname='node12' -d ipaddr='12.12.12.12' http://192.168.3.72:8000/blog.collect/

GET方法:經過瀏覽器傳遞數據
http://192.168.3.72:8000/blog.get?hostname=n3&ipaddr=1.1.1.3

 

 

 


 

SimpleCMDB項目   urllib模塊   urllib2模塊  httplib模塊

建立一個應用:
python manage.py startapp hostinfo
修改settings.py添加應用

 

 


admin.py
註冊數據庫:admin.py
from hostinfo.models import Host
class HostAdmin(admin.ModelAdmin):
list_display = ['hostname',
'vendor',
'product',
'osver',
'cpu_model',
'cpu_num',
'memory',
'sn']
admin.site.register(Host, HostAdmin)

 


syncdb
同步數據庫
定義url訪問路徑
views.py定義訪問方法

 

導入數據:
# cat data.sh
curl -d vendor='HP' -d product='2014' -d osver='rhel6.4' -d memory=4 -d cpu_model='Intel' -d cpu_num=8 -d sn='XXXXX' -d hostname='node2' http://192.168.131.10:8000/api/collect/
# bash data.sh

 

 

urllib,urllib2,httplib
使用urllib訪問網頁和傳數據,一般urllib,urllib2這兩個模塊一塊兒添加
req = urllib2.urlopen('http://192.168.131.10:8000/api/collect')
對字典data進行編碼,生成post格式的數據
data ={'hostname':'node05','ip':'192.18.2.3'}
d = urllib.urlencode(data) #必須先要urlencode 才能傳入url
req = urllib2.urlopen('http://192.168.131.10:8000/api/collect/',d)
req.read()

 

urlopen(url, data=None, timeout=<object object>, cafile=None, capath=None, cadefault=False, context=None)
data=None:請求的數據,post方式


urlencode(query, doseq=0)
Encode a sequence of two-element tuples or dictionary into a URL query string.
傳入一個兩個元素的元組或字典做爲url查詢字符串
print urllib.urlencode({'ip':'192.168.1.1','host':'123'})
ip=192.168.1.1&host=123 : 轉化爲url的post方式

 


vim models.py
from django.db import models

# Create your models here.

class Host(models.Model):
hostname = models.CharField(max_length=50)
ip = models.IPAddressField()
vendor = models.CharField(max_length=50)
product = models.CharField(max_length=50)
sn = models.CharField(max_length=50)
cpu_model = models.CharField(max_length=50)
cpu_num = models.IntegerField()
memory = models.CharField(max_length=50)
osver = models.CharField(max_length=50)

def __unicode__(self):
return self.hostname

class HostGroup(models.Model):
groupname = models.CharField(max_length=50)
members = models.ManyToManyField(Host)


建立HostGroup表,models.py
class HostGroup(models.Model):
groupname = models.CharField(max_length=50)
members = models.ManyToManyField(Host) # 多對多關係

註冊數據庫,admin.py
from hostinfo.models import HostGroup
class HostGroupAdmin(admin.ModelAdmin):
list_display = ['groupname']
admin.site.register(HostGroup, HostGroupAdmin)

 

 


python manage.py sqlall blog

BEGIN;
CREATE TABLE "blog_host" (
"id" integer NOT NULL PRIMARY KEY,
"hostname" varchar(50) NOT NULL,
"ip" char(15) NOT NULL,
"vendor" varchar(50) NOT NULL,
"product" varchar(50) NOT NULL,
"sn" varchar(50) NOT NULL,
"cpu_model" varchar(50) NOT NULL,
"cpu_num" integer NOT NULL,
"memory" varchar(50) NOT NULL,
"osver" varchar(50) NOT NULL
)
;
CREATE TABLE "blog_hostgroup_members" (
"id" integer NOT NULL PRIMARY KEY,
"hostgroup_id" integer NOT NULL,
"host_id" integer NOT NULL REFERENCES "blog_host" ("id"),
UNIQUE ("hostgroup_id", "host_id")
)
;
CREATE TABLE "blog_hostgroup" (
"id" integer NOT NULL PRIMARY KEY,
"groupname" varchar(50) NOT NULL
)
;
CREATE INDEX "blog_hostgroup_members_521bb4b0" ON "blog_hostgroup_members" ("hostgroup_id");
CREATE INDEX "blog_hostgroup_members_27f00f5d" ON "blog_hostgroup_members" ("host_id");

COMMIT;

 


django和web服務器整合  wsgi模塊   gunicorn模塊

wsgi模塊

wsgi:web server gateway interface web服務器網關接口
Django與Apache整合


安裝
yum install -y mod_wsgi

cd /etc/httpd/conf.d
vim wsgi.conf

 

 

 

 

gunicorn模塊

yum install -y epel-release

Django與nginx整合

netstat -tulanp|grep :8000
使用這個命令來看8000端口是否開啓,192.168.0.110上的8000是nginx開的,127.0.0.1上的8000是python這個進程開的。
因此使用netstat -tulanp|grep nginx這個命令是看不到的。

 

 

 


manage.py的用法

 

python manage.py runserver 8080
更改服務器端口號

python manage.py shell
啓動交互界面,若是系統安裝了ipython則啓動ipython,不然啓動python命令行,並且多了一些環境變量

python manage.py startapp books
建立一個app,名爲books

python manage.py validate
驗證Django數據模型代碼是否有錯誤,models.py文件裏面的代碼是否有誤

python manage.py sqlall books
爲模型產生sql代碼,但不實際執行

python manage.py syncdb
運行sql語句,在數據庫裏建立模型相應的Table

python manage.py dbshell
啓動數據庫的命令行工具

 

 


 

sqlite經常使用操做

 

跟mysql同樣,以分號 ; 做爲一個語句的結束

sqlite> .tables
auth_group                  auth_user_user_permissions
auth_group_permissions      blog_host                 
auth_permission             django_admin_log          
auth_user                   django_content_type       
auth_user_groups            django_session            

sqlite> .database
seq  name             file                                                      
---  ---------------  ----------------------------------------------------------
0    main             /data/www/web/db.sqlite3                                  
1    temp                                            
 sqlite> .exit 
[root@VM_centos web]# 
 sqlite> .schema 
CREATE TABLE "auth_group" (
    "id" integer NOT NULL PRIMARY KEY,
    "name" varchar(80) NOT NULL UNIQUE
);
CREATE INDEX "django_admin_log_6340c63c" ON "django_admin_log" ("user_id");
CREATE INDEX "django_session_b7b81f0c" ON "django_session" ("expire_date");


sqlite> .show
     echo: off
  explain: off
  headers: off
     mode: list
nullvalue: ""
   output: stdout
separator: "|"
    width: 

    

sqlite> .help 
.backup ?DB? FILE      Backup DB (default "main") to FILE
.bail ON|OFF           Stop after hitting an error.  Default OFF
.databases             List names and files of attached databases
.dump ?TABLE? ...      Dump the database in an SQL text format
                         If TABLE specified, only dump tables matching
                         LIKE pattern TABLE.
.echo ON|OFF           Turn command echo on or off
.exit                  Exit this program
.explain ON|OFF        Turn output mode suitable for EXPLAIN on or off.
.genfkey ?OPTIONS?     Options are:
                         --no-drop: Do not drop old fkey triggers.
                         --ignore-errors: Ignore tables with fkey errors
                         --exec: Execute generated SQL immediately
                       See file tool/genfkey.README in the source 
                       distribution for further information.
.header(s) ON|OFF      Turn display of headers on or off
.help                  Show this message
.import FILE TABLE     Import data from FILE into TABLE
.indices ?TABLE?       Show names of all indices
                         If TABLE specified, only show indices for tables
                         matching LIKE pattern TABLE.
.load FILE ?ENTRY?     Load an extension library
.mode MODE ?TABLE?     Set output mode where MODE is one of:
                         csv      Comma-separated values
                         column   Left-aligned columns.  (See .width)
                         html     HTML <table> code
                         insert   SQL insert statements for TABLE
                         line     One value per line
                         list     Values delimited by .separator string
                         tabs     Tab-separated values
                         tcl      TCL list elements
.nullvalue STRING      Print STRING in place of NULL values
.output FILENAME       Send output to FILENAME
.output stdout         Send output to the screen
.prompt MAIN CONTINUE  Replace the standard prompts
.quit                  Exit this program
.read FILENAME         Execute SQL in FILENAME
.restore ?DB? FILE     Restore content of DB (default "main") from FILE
.schema ?TABLE?        Show the CREATE statements
                         If TABLE specified, only show tables matching
                         LIKE pattern TABLE.
.separator STRING      Change separator used by output mode and .import
.show                  Show the current values for various settings
.tables ?TABLE?        List names of tables
                         If TABLE specified, only list tables matching
                         LIKE pattern TABLE.
.timeout MS            Try opening locked tables for MS milliseconds
.width NUM NUM ...     Set column widths for "column" mode
.timer ON|OFF          Turn the CPU timer measurement on or off

 


 

django中的模型三種關係

 

1=>N | 1<=>1 | N<=>N 三種關係

1對多:ForeignKey
1對1:OneToOneField
多對多:ManyToManyField

class Student(models.Model):
student_name = models.CharField(verbose_name=u'student name', max_length=100)
school = models.ForeignKey(School, on_delete=models.CASCADE, verbose_name='student school')
teachers = models.ManyToManyField(Teacher, verbose_name='students teachers')
bed = models.OneToOneField(Bed, on_delete=models.CASCADE, verbose_name='student bed')

 

 

 

 

django女孩博客

http://blog.djangogirls.org/

相關文章
相關標籤/搜索