Python rat la co ban - s3-ap-southeast-1.amazonaws.com · Có thể truy xuất từng ký tự...

Preview:

Citation preview

GiớithiệuHiệnnay,Pythonlàmộttrongnhữngngônngữlậptrìnhđangđượcchúýbởitínhđadạngvềứngdụng,thưviệnphongphúvàcộngđồngđôngđảo.

ĐãlàmviệcvớiPHP10năm,vàcónhữngtácvụmàPHPkhómàthựchiệntốiưuđược,khiếnmìnhphảitiếpcậnvớiPythontronggiaiđoạnnày.

CuốnsáchnhỏnàyđượcviếttrongquátrìnhmìnhbắtđầuhọcPythonvàgiảiquyếtcácbàitoáncơbảntheonhucầucủamình.

HyvọngnhữngghichépcủamìnhcũngsẽgiúpíchchonhữngaiđangquantâmđếnviệcứngdụngPythonvàocôngviệcvàxửlýhiệntại.

Mụclục

Sáchđượcchialàm15chương,mỗichươngsẽtrìnhbày1khíacạnhcủaPythonmàmìnhsẽgặpphảivàsẽhữuích

khibiếtcáckiếnthứcnàytrongviệcápdụngPythonvàocôngviệctrongtươnglai.

1. Helloworld

2. Cúpháp

3. Phânchiamodule

4. Class

5. Thaotáctrêntậptin

6. Xửlýhìnhảnh

7. XửlýfileJSON

8. XửlýfileXML

9. KếtnốiMySQL

10. KếtnốiRedis

11. KếtnốiMemcached

12. KếtnốiRabbitMQ

13. RestfulClient

14. GởiemailvớiSMTP

15. SocketProgramming

Tácgiả

Tên:VõDuyTuấn

Email:tuanmaster2012@gmail.com

Facebook:https://www.facebook.com/voduytuan

Chương1.HelloworldPythonlàmộtngônngữphiêndịch(InterpreterLanguage),tứclàkhôngcầnbuildthànhfilethựcthimàchạytrựctiếpnhưPHP.

HiệntạiPythoncó2nhánhchínhlà2.xvà3.x.Ởnhánh2.xđãdừngpháttriểnvàđangđứngởphiênbản2.7.NhánhPython3.xthìvẫnđangđượctiếptụcpháttriển.

WebsitechínhthứccủaPython:www.python.org

Càiđặt

PythonhỗtrợhầuhếtcácnềntảngvàrấtdễtìmthấysẵntrênmộtsốhệđiềuhànhnhưMacOS…

ĐểbiếtlàhệthốngcủabạnđãcàiPythonchưa,cóthểvàomànhìnhcommandlinevàgõ:

$python--version

Nếuđãcàiđặtpythonthìsẽhiểnthịthôngtinphiênbảnpython.NếubáolỗithìđồngnghĩavớibạnchưacàiđặtPython.

CóthểthamkhảocáchcàiđặtPythontại:https://www.python.org/downloads/

Côngcụpháttriển

Chỉcầndùngmộttexteditorlàbạncóthểviếtđượccodepythonhoặccóthểdùngcáccôngcụcaocấphơn(IDE)nhưAptana,PyCharm…CácIDEthườnghỗtrợthêmquátrìnhphântíchcúphápdònglệnh,debug…trongphạmvicuốnsáchnhỏnàythìmìnhhướngđếncáchthựcthipythonbằngdònglệnh.

Helloworld

Tạomộtfilecótênlà helloworld.py vàcónộidungnhưsau:

print'Helloworld'

print làlệnhcơbảnnhấtđểxuấtmộtbiếnra(thườnglàmànhình)

Sauđó,vàomànhìnhcommandline,dichuyểnđếnthưmụcchứafilenàyvàgõ.

$pythonhelloworld.py

Nếuthấyxuấthiệndòngchữ Helloworld tứclàbạnđãhoànthànhviệcviếtứngdụngpythonđầutiên.

Chương2.Cúpháp2.1.Biếnsố

Khaibáobiếnbằngmộtcâulệnhgán.

a=1

bạncóthểgánnhiềuloạigiátrị(số,chuỗi)chomộtbiến.

a=1

a='HelloWorld'

a=[1,2,3]

a=[1.2,'Hello','W',2]

2.2.Toántửsốhọc

Pythoncũnghỗtrợmộtsốtoántửtoánhọcthôngdụngnhư:

+ phépcộng

- phéptrừ

* phépnhân

/ phépchia

% phépchialấydư(modulo)

2.3.BooleanvàToántửlogic

Giátrịđúngvàsaitươngứnglà True và False .

not đểđảogiátrị.

and phéptínhlogicvà(AND)

or phéptínhlogichoặc(OR)

Mộtsốphépsosánhthôngthườngnhư < (béhơn), <= (béhơnhoặcbằng), > (lớnhơn), >= (lớnhơnhoặcbằng), ==(bằng), != (khác)đểsosánh2giátrị.

Hỗtrợdạngsosánhképnhư:

x=2

1<x<3#True

10<x<20#False

3>x<=2#True

2==x<4#True

Toántửkiểmtraphầntửtrongmộttậphợp:- in kiểmtracótồntại- notin kiểmkhôngtồntại

'good'in'thisisagreateexample'#F

alse

'good'notin'thisisagreateexample'#True

2.4.Cấutrúcđiềukhiển

Pythonhỗtrợmộtsốcấutrúcđiềukhiểnthôngdụng.Hầuhếtcáccấutrúcđiềukhiểnđềudựavàothụtđầudòng(indention)đểtạothànhmộtblockxửlý,thayvìsửdụng{…} nhưcácngônngữkhác(PHP,Javascript)###2.4.1.If…elif…else

ifcondition1:

indentedStatementBlockForTrueCondition1

elifcondition2:

indentedStatementBlockForFirstTrueCondition2

elifcondition3:

indentedStatementBlockForFirstTrueCondition3

elifcondition4:

indentedStatementBlockForFirstTrueCondition4

else:

indentedStatementBlockForEachConditionFalse

2.4.2.Switch…case

Pythonkhôngcócấutrúc switch…case

2.4.3.For…in

foriterating_varinsequence:

statements(s)

Vídụ:

forletterin'Python':#FirstExample

print'CurrentLetter:',letter

fruits=['banana','apple','mango']

forfruitinfruits:#SecondExample

print'Currentfruit:',fruit

print"Goodbye!"

Kếtquảhiểnthịcủavídụtrên:

CurrentLetter:P

CurrentLetter:y

CurrentLetter:t

CurrentLetter:h

CurrentLetter:o

CurrentLetter:n

Currentfruit:banana

Currentfruit:apple

Currentfruit:mango

Goodbye!

2.4.4.While

whileexpression:

statement(s)

Vídụ:

count=0

while(count<9):

print'Thecountis:',count

count=count+1

print"Goodbye!"

Kếtquảhiểnthịcủavídụtrên:

Thecountis:0

Thecountis:1

Thecountis:2

Thecountis:3

Thecountis:4

Thecountis:5

Thecountis:6

Thecountis:7

Thecountis:8

Goodbye!

2.5.Hàm

Khaibáohàmtheocúpháp:

deffunctionname(param,param2,..):

statements(s)

HàmnếukhôngtrảdữliệuthìmặcđịnhsẽtrảvềgiátrịNone

Vídụkhaibáohàmtínhvàtrảvềgiátrịtổngcủa2thamsốđầuvào:

defsum(a,b):

return(a+b)

Cáchgọihàm:

sum(1,2)

(trảvềgiátrịlà3)

Hàmcóhỗtrợgiátrịmặcđịnhchothamsốkhikhôngtruyềnvào.Vídụhàmsau:

defplus(c,d=10):

return(c+d)

Nếugọihàmtrênnhưsau:

plus(2)

(kếtquảtrảvềlà12)

MộtkhácbiệttrongcáchgọihàmcủaPythonsovớiPHPlàchúngtacóthểthayđổithứtựthamsốtruyềnvàobằng

cáchđặttênthamsốkhigọihàm.Vídụtacóthểgọihàmsum(a,b) ởvídụtrênbằngcáchtruyềnthamsố b trước anhưsau:

sum(b=1,a=10)

2.6.Xửlýchuỗi

Mộtchuỗicóthểkhaibáobằngdấunháyđôi " hoặcđơn' .Vídụcácchuỗisau:

str1="Hello"

str2='world'

Cóthểtruyxuấttừngkýtựtrongmộtchuỗitheohìnhthứcindex,vídụ: str1[0] , str1[1]…Cóthểsửdụng3dấunháy(đôihoặcđơn)đểkhaibáochuỗitrênnhiềudòng.Vídụ:

paragraph="""Thisisline1

Thisisline2

Thisisline3"""

2.6.1.Nốichuỗi

Cóthểtạomộtchuỗidàitừviệcnốicácchuỗilạitheocúpháp:

str=str1+""+str2

2.6.2.Tríchxuấtchuỗicon

Cóthểtạocácchuỗiconthôngquatoántửlấykhoản[start:end] (range).Mặcđịnh start làtừvịtríđầuchuỗi( 0 )và end làđếnvịtrícuốichuỗi.Vídụ:

str='Helloworld'

printstr[0:4]

(Hiểnthị"Hell")

printstr[:4]

(Hiểnthị"Hell")

printstr[-3:]

(Hiểnthị"rld")

printstr[6:-3]

(Hiểnthị"wo")

2.6.3.Lấyđộdàicủachuỗi

Sửdụnghàm len(...) đểtrảvềđộdàicủachuỗi.Vídụ:

count=len("Helloworld")

(countcógiátrị11)

2.6.4.Tìm&thaythếnộidung

Cóthểtìmvàthaythếtrongchuỗibằngcáchgọiphương

thức replace(search,replace[,max]) củamộtchuỗi.Vídụ:

str='Helloworld'

newstr=str.replace('Hello','Bye')

printnewstr

(Sẽhiểnthịchuỗi"Byeworld"trênmànhình)

2.6.5.Tìmvịtríchuỗicon

Cóthểtìmvịtrícủamộtchuỗicontrongchuỗilớnbằngcáchgọiphươngthức find(str,beg=0end=len(string)) .Bắtđầulàvịtrí 0 ,nếukhôngtìmrathìtrảvề -1 .Vídụ:

str='Helloworld'

printstr.find('world')

(hiểnthị6)

printstr.find('Bye');

(hiểnthị-1)

Hàm find() sẽtìmtheothứtựtừtráiquaphảicủachuỗi,

tứclàtừlầnxuấthiệnđầutiên.Cóthểdùnghàm rfind()đểtìmtheovịtrítừcuốichuỗivềphíatrước.

2.6.6.Táchchuỗi

Cóthểtáchchuỗidựatheomộtchuỗidelimeterbằngcáchgọiphươngthức split(str="",num=string.count(str)) .Vídụ:

str='Helloworld'

printstr.split('')

(Trảvềmộtmảngcó2phầntửlà2chuỗi"Hello"và

"world")

Cóthểsửdụnghàm splitlines() đểtáchchuỗitheotừnghàngvàloạibỏkýtựNEWLINE.

2.6.7.Trimkýtựkhoẳngtrắng

Cóthểloạibỏcáckýtự(mặcđịnhlàkýtựkhoảngtrắng)trướcvàsaumộtchuỗi,bằngcáchgọicácphươngthứcsau:

strip([chars]) :loạibỏtrướcvàsauchuỗi

lstrip([chars]) :loạibỏphíatrướcchuỗi

rstrip([chars]) :loạibỏphíasauchuỗi

2.6.8.Mộtsốhàmxửlýchuỗi

isnumeric() :Kiểmtramộtchuỗicóphảilàchuỗisố

lower() :Chuyểnchuỗihếtthànhchữthường

upper() :ChuyểnchuỗihếtthànhchữHOA

2.7.List

ListtrongPythonlàcấutrúcmảngvàcácphầntửcóindexcóthứtự.KhôngnhưPHP,keycủamộtmảngcóthểvừalàsố,vừalàchuỗi(associatedarray).

TrongPython,muốntạomộtmảngcókeylàchuỗithìsẽsửdụngcấutrúcDictionary(phầntiếptiếp).Trongphầnnày,chúngtasẽnóiđếnList.MộtListđượckhaibáonhưmảngtrongJSON.Sửdụng [..] đểkhaibáomộtmảng.Vídụ:

numbers=[1,2,3,4,5]

names=['Marry','Peter']

Cóthểtruyxuấttừngphầntửcủamảngbằngindex,phầntửđầutiêncóthứtựlà 0 .Vídụ:

printnumbers[0]

(Hiểnthị1)

printnumbers[-3]

(Hiểnthị3)

printnames[1]

(Hiểnthị'Peter')

Đểbiếtđượcsốlượngphầntửcủa1List,cóthểsửdụnghàm len(array) đểlấysốlượngphầntửcủamảngthamsốtruyềnvào.

2.7.1.Kiểmtrasựtồntạicủamộtphầntử

2.7.1.1.KiểmtratheoIndex

Trongnhiềutrườnghợpbạnmuốntruyxuấtmộtphầntửbấtkỳ(dựavàoindex)củamảngthìnếutruyxuấtđếnmộtphầntửkhôngtồntạithìứngdụngsẽbáolỗi.Dođó,trướckhitruyxuấtmộtphầntử,bạncầnkiểmtraxemphầntửnàyđãtồntạihaychưa.Hiệntạipythonkhônghỗtrợhàmnàođểkiểmtrasựtồntạicủamộtphầntửtrongmảng.

Có2cáchthườngthấyđểkiểmtrađólà“Lookbeforeyouleap”(LBYL)và“Easiertoaskforgivenessthanpermission”(EAFP).

Vídụvề“Lookbeforeyouleap(LBYL)”:

ifindex<len(array):

array[index]

else:

#handlethis

Vídụvề“Easiertoaskforgivenessthanpermission”(EAFP):

try:

array[index]

exceptIndexError:

#handlethis

2.7.1.2.Kiểmtratheogiátrị

Đểkiểmtramộtgiátrịcótồntại/khôngtồntạitrongmảnghaykhôngthìcóthểsửdụngtoántử in / notin .Vídụ:

mylist=['a','b','c']

print'a'inmylist

(HiểnthịTrue)

print'b'notinmylist

(HiểnthịFalse)

2.7.2.Tríchxuấtmảngcon

Tươngtựnhưchuỗi,tóthểtạocácmảngconthôngquatoántửlấykhoản [start:end] (range).Mặcđịnh start là

từvịtríđầuchuỗi( 0 )và end làđếnvịtrícuốichuỗi.Vídụ:

numbers=['a','b','c','d']

printnumbers[:2]

(Hiểnthị['a','b'])

printnumbers[-2:]

(Hiểnthị['c','d'])

2.7.3.Xóaphầntửcủamảng

Cóthểxóamộtphầntửthôngquatoántử del .Thứtựcủacácphầntửsẽdịchchuyểntùyvàovịtrícủaphầntửbịxóa.Vídụ:

numbers=[1,2,3,4,5]

delnumbers[0]

printnumbers

(Hiểnthị[2,3,4,5])

Bạncóthểxóamộtkhoảndựavàotoántửlấykhoản[start:end] .Vídụ:

numbers=[1,2,3,4,5,6,7]

delnumbers[2:4]

printnumbers

(Hiểnthị[1,2,5,6,7])

2.7.4.Nối2mảng

Bạncóthểsửdụngtoántử + đểnốigiátrịcủa2mảngvàtạoramộtmảnglớncósốlượngphầntửlàtổngsốlượngphầntửcủa2mảngcon.Vídụ:

a=[1,2]

b=[1,3]

printa+b

(Hiểnthị[1,2,1,3])

2.7.5.Thêmphầntửvàomảng

Nếubạnmuốnthêmphầntửvàomộtmảngđãtồntại,hãydùngphươngthức list.append(newvalue) đểthêmphầntửcógiátrị newvalue vàocuốimảng list .Vídụ:

numbers=[1,2,3]

numbers.append(4)

printnumbers

(Hiểnthị[1,2,3,4]

2.7.6.Lấyphầntửcuốimảng

Nếumuốnlấyphầntửcuốicùngcủamảngrakhỏimảng,cóthểsửdụngphươngthức list.pop() ,sẽtrảvềgiátrịcủaphầntửcuốicùngvàmảngbâygiờsẽkhôngcònphầntửnày.

numbers=[1,2,3]

mynumber=numbers.pop()

printmynumber

(Hiểnthị3)

printnumbers

(Hiểnthị[1,2])

2.7.7.Tìmmộtgiátrịtrongmảng

Nếubạnmuốntìmvịtrí(index)củamộtgiátrịtrongmột

mảng,cóthểdùngphươngthức list.index(obj) .Nếutìmthấysẽtrảvềindexcủaphầntửđầutiêntìmthấy.NếukhôngtìmthấysẽquăngException.Vídụ:

aList=[123,'xyz','zara','abc'];

print"Indexforxyz:",aList.index('xyz')

print"Indexforzara:",aList.index('zara')

Khichạysẽhiểnthịkếtquả:

Indexforxyz:1

Indexforzara:2

2.7.8.Đảongượcgiátrịcủamảng

Đểđảongượcthứtựcácgiátrịcủamộtmảng,sửdụngphươngthức list.reverse() .Phươngthứcnàykhôngtrảvềkếtquảmàthayđổitrựctiếpmảng list .Vídụ:

numbers=[1,2,3,4]

numbers.reverse()

printnumbers

(Hiểnthị[4,3,2,1])

2.7.9.Sắpxếpgiátrịcácphầntử

Đểsắpxếpthứtựcủagiátrịtrongmảng,sửdụngphươngthức list.sort([func]) đểsắpxếp.Nếuthamsốđầuvàolàhàm func khôngtruyềnvàothìmặcđịnhlàsắpxếptheogiátrịtăngdần.Phươngthứcnàykhôngtrảvềkếtquảmàthayđổitrựctiếpmảng list .Vídụ:

aList=[123,'xyz','zara','abc','xyz']

aList.sort()

print"List:",aList

(HiểnthịList:[123,'abc','xyz','xyz','zara'

])

Cáchtriểnkhaihàmcompare func() cũnggiốngnhưhàmusorttrongPHP.Hàmtrảvềcácgiátrị 0 , -1 và 1 .

2.8.Tuple

Tuplecũnglàmộtcấutrúcmảng,tươngtựnhưcấutrúcList.MộtsốđiểmkhácnhaucơbảnlàkhaibáoTuplesửdụngcặpdấungoặc (...) vàmộttupleđãđượckhaibáorồithìkhôngthayđổiđượcgiátrị(immutable)vàkhônghỗtrợcácphươngthứcnhư append() , pop()…Vídụ:

mytuple=('x','y','z')

printmytuple

(Hiểnthị('x','y','z'))

VẫnhỗtrợcáccáchđểtruyxuấtphầntửgiốngListnhưlàtruyxuấttheoindex,range,tìmkiếm…

2.9.Dictionary

Dictionarycũnglàmộtcấutrúcmảng,nhưngcácphầntửbaogồmkeyvàvalue.NếubạncóbiếtJSONthìcấutrúcDictionarytươngtựnhưmộtobjectjson.MộtDictionaryđượckhaibáobằngcặpdấungoặc {...} .Vídụ:

point={'x':1,'y':2}

Truyxuấtmộtgiátrịdựavàokeycủađốitượng.Vídụ:

point={'x':3,'y':6,'z':9}

printpoint[x]

(Hiểnthị3)

2.9.1.Thêmmộtphầntử

Đểthêmmộtphầntửvàođốitượngđãkhaibáo,sửdụngcấutrúc dict[key]=value .Vídụ:

user={'name':'Jone','age':30}

user['country']='Vietnam'

printuser

(Hiểnthị{'country':'Vietnam','age':30,'name':

'Jone'})

2.9.2.Mộtsốhàm,phươngthứcthôngdụng:

dict.clear() :Xóatoànbộdữliệubêntrongđối

tượng

dict.copy() :Trảvềmộtbảncopycủađốitượng

dict.fromkeys(seq[,value]) :Tạomộtđốitượngvới

danhsáchkeytừseqvànếucótruyền value thìlấy

đólàmgiátrịchocácphầntử.

dict.has_key(key) :kiểmtramộtkeycótồntạitrong

đốitượnghaykhông.

dict.keys() :TrảvềmộtListchứacáckey

dict.values() :TrảvềmộtListchứacácvalue

Chương3.PhânchiamoduleTấtcảvídụchođếnthờiđiểmnàyđềuđượcthựcthitrongcommandlinehoặctừmộtfilepython .py .Tuynhiên,đốivớicácứngdụnglớn,cónhiềuchứcnăngthìphânchianhỏdựánthànhcácfilekhácnhausẽgiúpdễbảotrìvàtáisửdụngcácthànhphầnđãthiếtkế.

Chươngnàysẽgiúpbạnthiếtkếcáctínhnăngtheomôhìnhcácmodulevàkhicầnthìsẽgọifiletươngứngvàsửdụng.

3.1.Cácloạimodule/thưviện

Có3loạimodulethườngthấylà:

1. ViếtbằngPython:cóphầnmởrộnglà .py

2. Cácthưviệnliênkếtđộng:cóphầnmởrộnglà .dll ,

.pyd , .so , .sl ,…

3. C-Moduleliênkếtvớitrìnhphiêndịch.

3.2.Đườngdẫntìmđểloadmodule

Đểtảimộtmodulevàoscriptcủabạn,sửdụngcúphápđơngiản:

importmodulename

khigặpcâulệnhtrênthìtrìnhbiêndịchsẽtiếnhànhtìmkiếmfilemoduletươngứngtheothứtựthưmụcsau:

1. Thưmụchiệnhànhmàscriptđanggọi

2. CácthưmụctrongPYTHONPATH(nếucóset)

3. CácthưmụccàiđặtchuẩntrênLinux/Unix..

Cóthểbiếtđượcđườngdẫnmàmộtmoduleđãđượcloadbằngđoạncodedướiđây:

importmath

math.__file__

(Vídụtrảvề'/usr/lib/python2.5/lib-dynload/math.

so')

importrandom

random.__file__

(Vídụtrảvề'/usr/lib/python2.5/random.pyc')

3.3.Lấydanhsáchthuộctínhvàphươngthứccủamộtmodule

Đểlấyđượcdanhsáchcácthuộctínhvàphươngthứcmàmodulehỗtrợ,sửdụnghàm dir(modulename) .Vídụ:

dir(math)

['__doc__','__file__','__name__','__package__',

'acos','acosh','asin','asinh','atan','atan2',

'atanh','ceil','copysign','cos','cosh','degree

s','e','erf','erfc','exp','expm1','fabs','fa

ctorial','floor','fmod','frexp','fsum','gamma'

,'hypot','isinf','isnan','ldexp','lgamma','lo

g','log10','log1p','modf','pi','pow','radians

','sin','sinh','sqrt','tan','tanh','trunc']

Cóthểgọihàm dir() khôngtruyềnthamsốđểlấycácthuộctínhvàphươngthứccủascopehiệntạiđangthựcthi.

3.4.Cáchkhaibáovàsửdụngmodule

Giảsửbạntạomộtfilepython mymath.py cónộidungnhưsau:

defcong(a,b):

returna+b

deftru(a,b):

returna-b

defnhan(a,b):

returna*b

Sauđó,tạomộtfilecótên myexample.py ,trongcùngthưmụcvớifile mymath.py vừatạoởtrên,cónộidungnhưsau:

importmymath

num1=1

num2=2

print'Tonghaisola:',mymath.cong(num1,num2)

Vàocommandline,thựchiệngọifilemyexamplenhưsau:

$pythonmyexample.py

Saukhithựchiệnsẽhiểnthịlênmànhìnhlà

Tonghaisola:3

3.5.Packagemodule

Cóthểgomnhiềumodule .py vàomộtthưmụcvàtênthưmụclàtêncủapackagevàtạomộtfile __init__.py trongthưmụcnày.

Nhưvậy,cấutrúcthưcủamộtpackagesẽnhưsau:

|--mypack

||--__init__.py

||--mymodule1.py

||--mymodule2.py

|

Cóthểsửdụng mymodule1 theocúphápimportsau:

importmypack.mymodule1

hoặc

importmypack.mymodule1asmymodule1

hoặc

importmypack.mymodule1asmod

Khisửdụngmộtmodulethuộcmộtpackagethìcáclệnhtrongfile __init__.py sẽđượcthựchiệntrước.Thôngthườngthìfile __init__.py sẽrỗng.

Cóthểtạocácsubpackagebêntrongmộtpackagetheođúngcấutrúcthưmục,cófile __init__.py .Vídụ:

importmypack.mysubpack.mysubsubpack.module

Chương4.ClassLậptrìnhhướngđốitượnglàmộtkháiniệmkhôngthểthiếutronghầuhếtcácngônngữthôngdụnghiệnnay.PythoncũnghỗtrợlậptrìnhhướngđốitượngvớicáckháiniệmClass,Object,Override…

4.1.KhaibáomộtClass

Khaibáomộtclasstheocúphápsau:

classmyclass([parentclass]):

assignments

def__init__(self):

statements

defmethod():

statements

defmethod2():

statements

Vídụmộtclass:

classanimal():

name=''

name=''

age=0

def__init__(self,name='',age=0):

self.name=name

self.age=age

defshow(self):

print'Mynameis',self.name

defrun(self):

print'Animalisrunning...'

defgo(self):

print'Animalisgoing...'

classdog(animal):

defrun(self):

print'Dogisrunning...'

myanimal=animal()

myanimal.show()

myanimal.run()

myanimal.go()

mydog=dog('Lucy')

mydog.show()

mydog.run()

mydog.go()

Saukhithựcthisẽchorakếtquả:

MyNameis

Animalisrunning...

Animalisgoing...

MyNameisLucy

Dogisrunning...

Animalisgoing...

Trongvídụtrênthì:

animal và dog là2class.Trongđóclass dog kếthừa

từclasschalà animal nênsẽcócácphươngthứccủa

class animal .

name và age làthuộctính(Attribute)củaclass.

Phươngthức __init__(self) làhàmtạocủaclass.

Hàmnàysẽđượcgọimỗikhicómộtobjectmớiđược

tạo(từmộtclass),gọilàquátrìnhtạoinstance.

show() , run() và go() là2phươngthứccủa2class.

Khikhaibáophươngthứccókèmthamsố self dùng

đểtruycậpngượclạiobjectđanggọi.Lúcgọiphương

thứcthìkhôngcầntruyềnthamsốnày.

Phươngthức run() củaclass dog gọilà override

củaphươngthức run() củaclass animal .

Chương5.ThaotáctrêntậptinvàThưmụcNộidungchươngnàysẽhướngdẫncácthaotácliênquanđếntậptinvàthưmục.

5.1.Tậptin(File)

5.1.1.Mởfile

Trướckhimuốnđọchoặcghifile,bạncầncóthaotácmởfiletheocúpháp:

fh=open(filepath,mode)

Trongđó, filepath làđườngdẫncủafilesẽmởvà modelàchếđộđểmở.Cómộtsốchếđộlà:

r :mởđểđọcnộidung(mặcđịnh)

w :mởđểghinộidung

a :mởđểghithêmnộidungvàocuốifile.

r+ :mởđểđọcvàghi.Contrỏnằmởđầufile.

w+ :mởđểđọcvàghi.Ghiđènếufileđãtồntại,nếu

filechưatồntạithìtạofilemớiđểghi.

a+ :mởđểđọcvàthêmvàocuốifile.Contrỏnằmở

cuốifile.Nếufilechưatồntạithìtạofilemớiđểghi.

Mặcđịnhlàmởfiletext,nếumuốnmởfilenhịphân(binary)thìthêm b ,vídụ: rb , wb , ab , rb+ , wb+ , ab+ .

Vídụ:

f1=open('test.txt','r')

f2=open('access_log','a+'

Saukhigọihàm open() thànhcôngthìsẽtrảvềmộtobjectcócácthuộctính:

closed :Truenếufileđãđóng

mode :chếđộkhimởfile

name :têncủafile

softspace :cờđánhdấusoftspacekhidùngvớihàm

print

5.1.2.Đọcnộidungtừfile

Saukhifileđãmởởchếđộđọcthìgọiphươngthứcread([count]) đểtrảvềtoànbộnộidungcủafile.Vídụ:

f1=open('test.txt','r')

data=f1.read();

Hàm read() cónhậnmộtthamsốlàsốlượngbytemuốnđọc.Nếukhôngtruyềnvàothìsẽđọchếtnộidungcủafile.Vídụ:

f2=open('log.txt','r')

buffdata=f2.read(1024)

5.1.3.Ghinộidungvàofile

Nếufileđượcmởởchếđộcóthểghithìcóthểdùngphươngthức write() đểghimộtnộidungvàofile.Vídụ:

f2=open('access_log','a+')

f2.write('Attackdetected')

5.1.4.Đóngfileđãmở

Saukhihoàntấtcácthaotácđọcghifilethìgọiphươngthức close() đểđóngfileđãmở.Vídụ:

f1.close()

f2.close()

5.1.5.Đổitênfile

Sửdụngphươngthức os.rename(old,new) đểđổitênmộtfile.Vídụ:

importos

os.rename('test.txt','test_new.txt')

5.1.6.Xóafile

Sửdụngphươngthức os.remove(file) đểxóamộtfile

khỏihệthống.Vídụ:

importos

os.remove('test.txt')

5.2.Thưmục(Directory)

5.2.1.Tạothưmục

Sửdụngphươngthức os.mkdir(dir) đểtạothưmục.Vídụ:

importos

os.mkdir('test')

5.2.2.Xóathưmục

Sửdụngphươngthức os.rmdir(dir) đểxóamộtthưmục.Vídụ:

importos

os.rmdir('test')

5.2.3.Đọcnộidungthưmục

Sửdụngphươngthức os.listdir(dir) đểlấydanhsáchtậptin,thưmụccủathưmục dir .Khigọisẽtrảvềmộtmảngdanhsáchcáctậptin,thưmục.Vídụ:

importos

allfiles=os.listdir('/root/downloads')

printallfiles

5.3.Moduleos

Module os làmộtmodulecónhiềuphươngthứchữuíchtrongviệclàmviệcvớicácfilevàdirectory,như:

os.chdir(path) :đổithưmụchiệnhành

os.getcwd() :trảvềthưmụchiệnhành

os.chmod(path,mode) :CHMODmộtđườngdẫn

os.chown(path,uid,gid) :CHOWNmộtđườngdẫn

os.makedirs(path[,mode]) :tạođườngdẫn(có

recursive)

os.removedirs(path) :xóamộtđườngdẫn(có

recursive)

Xemthêmtạihttps://docs.python.org/2/library/os.html

5.4.Moduleos.path

Module os.path hỗtrợcácphươngthứcgiúpthaotácnhanhchóngvàthuậntiệnhơntrênđườngdẫn.

os.path.exists(path) :kiểmtra1đườngdẫncótồn

tạihaykhông

os.path.getsize(path) :lấyfilesize(byte)

os.path.isfile(path) :kiểmtraxemcóphảilàmột

filethôngthường

os.path.isdir(path) :kiểmtraxemcóphảilàmột

thưmục

os.path.dirname(path) :trảvềtênthưmụccủapath

os.path.getatime(path) :trảvềthờigiantruycập

mớinhất

os.path.getmtime(path) :trảvềthờigianchỉnhsửa

cuốicùng

os.path.getctime(path) :trảvềthờigianchỉnhsửa

cuốicủametadatatrênmộtsốhệthống.Hoặctrảvề

thờigiantạofiletrênWindows.

Xemthêmtạihttps://docs.python.org/2/library/os.path.html

Chương6.XửlýhìnhảnhSửdụngthưviệnPillow(PILFork)đểtiếnhànhcácthaotácxửlýhìnhảnhđơngiảnnhưresize,crop,rotate…

6.1.CàiđặtPIL

Vàotrangwebsauđểdownload/càiđặtpackagePILchopythoncủabạnhttp://pillow.readthedocs.org/en/latest/installation.html

SaukhicàiđặtthìcóthểsửdụngcácmoduletrongpackageIPL

fromPILimportImage

6.2.Mởfile

fromPILimportImage

im=Image.open("photo.jpg")

Saukhimởfilehìnhthànhcôngthìcóthểthaotáctrênđốitượng im .

6.3.Ghifile

Từđốitượng Image cóthểlưufilexuốngmáytínhbằngphươngthức save(path,type) .Vídụ:

...

im.save('photo_new.jpg','JPEG')

6.4.Tạothumbnail

Sửdụngphươngthức thumbnail nhưsau:

fromPILimportImage

im=Image.open('photo.jpg')

im.thumbnail((100,100))

im.save('photo_thumbnail.jpg','JPEG')

thumbnail khôngtrảvềimagemớimàthựchiệntrênobjectimageđanggọi.

6.5.Cácthaotácxửlýhìnhảnh

ThamkhảothêmthưviệnPILtại:http://pillow.readthedocs.org/en/latest/index.html

Chương7.XửlýfileJSONJSONlàmộttrongnhữngđịnhdạngfiletraođổidữliệuthôngdụngnhấthiệnnay.VớikiếntrúcđơngiảnvàtươngđồngvớicấutrúccủaPythonnênviệcthaotácJSONtrênPythonrấtdễhiểu.

7.1.LoadfiletừInternet

ThôngthườngdữliệuJSONđượclấytừnguồnkhác(nhưfile,internet..)nênchươngnàysẽbắtđầubằngcáchhướngdẫndownloadmộtfileJSONtừInternetvàsauđómớiparsingnộidungJSONdownload.

Sửdụngmodule urllib2 đểdownloadfilevàmodulejson đểencode/decodeJSONdata.Vídụ:

importurllib2

importjson

response=urllib2.urlopen('https://api.github.com/

users/voduytuan/repos')

data=json.load(response)

printdata

Vídụtrênsẽtruyvấnđườngdẫnhttps://api.github.com/users/voduytuan/reposđểlấydanhsáchRepositorytrênGithubcủamìnhdướiđịnhdạngJSON.Sauđó,sẽđược

7.2.ParsingJSONData

NếunhưbạnđãcóJSONdatadướidạngchuỗi,muốnparsingchuỗinàythànhDatathìsửdụngnhưcáchdướiđây:

importjson

mystring='{"a":1,"b":2,"c":3,"d":4,"e":5}'

data=json.loads(mystring)

printdata

(Hiểnthị:{u'a':1,u'c':3,u'b':2,u'e':5,u'd

':4})

7.3.EncodingJSONData

NếunhưbạnđãcómộtbiếnvàmuốnencodethànhJSONstringthìcóthểdùngtheocáchsau:

importjson

mydata={

'name':'John',

'age':10

}

jsonstring=json.dumps(mydata)

printjsonstring

(hiểnthị:{"age":10,"name":"John"})

Chương8.XửlýfileXMLTrongphầnnày,chúngtasẽparsingnộidungXMLthànhdữliệuđểxửlý.ĐểxửlýXML,tasẽsửdụngthưviệnBeautifulsoup4.Đâylàmộtthưviệngiúpviệctriểnkhaiviệcparsinghtml,xmlđượcnhanhchóngvàtiệnlợi.

8.1.CàiđặtBeautifulsoup

Bạncóthểthamkhảohướngdẫncáchcàiđặttạiwebsitehttp://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-beautiful-soup.

TrênMacOS,cóthểcàibằng pip nhưsau:

$sudopipinstallbeautifulsoup4

8.2.Càiđặtlxml parser

Đểparsing xml từbeautifulsoup,taosửdụngbộparserxmlcótênlà lxml .Xemhướngdẫncàiđặttại

http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser

TrênMacOS,cóthểcàibằng pip nhưsau:

sudopipinstalllxml

8.3.VídụvềparsingXML

Chovídụsau:

frombs4importBeautifulSoupasSoup

note='''

<?xmlversion="1.0"encoding="UTF-8"?>

<breakfast_menu>

<food>

<name>BelgianWaffles</name>

<price>$5.95</price>

<description>TwoofourfamousBelgianWaff

leswithplentyofrealmaplesyrup</description>

<calories>650</calories>

</food>

<food>

<name>StrawberryBelgianWaffles</name>

<name>StrawberryBelgianWaffles</name>

<price>$7.95</price>

<description>LightBelgianwafflescovered

withstrawberriesandwhippedcream</description>

<calories>900</calories>

</food>

</breakfast_menu>

'''

soup=Soup(note,'xml')

foods=soup.findAll('food')

forxinfoods:

printx.find('name').string,':',x.price.stri

ng

Khichạythìsẽhiểnthịramànhìnhnhưsau:

BelgianWaffles:$5.95

StrawberryBelgianWaffles:$7.95

Đốitượngthuộcclass Soup (BeautifulSoup)sẽgiúptruyxuấtcácthànhphầncủafilexmlnhanhchóngvàtiệnlợi.

Trongvídụcómộtsốcáchtruyxuấtđếncácphầntửnhư:

findAll() :trảvềmảngcácthẻcótêncầntìm

find() :trảvềphầntửđầutiêncótêncầntìm

Truyxuấttrựctiếpthôngquatênthẻnhư

x.price.string

8.4.ParsingHTML

Tươngtựnhư xml ,BeautifulSoupcóthểparsingnộidungHTMLthôngquahàmkhởitạovàchọn html ởthamsốthứ2.

...

soup=Soup(websitehtml,'html')

Chương9.KếtnốiMySQLMySQLlàmộthệcơsởdữliệuquanhệphổbiếnnhấthiệnnay.RấtnhiềungônngữcóthểkếtnốiđếnMySQLvàPythoncũngkhôngngoạilệ.

MặcđịnhPythonkhôngcóthưviệnđểkếtnốiđếnMySQLserver.Trongphầnnày,đểkếtnốiđếnMySQLServertừPython,chúngtasẽsửdụngmodule MySQLdb

9.1.CàiđặtMySQLdb

Càiđặtthôngqua pip nhưsau:

$sudopipinstallMySQL-python

Thamkhảothêmtại:https://pypi.python.org/pypi/MySQL-python/1.2.5

KhaibáomoduleMySQLdblàcóthểsửdụng.

importMySQLdb

TrongmộtsốtrườnghợpđãcàiMySQLdbnhưngimportbáolỗithiếufile libmysqlclient.18.dylib .Nguyênnhâncóthểlàdohiệntạiđườngdẫnđếnfilekhôngtồntại.Thửtạosymlinkhoặcsửdụngcâulệnhsauđểtạosymlinktừfile libmysqlclient.18.dylib đếnthưmục /usr/lib/

$sudoln-s/usr/local/mysql/lib/libmysqlclient.18

.dylib/usr/lib/libmysqlclient.18.dylib

9.2.KếtnốiđếnMySQLServer

BạncầncómộtMySQLserverđangchạyvàchokếtnốiđến.Trongtrườnghợpnàylàlocalhostnênkhôngcầncấuhìnhđặcbiệt,chỉcầncungcấpusernamevàpasswordlàcóthểkếtnốiđếnMySQLServer.

Thựchiệngọihàmnhưsauđểtrảvềkếtnối:

importMySQLdb

dbcon=MySQLdb.connect(host='localhost',user=

'myusername',passwd='mypassword',db='mydbname

')

Nếukếtnốikhôngthànhcôngthìsẽbáolỗivàngưngchươngtrình.Cáchkếtnốiantoànlàđưavàotrong tryđểbắtlỗinhưsau:

importMySQLdb

db=None

try:

db=MySQLdb.connect(host='localhost',user=

'root',passwd='root',db='mysql')

exceptMySQLdb.Error,e:

print"Error%d:%s"%(e.args[0],e.args[1])

sys.exit(1)

ifdb:

cur=db.cursor()

cur.execute("SELECTVERSION()")

ver=cur.fetchone()

print"Databaseversion:%s"%ver

9.3.Kếtnốivớicharsetutf8

MặcđịnhkếtnốiđếnMySQLserverlàcharset latin nênkhilấydữliệuunicodethìhiểnthịTiếngViệtkhôngđúng,bạncầnphảichọncharsetlà utf8 khitạokếtnối.Cúphápnhưsau:

...

db=MySQLdb.connect(host='localhost',user='ro

ot',passwd='root',db='test',charset='utf8'

)

9.4.Querydữliệu

Đểtruyvấndữliệu(chạycâulệnhSQL)thìsửdụng cursorcủaMySQLdb.Vídụ:

importMySQLdb

db=MySQLdb.connect(host='localhost',user='ro

ot',passwd='root',db='mysql');

cursor=db.cursor()

sql='SELECT*FROMuser'

cursor.execute(sql)

myusers=cursor.fetchall()

Vídụdữliệubiến myusers là: ((1,'John'),(2,'Doe'))

Mặcđịnh, cursor sẽtrảvềmỗidòngdữliệutừMySQLtheokiểu tuple ,tứclàkhôngcókey.Nếubạnmuốntrảvề

kiểu Dictionary thìcóthểkhaibáo:

importMySQLdb

db=MySQLdb.connect(host='localhost',user='ro

ot',passwd='root',db='mysql')

cursor=db.cursor(MySQLdb.cursors.DictCursor)

...

9.5.Fetchdữliệu

Cómộtsốcáchđểfetchdữliệuthôngdụngtừ cursor saukhiđã exectute(sql) là fetchone() và fetchall() .

fetchone() :chỉfetchmộtdòngdữliệu.Nếumuốn

fetchnhiềudòngdữliệuthìcóthểgọinhiềulần,mỗi

lầnsẽtrảvềmộtdòngdữliệu.Tốtchotrườnghợptruy

vấnrấtnhiềudữliệumộtlúc.Nếutrảvề None tứclà

đãfetchhếtdữliệutừcâutruyvấn.

fetchall() :fetchtoànbộdữliệutruyvấnđượctừ

câutruyvấnvàtrảvềmộttuplechứacácdòngdữ

liệu.MỗiphầntửcủaTuplecóthểlàmộtTuplekhác

hoặclàmộtDictionarytùytheocàiđặtởbướclấy

cursor(Xemphần9.4).

fetchmany(size) :nằmởgiữa2kiểufetchtrên,cóthể

quyđịnhsốlượngrowtrongmỗilầnfetch.Nếufetch

hếtthìtrảvềTuplerỗng.

9.6.Đóngkếtnối

Saukhikếtnốivàtruyvấnthìcóthểđóngkếtnốitheovídụsau:

importMySQLdb

db=MySQLdb.connect(...)

db.close()

Ngoàira,bạncũngnênđóng cursor khikhôngcònsửdụngtheovídụ:

importMySQLdb

db=MySQLdb.connect(...)

cursor=db.cursor()

cursor.close()

db.close()

9.7.PreparedStatement

Preparedstatementlàkỹthuậtthamsốhóacácdữliệutruyềnvàocâutruyvấnthayvìnốichuỗitrựctiếpđểxâydựngmộtchuỗitruyvấndài.Kỹthuậtnàyđượcápdụngnhiềuvàgiúptănghiệuquảvàtínhbảomậtcủacâutruyvấn.Vídụ:

...

cur.execute("UPDATEWritersSETName=%sWHEREId

=%s",("John","4"))

...

Mỗithamsốtruyvấnsẽđượcthaythếbằng %s vàphươngthức execute() sẽcóthamsốthứ2làmộtTuplecógiátrị

tươngứngvớithứtựxuấthiệncủacácthànhphần %s

Chương10.KếtnốiRedisRedislàmộtmemorycacheserverhỗtrợpersistantdatathôngdụngnhấthiệnnay.NộidungchươngnàysẽhướngdẫnbạnkếtnốiđếnmộtRedisserver(đãđượccàiđặtsẵn)thôngquathưviệnredis-py.

10.1.Càiđặt

Cóthểxemthêmvềhướngdẫncàiđặtthưviệnnàytạihttps://github.com/andymccurdy/redis-py

Đơngiảncàithôngqua pip là:

$sudopipinstallredis

10.2KếtnốiđếnRedis

ĐểkếtnốiđếnRedisserverthìbạncóthểxemvídụsau:

importredis

r=redis.StrictRedis(host='localhost',port=6379,

db=0)

10.3.Thựchiệnlệnh

Thựchiệncáclệnhbìnhthườngtrênđốitượngredis.Vídụ:

importredis

r=redis.StrictRedis(...)

r.set('foo','bar')

printr.get('foo')

(Hiểnthị'bar')

10.4.Pipeline

Pipelinelàkỹthuậtđượcdùngtrongtrườnghợpbạnmuốntăngperformancebởigộpnhiềulệnhvàomộtrequestthayvìmỗilệnhlàmộtrequestnhưthôngthường.Xemvídụsauđểhiểucáchsửdụngpipelinebằng redis-py :

importredis

r=redis.StrictRedis(...)

r.set('foo','bar')

pipe=r.pipeline()

pipe.set('a',1)

pipe.set('b',2)

pipe.set('c',3)

pipe.get('foo')

pipe.execute()

Saukhigọiphươngthức execute() thìsẽtrảvềListtươngứngvớicáckếtquảcủatừnglệnh.Vídụkếtquảtừđoạncodetrên:

[True,True,True,'bar']

Chương11.KếtnốiMemcachedMemcachedlàmộtmemorycacheserverthôngdụnghiệnnay.NộidungchươngnàysẽhướngdẫnbạnkếtnốiđếnmộtMemcachedserver(đãđượccàiđặtsẵn)thôngquathưviện pylibmc .

11.1.Càiđặt

Cóthểxemthêmvềhướngdẫncàiđặtthưviệnnàytạihttp://sendapatch.se/projects/pylibmc/install.html

Đơngiảncàithôngqua pip là:

$sudopipinstallpylibmc

11.2KếtnốiđếnMemcachedServer

ĐểkếtnốiđếnMemcachedserverthìbạncóthểxemvídụsau:

importpylibmc

mc=pylibmc.Client(["127.0.0.1"],binary=True,beh

aviors={"tcp_nodelay":True,"ketama":True})

10.3.Thựchiệnlệnh

Thựchiệncáclệnhbìnhthườngtrênđốitượngmemcache.Vídụ:

importpylibmc

mc=pylibmc.Client(...)

mc.set('foo','bar')

printmc.get('foo')

(Hiểnthị'bar')

Chương12.KếtnốiRabbitMQRabbitMQlàmộtphầnmềmchophépxâydựngMessageQueuetheoprotocolAMQPvàkháthôngdụngtrênthếgiới.ĐểkếtnốiđếnRabbitMQtrênPython,tasẽsửdụngthưviện pika .

12.1.Càiđặt

Cóthểxemthêmvềhướngdẫncàiđặtthưviệnnàytạihttps://pika.readthedocs.org/en/0.10.0/

Đơngiảncàithôngqua pip là:

$sudopipinstallpika

12.2GởimộtmessageđếnServer-Provider

Vídụđểgởimộtmessageđếnserver

importpika

connection=pika.BlockingConnection(pika.Connectio

nParameters('localhost'))

channel=connection.channel()

channel.queue_declare(queue='hello')

channel.basic_publish(exchange='',routing_key='hel

lo',body='HelloWorld!')

print"[x]Sent'HelloWorld!'"

connection.close()

Đểgởimộtmessage,chúngtacầnkếtnốiđếnservervàkhaibáomộtchannel,ởđâylàchannelcótênlà hello .Saukhikhaibáochannel,taotiếnhànhgởimessagecónộidung HelloWorld! thôngquachannelnày,kèmtheokhaibáo routing_key là hello .RoutingKeysẽgiúpđiềuhướngmessagenàyđếnđúngcácworkerđượckhaibáonhậnmessagetheoroutingkey(Consumer)

12.3.Nhậnmessage-Consumer

Ởbướctrước,tađãtạomộtmessagelênqueue.Ởbướcnày,tasẽkhaibáomộtworkerxửlýcácmessagenhậnđượctừchannel hello .

importpika

connection=pika.BlockingConnection(pika.Connectio

nParameters(host='localhost'))

channel=connection.channel()

channel.queue_declare(queue='hello')

print'[*]Waitingformessages.ToexitpressCTR

L+C'

defcallback(ch,method,properties,body):

print"[x]Received%r"%(body,)

channel.basic_consume(callback,queue='hello',no_a

ck=True)

channel.start_consuming()

Đoạncodenàycũngcóphầnkhaibáo connection ,

channel .Tuynhiên,vìlàconsumernênsẽsửdụngphươngthức basic_consume đểlắngnghetrênqueuehello ,khicómessageđếnsẽgọihàm callback() đểxửlý.Trongtrườnghợpvídụnàythìcallbackchỉđơngiảnlàhiểnthịchuỗithôngbáođãnhậnđượcmessage.

12.4.TìmhiểuthêmvềRabbitMQvàPika

NộidungchươngnàykhôngcóýđịnhgiớithiệutấtcảkháiniệmcủaAMQPcũngnhưRabbitMQmàchủyếugiớithiệuthưviện pika đểlàmviệcvớiRabbitMQ.BạncóthểtiếptụctheodõicáchướngdẫnvềkháiniệmcủaRabbitMQvàPikatạiwebsitechínhthứccủaRabbitMQ.

https://www.rabbitmq.com/tutorials/tutorial-one-python.html

Chương13.RestfulclientNgàynay,vớisựphongphúcủacácứngdụngvànhucầukếtnốingàycànglớnthìRestfullàmộttrongnhữngmôhìnhwebserviceđượcnhiềucôngtysửdụng.Dođó,việccóthểkếtnốiđếncácRestfulwebservicelàmộtkỹnăngcầnthiếtchocáclậptrìnhviên.

ChươngnàysẽgiớithiệuvềmộttrongnhữngthưviệnnổitiếngnhấttrongPythonđểlàmviệcvớicácRestfulwebservice,đólà requests .

Websitechínhthứcvàcácmôtảđầyđủđềuđượcđềcậptạihttp://www.python-requests.org/

13.1.Càiđặt

Càiđặtnhanhchóngthôngqua pip nhưsau:

$sudopipinstallrequests

13.2.Request

HỗtrợsẵncácphươngthứctươngứngchoHttprequestnhưGET,POST,PUT,DELETE…

importrequests

r=requests.get('https://api.github.com/events')

r=requests.post("http://httpbin.org/post")

r=requests.put("http://httpbin.org/put")

r=requests.delete("http://httpbin.org/delete")

r=requests.head("http://httpbin.org/get")

r=requests.options("http://httpbin.org/get")

13.2.1.GETQuerystring

Đốivớicácrequest GET ,cóthểtruyềnthamsốđườngdẫnthôngquathamsố params khigọiphươngthức get() .Vídụ:

importrequests

payload={'key1':'value1','key2':'value2'}

r=requests.get("http://httpbin.org/get",params=

payload)

print(r.url)

(Hiểnthị:http://httpbin.org/get?key2=value2&key1=

value1)

13.2.2.RequestBody

TronghầuhếttrườnghợpcácrequestnhưPOST,PUTthươngcầntruyềndữliệukhirequest,cóthểsửdụngthamsố data đểtruyềndatalênkèmrequest.Vídụ:

importrequests

payload={'key1':'value1','key2':'value2'}

r=requests.post("http://httpbin.org/post",data=

payload)

13.2.3.Uploadfile

Cóthểgởithêmthamsố files đểuploadfilekèmtheorequest.Vídụ:

importrequests

url='http://httpbin.org/post'

files={'file':open('report.xls','rb')}

r=requests.post(url,files=files)

13.3.Response

Saukhigọicácphươngthứctươngứngđểrequest,bạnsẽcóđốitượngthuộcclass Response .Đốitượngnàycómộtsốthôngtinnhưsau:

status_code :HTTPStatusservertrảvề

headers :Cácthôngtinheadermàservertrảvềdưới

dạngDictionary.

cookies :Nếuservercótrảvềcookiethìcóthểsử

dụngthuộctínhnàyđểlấycáccookie.

text :Trảvềnộidungresponse

Thamkhảovềcáctínhnăngkháccủathưviện requeststạiwebsitechínhthức.http://docs.python-requests.org

Chương14.GởiemailvớiSMTPSMTPlàgiaothứcgởimailthôngdụnghiệnnay.Pythonhỗtrợmặcđịnhthưviện smtplib dùngđểkếtnốiđếnmộtSMTPServervàgởiemail.Tuynhiên,việcsửdụngthưviệnnàysẽgâykhókhănchoviệcđịnhdạngvàsửdụngnênchúngtasẽsửdụngthưviện sender ,làmộtthưviệngiúpđịnhdạngvàgởiemailđơngiảnhơn.

14.1.Càiđặtsender

Càiđặttừ pip nhưsau:

$sudopipinstallsender

14.2.Gởiemailđơngiản

Đểgởi1emailvới sender ,bạncầncótàikhoảnvàmộtsốthôngtincủaSMTPServertrướckhigởi.Vídụđoạncodeđểgởi1emailtừSMTPServercủaAmazon.

fromsenderimportMail,Message

mail=Mail(

"smtp.gmail.com",

port=465,

username="example@gmail.com",

password="yourpassword",

use_tls=False,

use_ssl=True,

debug_level=False

)

msg=Message("msgsubject")

msg.fromaddr=("VoDuyTuan","example@gmail.com")

msg.to="destuser@gmail.com"

msg.body="thisisamsgplaintextbody"

msg.html="<b>thisisamsgtextbody</b>"

msg.reply_to="example@gmail.com"

msg.charset="utf-8"

msg.extra_headers={}

msg.mail_options=[]

msg.rcpt_options=[]

#Sendmessage

mail.send(msg)

14.3.Gởiemailcóđínhkèmfile

BạncầnsửdụngthêmclassAttachmentđểtạoattachment.

fromsenderimportMail,Message,Attachment

mail=Main(...)

msg=Message(..)

...

#OpenattachedfileandcreateAttachmentobject

withopen("photo01.jpg")asf:

file01=Attachment("photo01.jpg","image/jpeg"

,f.read())

msg.attach(file01)

#Sendmessage

mail.send(msg)

14.4.Tìmhiểuthêm

Bạncóthểtìmhiểuthêmvềthưviện sender tạiwebsite

chínhthứctạiđịachỉhttp://sender.readthedocs.org/

Chương15.SocketprogrammingChươngnàysẽvídụviệcxâydựngmộtmôitrườngClient-ServersửdụngSocket.Serversẽlắngnghetrênmộtport(12345)vàkhiclientkếtnốivàosẽthôngbáohiểnthịthôngtincủaclient(IPvàPort)vàgởi1messagexuốngchoclient.

15.1.Serverside

Tạofile server.py vớinộidungbêndưới.

importsocket

s=socket.socket()

host=socket.gethostname()

port=12345

s.bind((host,port))

s.listen(5)

whileTrue:

c,addr=s.accept()

print'Gotconnectionfrom',addr

c.send('Thankyouforconnecting')

c.close()

ĐoạncodetrênkhithựcthisẽchạyvàlắngngheởportTCP12345.MỗikhicómộtkếtnốitừclientsẽhiệnrathôngbáokếtnốitừIPvàPortnào,vídụ: GotconnectionfromGotconnectionfrom('192.168.1.104',60018) .Sauđó,gởitrảmộtmessagevớinộidung Thankyouforconnecting vềchoclient.Sauđó,đóngkếtnốivớiclient.

15.2.Clientside

Tạofile client.py vớinộidungbêndưới.

importsocket

s=socket.socket()

host='127.0.0.1'

port=12345

s.connect((host,port))

prints.recv(1024)

s.close

Đoạncodetrênsẽkếtnốiđếnmộtsocketserverthôngquahostnamelấyđượctừphươngthứcsocket.gethostname() vàport12345.Saukhikếtnối,sẽhiểnthịrakếtquảtrảvềtừserver.Sauđóthìđóngkếtnối.

Recommended