## 零、開發的軟件:Wingide
+ 解決python的中文編碼亂碼問題:
1.點擊debug
2.點擊右邊出現的扳手形狀的按鈕
3.新出現的窗口中間的option點擊
4.選擇utf-8編碼。endoce('utf-8')把其餘編碼轉成utf8的格式;decode('utf-8')是把utf8解碼成其餘編碼格式
## 1、第一個python程序:
>>> 100+200
>>> print 'hello world'
## 2、輸入
name = raw_input()
## 3、轉義字符\能夠轉義不少字符,好比\n表示換行,\t表示製表符,字符\自己也要轉義,因此\\表示的字符就是\
## 4、指令:
+ 1.list:一個有序的集合,下標從0開始,list[-1]最後一個元素。增刪改所有跟js同樣.-----------列表
```
a.list[0],list[1].... //查
b.len(list) //長度
c.list.append(new); //增(追加)
d.list.insert([index],new); //增(前加)
e.list.pop([index]); //刪除
f.list[index] = 'new'; //改
g.list2.extend(list) //在原有的基礎上追加,不建立新的列表
h.del list:刪除列表對象的引用
i.del [:]:產出列表的元素
```
+ 2.tuple:也是一個有序的數據,格式是(),一旦初始化,就不能夠改變,除了沒有append,insert,其餘跟list同樣 ------元組
```
>>> t = ('a', 'b', ['A', 'B'])
>>> t[2][0] = 'X'
>>> t[2][1] = 'Y'
>>> t
('a', 'b', ['X', 'Y'])
```
+ 3.判斷語句
```
if num>10
print xxx;
print x
```
用elif帶替else if.range(num)按照順序生成有序的數組。特別注意一點:python更多的使用:代替{}
+ 4.dict:格式跟定義json同樣,採用key-value的形式。訪問:dict[key];dict的key必須是不可變的參數 ------字典
```
student = {'aa':12,'vv',2344}
student[aa]
```
#### dict的操做
##### a. del student[a] #刪除某個元素
##### b. student.clear() #清空全部的元素
##### c. student.pop('aa') #返回鍵對應的值。注意:pop操做的列表是最原始的列表
##### d. student.get('aa') #返回的是鍵的值
e. student.keys() #返回的是student的key列表
+ 5.set:要建立一個set,須要提供一個list做爲輸入集合:建立一個key不重複的集合 -------集合
```
>>> s = set([1, 2, 3])
>>> s
set([1, 2, 3])
```
a. s.add(4) //增長元素
b. s.remove(key) //刪除元素
c.s1 & s2,s1 | s2
d.in 成員關係
>>>1 in a
>>>True
+ 6.字符串的替換:
a.replace方法html
b.maketrans('old','new') #翻譯表
```
import string
a = '1234456'
g = string.maketrans('123','qwe')
a.translate(g) #'qwe4456'
```
## 4.2 字符串拼接
+ +:'str1'+'str2'
+ %s:佔位符
```
s = 'my name is %s,i love %s',%('python','apple')
```
+ format()
```
'mu name is {0},i love {1}'.format('apple','python')
```
+ join:
```
''.join('abc','heha')
```
+ 7.python的內置方法:
###### a.len('str')
###### b.max(list)
###### c.min(turple)
###### d.sum(list)
###### e.sorted(list)
###### f.enumerate(list) #枚舉
###### g.list(turple)
###### h.turple(list)
###### i.zip(list1,list2) #對應組合
5、函數
+ 函數由函數名和變量組成;
```
abs(10) ---> 10
abs(-10) ---> 10
cmp(1,2) ---> -1python
```
+ python提供了數據類型轉換的方法
```
int('12') --> 12
float('1.23') ---> 1.23
bool('aa') ---> true
bool('') ---> false
```
+ 函數能夠設置默認參數,減小函數調用時的複雜度。
```
def main(name,sex,age=4,city="beijing"):
print 'name',name;
print 'sex',sexmysql
main('zhangsan','男')
```
+ 函數參數匹配:使用如下幾種匹配方式:
##### 1.常規參數的順序匹配
##### 2.默認參數的順序匹配,調用函數時若是未傳入參數,就按照默認參數的值
##### 3.**,*之類的參數匹配,要在對應的位置傳入實參
+ 遞歸函數:若是咱們在使用遞歸時可能出現棧內存泄漏的問題,咱們使用尾遞歸處理
```
def fact(n):
return fact_ater(n,1)
def fact_ater(num,result):
if num == 1:
return result
else:
```
+ **,*的用法:**表示dict;*表示元組
```
def test(**kr):
return krweb
text(name='zhagsan',age=12,score=78)正則表達式
{name:'zhangsan',age:12,score:78}
```
*表示元組
```
def text(*z):
return z
test(12,36,6):
(12,36,6)
```
## 6、高級特性:
+ 切片:
```
>>> L[0:3]
['Michael', 'Sarah', 'Tracy']
```
```
L[:10:2] //前十個數,每兩個取一個
L[::4] //全部的數,每4個取一個
```
+ 迭代:for ... in ... 遍歷dirc。
```
d = {'a':1,'v':2,'e':3}
for k in d:
print k;sql
for value in d.itervalues: //獲得value
print value;數據庫
for k,v in d.iteritems: //獲得key和value
print k,v
```
a.判斷一個對象是否是可迭代對象:
```
>>> from collections import Iterable
>>> isinstance('abc', Iterable) # str是否可迭代
True
>>> isinstance([1,2,3], Iterable) # list是否可迭代
True
>>> isinstance(123, Iterable) # 整數是否可迭代
False
```
b.若是要把一個list對象也像dirc同樣迭代,python提供了一個方法enumerate
```
>>> for i, value in enumerate(['A', 'B', 'C']):
... print i, value
...
0 A
1 B
2 C
```
c.列表生成式:實際上就是在合理的應用for循環
```
[(x,y) for x in range(3) for y in range(3) if x%2==0 and y%2==0]
>>>[(0,0),(0,2),(2,0),(2,2)]
>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]express
```
d.生成器:若是把列表生成式中的[]換成(),就是一個generator.若是一個函數定義中包含yield關鍵字,那麼這個函數就再也不是一個普通函數,而是一個generator.send('')當yield裏面沒有返回值時,send函數就會把裏面的東西替代yield要返回的內容
```
>>> g = (x * x for x in range(10))
>>>g
0,1,4,9...django
>>> def odd():
... print 'step 1'
... yield 1
... print 'step 2'
... yield 3
... print 'step 3'
... yield 5
...
>>> o = odd()
>>> o.next()
step 1
1
>>> o.next()
step 2
3
>>> o.next()
step 3
5
```
## 7、高階函數:能夠在一個自定義函數中調用另一個函數
```
def my_abs(x,y,f):
return f(x)+f(y)
my_abs(10,-10,abs)編程
```
a.map(fn,list[]):fn函數做用於list列表的每一個元素,生成一個新的list
```
def f(x):
return x*x;
map(f,[1,2,3....])
```
b.reduce(fn,[x1,x2,x3])調用函數屢次,把第一次的計算的結果當作參數傳進去當作第二次的參數.
c.filter:和map()相似,filter()也接收一個函數和一個序列。和map()不一樣的時,filter()把傳入的函數依次做用於每一個元素,而後根據返回值是True仍是False決定保留仍是丟棄該元素。
d.sorted:對list或者str排序,能夠傳入自定義的函數,實現排序規則
```
def reverse(x,y):
if x<y:
return 1
elif x=y:
return 0
else:
return -1
sorted([12,32,56,33,3],reverse)
```
## 8、匿名函數:沒有函數名的函數:
```
>>> map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])
[1, 4, 9, 16, 25, 36, 49, 64, 81]
```
+ 關鍵字lambda表示匿名函數,冒號前面的x表示函數參數。
## 9、偏函數:就是把一個函數的默認參數改掉,以便咱們下次調用時方便,不用再設置參數
```
>>> import functools
>>> int2 = functools.partial(int, base=2)
>>> int2('1000000')
64
>>> int2('1010101')
85
```
## 10、模塊:
+ python的內置模塊,咱們在命名模塊時不能與其同名。[點擊這裏](https://docs.python.org/2/library/functions.html)
+ 自定義模塊:
```
#!usr/bin/env python
# -s-coding:utf-8 -s-
'a hello module'
__author__ = 'My.lai'
import sys
def test():
args = sys.argv
if len(args) == 1:
print 'hello world'
elif len(args) == 2:
print 'hello,%s!'%args[1]
else:
print 'Too many arguments!'
if __name__ == '__main__':
test()
```
+ 添加第三方模塊:如:Python Imaging Library處理圖形的模塊
```
pip install PIL
```
## 11、面向對象編程
+ 面向對象的三大特徵:封裝、繼承、多態
+ 格式:
```
class Student(object): //object是類繼承哪一個類
def __init__(self,name,score): //參數self是固定的參數,指向類自己
self.name = name;
slef.score = score;
student = Student() //實例化
```
+ 若是要讓內部屬性不被外部訪問,能夠把屬性的名稱前加上兩個下劃線__,在Python中,實例的變量名若是以__開頭,就變成了一個私有變量(private),只有內部能夠訪問,外部不能訪問
```
class Student(object): //object是類繼承哪一個類
def __init__(self,name,score): //參數self是固定的參數,指向類自己
self.__name = name;
slef.__score = score;
student = Student() //實例化
>>> self.__name //私有變量,訪問不到
```
+ 析構函數:釋放變量佔用的內存
```
def __del__:
del self.name
del self.age
```
+ isinstance('animal',str)判斷animal是否是str類型
+ type()獲取對象類型,phthon提供了一個獲取類型的模塊
```
>>> import types
>>> type('abc')==types.StringType
True
>>> type(u'abc')==types.UnicodeType
True
>>> type([])==types.ListType
True
>>> type(str)==types.TypeType
True
```
+ dir()獲取對象的屬性和方法,接着配合hasattr(),setattr(),getattr()對屬性操做
```
>>> hasattr(obj, 'power') # 有屬性'power'嗎?
True
>>> getattr(obj, 'power') # 獲取屬性'power'
<bound method MyObject.power of <__main__.MyObject object at 0x108ca35d0>>
>>> fn = getattr(obj, 'power') # 獲取屬性'power'並賦值到變量fn
>>> fn # fn指向obj.power
<bound method MyObject.power of <__main__.MyObject object at 0x108ca35d0>>
>>> fn() # 調用fn()與調用obj.power()是同樣的
81
```
## 12、高級面向對象編程
+ 面向對象能夠給子類實例添加方法,可是對後來的實例對象是無效的。
```
def set_score(score):
return score
class Student(object):
pass
s = Student()
form types import MethodType
s.set_score = MethodType(set_score,s,Student)
s.set_score(23)
>>>23
```
+ __slots__:定義實例化對象能夠賦值的屬性
```
class Student(object):
__slots__:('name','age')
s = Student()
s.name = 'kangkang'
s.age = 12
s.score = 34
>>>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'score'
```
+ __init__(self):#構造方法
+ __repr__(self):#自定yi實例的輸出
```
class Student():
def __repr__(self):
print 'cuo'
s = Student()
>>> s
>>> cuo
```
+ @property負責把一個方法變成屬性來使用
```
class Student(object):
@property
def score(self):
return self._score
@score.setter
def score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
>>> s = Student()
>>> s.score = 60 # OK,實際轉化爲s.set_score(60)
>>> s.score # OK,實際轉化爲s.get_score()
60
>>> s.score = 9999
Traceback (most recent call last):
...
ValueError: score must between 0 ~ 100!
```
+ 多繼承:就是讓子類有多個父類,同時擁有多個父類的方法和屬性:
```
class Animal(object):
pass
class FlyableMixin(object):
pass
class Dog(Animal,FlyableMixin):
pass
```
+ __fn__(self,....):相似這種兩個_的函數在python是不能隨便亂用的
```
class Student(object):
def __init__(self,name):
self.name = name
def __str__(self):
return self.name
```
*經過callable()函數,咱們就能夠判斷一個對象是不是「可調用」對象。*
```
>>> callable(Student())
true
>>> callbale(max)
true
>>> callable('none)
false
>>> callable('string')
false
```
## 十3、錯誤、調試和測試
+ 錯誤:咱們使用try...except...finally來處理錯誤,若是try代碼運行時出現錯誤,被except捕捉到那就執行except的代碼,再執行finally代碼
```
try:
print 'try...'
r = 10/0
print 'result:',r
except ZeroDivisionError, e:
print 'except...',e
finally:
print 'finally'
print 'end'
```
+ 調試:一個比較常見和好用的方式:在執行py文件時,開啓pdb調試
```
python -m pdb err.py
>>> l //顯示代碼
>>> n //單步執行代碼
>>> p 參數 //查看變量的值
```
*咱們能夠在可能會出錯的地方設置pdb.set_trace(),實際上就是斷點,c繼續運行*
## 十4、讀寫文件
```
f = open('dirs/user/demo.txt','r')
f.read()
f.close()
```
+ 使用with代替close來關閉文件
```
with open('/path/to/file', 'r') as f:
print f.read()
```
+ 文件編碼:python提供了一個自動幫咱們讀取文件編碼的模塊
```
import codecs
with codecs.open('/Users/michael/gbk.txt', 'r', 'gbk') as f:
f.read() # u'\u6d4b\u8bd5'
```
+ 寫文件:與讀文件類型,區別在傳入參數'w',或者''wb'
```
f = open('dirs/path/user/demo/index.html','w')
```
```
b.操做文件目錄
import os
+ os.path.abspath('.') //當前文件所在的決對路徑
+ os.mkdir('') //建立文件
+ os.rmdir('') //刪除文件
+ os.path.join('','') //拼接文件路徑
```
c.python對象轉化成json對象
```
import json
f = dirc(name='zhagsan',age=12,score=90)
json.dumps(f)
{"name":"zhagsan","age":12,"score":90}
```
d.把一個json對象反序列化成python對象
```
json_str = '{"name":"zhagsan","age":12,"score":90}'
json.load(json_str)
{u'age': 20, u'score': 88, u'name': u'Bob'}
```
e.類的實例化對象json序列化
```
import json
class Student(object):
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
s = Student('Bob', 20, 88)
print(json.dumps(s))
def student2dict(std):
return {
'name': std.name,
'age': std.age,
'score': std.score
}
print(json.dumps(s, default=student2dict))
```
#### 在外面函數就對s的參數進行json格式的定義
## 十5、進程和線程
+ 進程間的通訊:
```
from multiprocessing import Process, Queue
import os, time, random
# 寫數據進程執行的代碼:
def write(q):
for value in ['A', 'B', 'C']:
print 'Put %s to queue...' % value
q.put(value)
time.sleep(random.random())
# 讀數據進程執行的代碼:
def read(q):
while True:
value = q.get(True)
print 'Get %s from queue.' % value
if __name__=='__main__':
# 父進程建立Queue,並傳給各個子進程:
q = Queue()
pw = Process(target=write, args=(q,))
pr = Process(target=read, args=(q,))
# 啓動子進程pw,寫入:
pw.start()
# 啓動子進程pr,讀取:
pr.start()
# 等待pw結束:
pw.join()
# pr進程裏是死循環,沒法等待其結束,只能強行終止:
pr.terminate()
```
## 十6、正則表達式
+ .表示匹配任何字符
+ *表示匹配任何個數的字符,包括0個
+ +表示匹配至少一個字符
+ ?表示0個或1個字符
+ {n}表示匹配n個
+ {n,m}表示匹配n-m個字符
+ \s空格,\d數字,\w數字或者字母
+ []表示範圍
```
[a-zA-Z\_][0-9a-zA-Z\_]*能夠匹配由字母或下劃線開頭,後接任意個由一個數字、字母或者下劃線組成的字符串,也就是Python合法的變量;
```
+ ^表示行的開頭,^\d表示必須以數字開頭。
+ $表示行的結束,\d$表示必須以數字結束。
+ 使用Python的r前綴,就不用考慮轉義的問題了:
```
s = r'ABC\-001' # Python的字符串
```
+ re.match()測試正則表達式是否能夠匹配上
```
test = '用戶輸入的字符串'
if re.match(r'正則表達式', test):
print 'ok'
else:
print 'failed'
```
+ 除了簡單地判斷是否匹配以外,正則表達式還有提取子串的強大功能。用()表示的就是要提取的分組(Group)
```
>>> m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')
>>> m
<_sre.SRE_Match object at 0x1026fb3e8>
>>> m.group(0)
'010-12345'
>>> m.group(1)
'010'
>>> m.group(2)
'12345'
```
## 十7、常見內建模塊
### 1.collections
+ namedtuple 定義各類各樣的類,告訴解釋器這是什麼
```
from collections import namedtuple
Point = namedtuple('Point',['x','y']) //定義了一個類
point = Point(1,30) //類的實例化
point.x //1
point.y //30
```
+ deque 是對list列表增長和刪除元素,很是適合對列和棧
```
from collections import deque
q = deque(['a','b','c'])
q.append('x')
q.appendleft('y')
q = deque(['y','a','b','c','x'])
```
+ defaultdict:使用dict時,若是引用的Key不存在,就會拋出KeyError。若是但願key不存在時,返回一個默認值,就能夠用defaultdict
+ OrderedDict:使用dict時,Key是無序的。在對dict作迭代時,咱們沒法肯定Key的順序。若是要保持Key的順序,能夠用OrderedDict
+ counter:Counter是一個簡單的計數器,例如,統計字符出現的個數:
```
>>> from collections import Counter
>>> c = Counter()
>>> for ch in 'programming':
... c[ch] = c[ch] + 1
...
>>> c
Counter({'g': 2, 'm': 2, 'r': 2, 'a': 1, 'i': 1, 'o': 1, 'n': 1, 'p': 1})
```
#### 2.itertools:用於操做迭代對象的模塊
+ itertools.count(1) //無線計數
```
import itertools
natural = itertools.count(1)
for n in natural:
print n
```
+ itertools.cycle()會把傳入的一個序列無限重複下去:
```
>>> import itertools
>>> cs = itertools.cycle('ABC') # 注意字符串也是序列的一種
>>> for c in cs:
... print c
...
'A'
'B'
'C'
'A'
'B'
'C'
```
+ itertools.repeat('a',10) //重複打印傳入的字符,傳入第二個參數就限定了次數
```
>>> ns = itertools.repeat('A', 10)
>>> for n in ns:
... print n
...
打印10次'A'
```
+ chain()能夠把一組迭代對象串聯起來,造成一個更大的迭代器:
```
for c in itertools.chain('ABC', 'XYZ'):
print c
# 迭代效果:'A' 'B' 'C' 'X' 'Y' 'Z'
```
+ imap()能夠做用於無窮序列,而且,若是兩個序列的長度不一致,以短的那個爲準。
```
>>> for x in itertools.imap(lambda x, y: x * y, [10, 20, 30], itertools.count(1)):
... print x
...
10
40
90
```
## 十8、經常使用的第三方模塊
+ PIL模塊windows平臺須要到官方網站下載exe
```
import Image
# 打開一個jpg圖像文件,注意路徑要改爲你本身的:
im = Image.open('/Users/michael/test.jpg')
# 得到圖像尺寸:
w, h = im.size
# 縮放到50%:
im.thumbnail((w//2, h//2))
# 把縮放後的圖像用jpeg格式保存:
im.save('/Users/michael/thumbnail.jpg', 'jpeg')
```
## 十9、圖形界面
#### 使用python內置的Tkinter圖形界面
```
from Tkinter import * //從Tkinter包的全部內容
class Application(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack() //把Widget加入到父容器中
self.createWidgets()
def createWidgets(self):
self.helloLabel = Label(self, text='Hello, world!') //標籤
self.helloLabel.pack()
self.quitButton = Button(self, text='Quit', command=self.quit) //按鈕
self.quitButton.pack()
# 實例化
app = Application()
# 設置窗口標題:
app.master.title('Hello World')
# 主消息循環:
app.mainloop()
```
```
from Tkinter import *
# tkMessageBox模塊
import tkMessageBox
class Application(Frame):
def __init__(self,master=None):
Frame.__init__(self,master)
self.pack()
self.createWidgets()
def createWidgets(self):
self.nameInput = Entry(self)
self.nameInput.pack()
self.alertButton = Button(self,text = 'hello',command=self.hello)
self.alertButton.pack()
def hello(self):
name = self.nameInput.get() or 'world'
tkMessageBox.showinfo('Message','Hello,%s'%name)
app = Application()
app.master.title('Hello World')
app.mainloop()
```
## 二10、網絡編程
#### TCP編程
```
# 服務端
import socket
# 創建基於ipv4和TCP協議的socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 建立端口號
s.bind(('127.0.0.1',9000))
# 監聽端口,參數規定每次傳入的個數
s.listen(5)
while True:
# 接受一個新鏈接:
sock, addr = s.accept()
# 建立新線程來處理TCP鏈接:
t = threading.Thread(target=tcplink, args=(sock, addr))
t.start()
def tcplink(sock, addr):
print 'Accept new connection from %s:%s...' % addr
sock.send('Welcome!')
while True:
data = sock.recv(1024)
time.sleep(1)
if data == 'exit' or not data:
break
sock.send('Hello, %s!' % data)
sock.close()
print 'Connection from %s:%s closed.' % addr
# 客戶端
import socket
#創建socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 建議連接
s.connect(('127.0.0.1',9000))
#發送數據
print s.recv(1024)
for data in ['Michael','Tracy','Sarch']:
s.send(data)
print s.recv(1024)
s.send('exit')
s.close()
```
#### UDP編程
```
# 服務端
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(('127.0.0.1',9000))
print 'Bind UDP on 9000'
while True:
data,addr = s.recvfrom(1024)
print 'Recived from %s:%s'%addr
s.send('Hello,%s!' %data)
# 客戶端
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
for data in ['kangkang','zhangsan','Mick']:
s.sendto(data,('127.0.0.1',9000))
print s.recv(1024)
s.close()
```
## 二11、電子郵件
## 二12、使用內置的數據庫
+ python 有一套內置的數據庫sqlite3
```
import sqlite3
#鏈接到數據庫
conn = sqlite3.connect('test.db')
# 建立遊標
cursor = conn.cursor()
# 執行一條SQL語句,建立user表:
cursor.execute('create table user (id varchar(20) primary key, name varchar(20)')
# 執行一條SQL語句,插入一條數據
cursor.execute('insert into user (id, name) values (\'1\', \'Michael\')')
# 經過rowcount得到插入的行數:
>>> cursor.rowcount
1
# 關閉Cursor:
>>> cursor.close()
# 提交事務:
>>> conn.commit()
# 關閉Connection:
>>> conn.close()
# 查詢插入的數據
>>> conn = sqlite3.connect('test.db')
>>> cursor = conn.cursor()
# 執行查詢語句:
>>> cursor.execute('select * from user where id=?', ('1',))
<sqlite3.Cursor object at 0x10f8aa340>
# 得到查詢結果集:
>>> values = cursor.fetchall()
>>> values
[(u'1', u'Michael')]
>>> cursor.close()
>>> conn.close()
```
+ 使用MySQL
調用咱們本身的數據庫時,咱們要先安裝mysql的驅動,兩個任選一個均可以
```
easy_install mysql-connector-python
easy_install MySQL-python
```
下面就以mysql-connnecot爲例
```
# 導入MySQL驅動:
>>> import mysql.connector
# 注意把password設爲你的root口令:
>>> conn = mysql.connector.connect(user='root', password='password', database='test', use_unicode=True)
>>> cursor = conn.cursor()
# 建立user表:
>>> cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')
# 插入一行記錄,注意MySQL的佔位符是%s:
>>> cursor.execute('insert into user (id, name) values (%s, %s)', ['1', 'Michael'])
>>> cursor.rowcount
1
# 提交事務:
>>> conn.commit()
>>> cursor.close()
# 運行查詢:
>>> cursor = conn.cursor()
>>> cursor.execute('select * from user where id = %s', ('1',))
>>> values = cursor.fetchall()
>>> values
[(u'1', u'Michael')]
# 關閉Cursor和Connection:
>>> cursor.close()
True
>>> conn.close()
```
## 二十3、Web開發
+ python內置了一個比較簡單的WSGI服務器,python徹底能夠忽略底層怎麼實現http請求的代碼,專一於返回什麼就好了
```
def application(environ,start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return '<h1>Hello, web!</h1>')
# server.py
# 從wsgiref模塊導入:
from wsgiref.simple_server import make_server
# 導入咱們本身編寫的application函數:
from hello import application
# 建立一個服務器,IP地址爲空,端口是8000,處理函數是application:
httpd = make_server('', 8000, application)
print "Serving HTTP on port 8000..."
# 開始監聽HTTP請求:
httpd.serve_forever()
```
+ 處理不一樣的url地址,使用web的框架會比較簡單
```
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def home():
return '<h1>Home</h1>'
@app.route('/signin', methods=['GET'])
def signin_form():
return '''<form action="/signin" method="post">
<p><input name="username"></p>
<p><input name="password" type="password"></p>
<p><button type="submit">Sign In</button></p>
</form>'''
@app.route('/signin', methods=['POST'])
def signin():
# 須要從request對象讀取表單內容:
if request.form['username']=='admin' and request.form['password']=='password':
return '<h3>Hello, admin!</h3>'
return '<h3>Bad username or password.</h3>'
if __name__ == '__main__':
app.run()
```
+ 常見的Python Web框架還有:
1.Django:全能型Web框架;
2.web.py:一個小巧的Web框架;
3.Bottle:和Flask相似的Web框架;
4.Tornado:Facebook的開源異步Web框架。
+ mvc實現web框架
```
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def home():
return render_template('home.html')
@app.route('/signin', methods=['GET'])
def signin_form():
return render_template('form.html')
@app.route('/signin', methods=['POST'])
def signin():
username = request.form['username']
password = request.form['password']
if username=='admin' and password=='password':
return render_template('signin-ok.html', username=username)
return render_template('form.html', message='Bad username or password', username=username)
if __name__ == '__main__':
app.run()
```
除了Jinja2,常見的模板還有:
Mako:用<% ... %>和${xxx}的一個模板;
Cheetah:也是用<% ... %>和${xxx}的一個模板;
Django:Django是一站式框架,內置一個用{% ... %}和{{ xxx }}的模板。
## 二十4、python的語句
+ print:基本的輸出語句
```
print 'a',
print 'b',#逗號是爲了讓輸出不換行
f = open('test.txt','w')
print >>f,'adaer' #>>往文件裏面寫入內容
```
+ global關鍵字:定義全局的變量
## 二十5、python一些內置的模塊:
### 1.urllib:操做地址欄地址的模塊:
quote_plus(s, safe='')
Quote the query fragment of a URL; replacing ' ' with '+'
splitattr(url)
splitattr('/path;attr1=value1;attr2=value2;...') ->
'/path', ['attr1=value1', 'attr2=value2', ...].
splithost(url)
splithost('//host[:port]/path') --> 'host[:port]', '/path'.
splitnport(host, defport=-1)
Split host and port, returning numeric port.
Return given default port if no ':' found; defaults to -1.
Return numerical port if a valid number are found after ':'.
Return None if ':' but not a valid number.
splitpasswd(user)
splitpasswd('user:passwd') -> 'user', 'passwd'.
splitport(host)
splitport('host:port') --> 'host', 'port'.
splitquery(url)
splitquery('/path?query') --> '/path', 'query'.
splittag(url)
splittag('/path#tag') --> '/path', 'tag'.
splittype(url)
splittype('type:opaquestring') --> 'type', 'opaquestring'.
splituser(host)
splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'.
splitvalue(attr)
splitvalue('attr=value') --> 'attr', 'value'.
thishost()
Return the IP address of the current host.
unquote(s)
unquote('abc%20def') -> 'abc def'.
unquote_plus(s)
unquote('%7e/abc+def') -> '~/abc def'
unwrap(url)
unwrap('<URL:type://host/path>') --> 'type://host/path'.
url2pathname(url)
OS-specific conversion from a relative URL of the 'file' scheme
to a file system path; not recommended for general use.
urlcleanup()
urlencode(query, doseq=0)
Encode a sequence of two-element tuples or dictionary into a URL query string.
If any values in the query arg are sequences and doseq is true, each
sequence element is converted to a separate parameter.
If the query arg is a sequence of two-element tuples, the order of the
parameters in the output will match the order of parameters in the
input.
urlopen(url, data=None, head=None,proxies=None, context=None)
Create a file-like object for the specified URL to read from.
reporthook=None, data=None, context=None)
head 是訪問頁面是請求的對象:網頁仍是程序
### 2.urlparse:
FUNCTIONS
parse_qs(qs, keep_blank_values=0, strict_parsing=0)
Parse a query given as a string argument.
Arguments:
qs: percent-encoded query string to be parsed
keep_blank_values: flag indicating whether blank values in
percent-encoded queries should be treated as blank strings.
A true value indicates that blanks should be retained as
blank strings. The default false value indicates that
blank values are to be ignored and treated as if they were
not included.
strict_parsing: flag indicating what to do with parsing errors.
If false (the default), errors are silently ignored.
If true, errors raise a ValueError exception.
parse_qsl(qs, keep_blank_values=0, strict_parsing=0)
Parse a query given as a string argument.
Arguments:
qs: percent-encoded query string to be parsed
keep_blank_values: flag indicating whether blank values in
percent-encoded queries should be treated as blank strings. A
true value indicates that blanks should be retained as blank
strings. The default false value indicates that blank values
are to be ignored and treated as if they were not included.
strict_parsing: flag indicating what to do with parsing errors. If
false (the default), errors are silently ignored. If true,
errors raise a ValueError exception.
Returns a list, as G-d intended.
urldefrag(url)
Removes any existing fragment from URL.
Returns a tuple of the defragmented URL and the fragment. If
the URL contained no fragments, the second element is the
empty string.
urljoin(base, url, allow_fragments=True)
Join a base URL and a possibly relative URL to form an absolute
interpretation of the latter.
urlparse(url, scheme='', allow_fragments=True)
Parse a URL into 6 components:
<scheme>://<netloc>/<path>;<params>?<query>#<fragment>
Return a 6-tuple: (scheme, netloc, path, params, query, fragment).
Note that we don't break the components up in smaller bits
(e.g. netloc is a single string) and we don't expand % escapes.
urlsplit(url, scheme='', allow_fragments=True)
Parse a URL into 5 components:
<scheme>://<netloc>/<path>?<query>#<fragment>
Return a 5-tuple: (scheme, netloc, path, query, fragment).
Note that we don't break the components up in smaller bits
(e.g. netloc is a single string) and we don't expand % escapes.
urlunparse(data)
Put a parsed URL back together again. This may result in a
slightly different, but equivalent URL, if the URL that was parsed
originally had redundant delimiters, e.g. a ? with an empty query
(the draft states that these are equivalent).
urlunsplit(data)
Combine the elements of a tuple as returned by urlsplit() into a
complete URL as a string. The data argument can be any five-item iterable.
This may result in a slightly different, but equivalent URL, if the URL that
was parsed originally had unnecessary delimiters (for example, a ? with an
empty query; the RFC states that these are equivalent).
### 3.time,datetime #時間
### 4.sys #系統有關
### 5.logging #日誌
### 6.json #序列化
### 7.pickle #以二進制的編碼方式寫入文件
### 8.os #操做與文件夾相關和不一樣操做系統
### 9.fileinput #文件的每一行
### 10.random #隨機數
### 11.shelve #往硬盤裏面寫入文件
### 12.re #正則表達式
```
compile(pattern, flags=0)
Compile a regular expression pattern, returning a pattern object.
escape(pattern)
Escape all non-alphanumeric characters in pattern.
findall(pattern, string, flags=0)
Return a list of all non-overlapping matches in the string.
If one or more groups are present in the pattern, return a
list of groups; this will be a list of tuples if the pattern
has more than one group.
Empty matches are included in the result.
finditer(pattern, string, flags=0)
Return an iterator over all non-overlapping matches in the
string. For each match, the iterator returns a match object.
Empty matches are included in the result.
match(pattern, string, flags=0)
Try to apply the pattern at the start of the string, returning
a match object, or None if no match was found.
purge()
Clear the regular expression cache
search(pattern, string, flags=0)
Scan through string looking for a match to the pattern, returning
a match object, or None if no match was found.
split(pattern, string, maxsplit=0, flags=0)
Split the source string by the occurrences of the pattern,
returning a list containing the resulting substrings.
sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a string, backslash escapes in it are processed. If it is
a callable, it's passed the match object and must return
a replacement string to be used.
subn(pattern, repl, string, count=0, flags=0)
Return a 2-tuple containing (new_string, number).
new_string is the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in the source
string by the replacement repl. number is the number of
substitutions that were made. repl can be either a string or a
callable; if a string, backslash escapes in it are processed.
If it is a callable, it's passed the match object and must
return a replacement string to be used.
template(pattern, flags=0)
Compile a template pattern, returning a pattern object
```
### 13.cgi #編寫動態網頁 ++詳細請查看官方文檔+++ 1.咱們自定義的模塊要放在python.exe的根目錄下2. a.import 模塊名 b.from 模塊名 import 函數名 c.import 模塊名 as 新名字3. 定義包名:在python的運行環境下新建一個包(文件夾),而後把模塊文件、新建的一個__init__.py放進包裏面,__init__裏面定義__all__來限制哪些模塊的文件能夠進出。最後經過import 包名.模塊名導入### 14.數據的永久性存儲,序列化 ----pickle```#寫入import picklemy_list = [1,2,(3,4),{'name':'zhangsan'}]pickle_file = open(path,'wb')pickle.dump(my_list,pick)_file)#讀取pickle_file = open(path.'rb')pickle.load(pickle_file)```### 15.shelve```import shelved = shelve.open('example.s')d['key'] = 'some_value'd.close()d2 = shelve.open('example.s')print d2```## 二十6、Django+ 使用eclipse[推薦下載網址](https://www.eclipse.org/downloads/)+ 新建項目的時候必需要django-admin.py拷貝到要新建文件夾的父級目錄下,也就是跟即將新建的目錄在同一文件夾下+ django1.9版本的已經將使用模塊新建表的命令從python manage.py syncdb改爲python manage.py migrate+ 新建管理數據庫的用戶:```pythion manage.py createsuperuser```+ setting.py文件裏面須要配置模板的路徑、項目實例的名字