Python cơ bản - Công nghệ thông tin | Trường đại học Điện Lực
Python cơ bản - Công nghệ thông tin | Trường đại học Điện Lực được sưu tầm và soạn thảo dưới dạng file PDF để gửi tới các bạn sinh viên cùng tham khảo, ôn tập đầy đủ kiến thức, chuẩn bị cho các buổi học thật tốt. Mời bạn đọc đón
xem!
Môn: Công nghệ thông tin(CNTT350)
Trường: Đại học Điện lực
Thông tin:
Tác giả:
Preview text:
+MЪM XLMЖY , MЖR RE]
4]XLSR Pɧ QШX XVSRK RLоRK RKɺR RK
чERK ч вG GLɾ ʁ FЮM XɴRL чE HϰRK ZА иRK HдR
TLSRK TLɾ Zɧ GШRK чТRK чɺRK чϲS ɇ ɪ PɧQ ZMЖG ZЪM 4,4 RʆQ Zɧ Gɹ RLоRK XɨG OLɹ Qɧ XLрG LMЖR XРM Y ч вG OLMЎR QɳRL 4]XLSR XVSRK KMEM чSϰR Rɧ]
' YРR WɨGL RLО Rɧ] ч вG ZMЎX XVSRK UYɨ XVɳRL
LМG 4]XLSR Zɧ KMϲM UY]ЎX GɨG FɧM XSɨR G FϲR GжE QɳRL
, ] ZМRK RLоRK KLM GLɰT GжE QɳRL GˢRK WЌ KM
RLоRK EM чERK UYER XɩQ чЎR ZMЖG иRK HдRK 4
GɺRK ZMЖG Zɧ \м Pʁ LMЖR XϰM 1 дG PдG 7ɨGL ч вG GLME PɧQ GL RK QЦM GL RK
OLɴE GϰRL GжE 4]XLSR Qɧ QɳRL WЌ KІT TLϲM Zɧ
OLM FMЎX GɨG OMЎR XLиG Rɧ] XVSRK ZMЖG GɺRK ZMЖG XVSRK X RK PEM ,IPPS [SVPH 'ɾ TLɨT 4LɩR GLME QSHYPI 'PEWW 8LES XɨG XVɱR XϼT XMR <м Pʁ LɳRL ϲRL <м Pʁ JMPI .732 <м Pʁ JMPI <10 /ЎX RРM 1]750 /ЎX RРM 6IHMW /ЎX RРM 1IQGEGLIH /ЎX RРM 6EFFMX15 6IWXJYP 'PMIRX +ЮM IQEMP ZЪM 7184 7SGOIX 4VSKVEQQMRK 'L RK ,IPPS [SVPH
4]XLSR Pɧ QШX RKɺR RKо TLMɱR HКGL -RXIVTVIX
XиG Pɧ OLɺRK G϶R FYMPH XLɧRL JMPI XLрG XLM Q RL 4,4 , MЖR XϰM 4]XLSR Gɹ RLɨRL GLɴRL Pɧ \ Zɧ
чɪ HкRK TLɨX XVMВR Zɧ чERK чиRK Ю TLMɱR FϲR 4]XLSR
\ XLɳ ZϺR чERK ч вG XMЎT XдG TLɨX
; IFWMXI GLɴRL XLиG GжE 4]XLSR [[[ T]XLSR SVK ' ɧM чІX
4]XLSR LЦ XVв L϶Y LЎX GɨG RАR XϲRK Zɧ VϴX H
XVɱR QШX WР LЖ чMАY LɧRL RL 1EG 37ŷ
ɇ В FMЎX Pɧ LЖ XLРRK GжE FϰR чɪ GɧM 4]XLSR G
Q ɧR LɳRL GSQQERH PMRI Zɧ Kɻ $ python --version
2 ЎY чɪ GɧM чІX T]XLSR XLɳ WЌ LMВR XLК XLɺRK T]XLSR
2ЎY FɨS PЦM XLɳ чТRK RKLʨE ZЪM FϰR G 4]XLSR
' ɹ XLВ XLEQ OLϲS GɨGL GɧM чІX 4]XLSR XϰM LXXTW [[[ T]XLSR SVK HS[RPSEHW ' ɺRK Gд TLɨX XVMВR
' LИ G϶R HɽRK QШX XI\X IHMXSV Pɧ FϰR Gɹ XLВ
T]XLSR LSІG Gɹ XLВ HɽRK GɨG GɺRK Gд GES GϴT L RL %TXERE
4]'LEVQŷ'ɨG -() XL ЬRK LЦ XVв XLɱQ
XVɳRL TLɩR XɴGL Gɾ TLɨT HɸRK PЖRL HIFYKŷXVSR
GYРR WɨGL RLО Rɧ] XLɳ QɳRL L ЪRK чЎR GɨGL XL T]XLSR FЀRK HɸRK PЖRL , IPPS [SVPH
8ϰS QШX JMPI Gɹ XɱR Pɧ helloworld.py Zɧ Gɹ RШM H WEY print 'Hello world' print Pɧ PЖRL G
FϲR RLϴX чВ \YϴX QШX FMЎR V Q ɧR LɳRL 7EY чɹ ZɧS QɧR LɳRL GSQQERH PMRI HM GLY]ВR Q дG GLиE JMPI Rɧ] Zɧ Kɻ $ python helloworld.py
2 ЎY XLϴ] \YϴX LMЖR HɸRK GLо Hello world XиG Pɧ
LSɧR XLɧRL ZMЖG ZMЎX иRK HдRK T]XLSR ч϶Y XM 'L RK 'ɾ TLɨT &MЎR WР
/ LEM FɨS FMЎR FЀRK QШX GɩY PЖRL KɨR a = 1
FϰR Gɹ XLВ KɨR RLMАY PSϰM KMɨ XVК WР GLY a = 1 a = 'Hello World' a = [1, 2, 3] a = [1.2, 'Hello', 'W', 2] 8SɨR Xм WР LМG
4]XLSR GˢRK LЦ XVв QШX WР XSɨR Xм XSɨR LМG RL + TLɰT GШRK - TLɰT XVк * TLɰT RLɩR / TLɰT GLME % TLɰT GLME Pϴ] H QSHYPS
&SSPIER Zɧ 8SɨR Xм PSKMG + Mɨ XVК чɾRK Zɧ WEM X RK иRK Pɧ True Zɧ Fals not чВ чϲS KMɨ XVК and TLɰT XɴRL PSKMG Zɧ %2( or TLɰT XɴRL PSKMG LSІG 36
1 ШX WР TLɰT WS WɨRL XLɺRK XL ЬRK RL < F L R LSІG FЀRK > PЪR L R >= PЪR L R L FЀRK != OLɨG чВ WS WɨRL KMɨ XVК
, Ц XVв HϰRK WS WɨRL OɰT RL x = 2 1 < x < 3 # True 10 < x < 20 # False 3 > x <= 2 # True 2 == x < 4 # True
8SɨR Xм OMВQ XVE TL϶R Xм XVSRK QШX XϼT LвT Gɹ XТR XϰM not in OMВQ OLɺRK XТR XϰM
'good' in 'this is a greate example' # F alse
'good' not in 'this is a greate example' # True 'ϴY XVɾG чMАY OLMВR
4]XLSR LЦ XVв QШX WР GϴY XVɾG чMАY OLMВR
LЎX GɨG GϴY XVɾG чMАY OLMВR чАY HрE ZɧS XL MRHIRXMSR
чВ XϰS XLɧRL QШX FPSGO \м Pʁ X { ŷ } RL GɨG RKɺR RKо OLɨG 4,4 .EZEWGVMTX -JŷIPMJŷIPWI if condition1 :
indentedStatementBlockForTrueCondition1 elif condition2 :
indentedStatementBlockForFirstTrueCondition2 elif condition3 :
indentedStatementBlockForFirstTrueCondition3 elif condition4 :
indentedStatementBlockForFirstTrueCondition4 else:
indentedStatementBlockForEachConditionFalse 7[MXGLŷGEWI
4]XLSR OLɺRK Gɹ GϴY XVɾG switchŷ case *SVŷMR for iterating_var in sequence: statements(s) : ɴ Hд
for letter in 'Python': # First Example
print 'Current Letter :', letter
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
print 'Current fruit :', fruit print "Good bye!"
/ ЎX UYϲ LMВR XLК GжE Zɴ Hд XVɱR Current Letter : P Current Letter : y Current Letter : t Current Letter : h Current Letter : o Current Letter : n Current fruit : banana Current fruit : apple Current fruit : mango Good bye! ;LMPI while expression: statement(s) : ɴ Hд count = 0 while (count < 9): print 'The count is:', count count = count + 1 print "Good bye!"
/ ЎX UYϲ LMВR XLК GжE Zɴ Hд XVɱR The count is: 0 The count is: 1 The count is: 2 The count is: 3 The count is: 4 The count is: 5 The count is: 6 The count is: 7 The count is: 8 Good bye! ,ɧQ / LEM FɨS LɧQ XLIS Gɾ TLɨT
def functionname(param, param2,..): statements(s)
, ɧQ RЎY OLɺRK XVϲ Hо PMЖY XLɳ QІG чКRL WЌ None
: ɴ Hд OLEM FɨS LɧQ XɴRL Zɧ XVϲ ZА KMɨ XVК X WР ч϶Y ZɧS r+ QЮ чВ чМG Zɧ KLM 'SR XVО RЀQ Ю ч϶Y w+ QЮ чВ чМG Zɧ KLM +LM чɯ RЎY JMPI
JMPI GL E XТR XϰM XLɳ XϰS JMPI QЪM чВ KL a+
QЮ чВ чМG Zɧ XLɱQ ZɧS GYРM JMPI 'SR GYРM JMPI
2ЎY JMPI GL E XТR XϰM XLɳ XϰS 1 ІG чКRL Pɧ QЮ JMPI XI\X RЎY QYРR QЮ JMPI FMREV] XLɳ XLɱQ b Zɴ Hд rb wb ab rb+ : ɴ Hд f1 = open('test.txt', 'r') f2 = open('access_log', 'a+'
7EY OLM KМM LɧQ open() XLɧRL GɺRK XLɳ WЌ XVϲ SFNIGX Gɹ GɨG XLYШG XɴRL closed 8VYI RЎY JMPI чɪ чɹRK mode GLЎ чШ OLM QЮ JMPI name XɱR GжE JMPI softspace
GЬ чɨRL HϴY WSJXWTEGI OLM HɽRK ZЪ print ɇМG RШM HYRK Xк JMPI
7EY OLM JMPI чɪ QЮ Ю GLЎ чШ чМG XLɳ KМM
read([count]) чВ XVϲ ZА XSɧR FШ RШM HYRK GжE JM f1 = open('test.txt', 'r') data = f1.read();
, ɧQ read() Gɹ RLϼR QШX XLEQ WР Pɧ WР P вRK F] чМG
2ЎY OLɺRK XVY]АR ZɧS XLɳ WЌ чМG LЎX R : ɴ Hд f2 = open('log.txt', 'r') buffdata = f2.read(1024) +LM RШM HYRK ZɧS JMPI
2 ЎY JMPI ч вG QЮ Ю GLЎ чШ Gɹ XLВ KLM XLɳ TL
RK XLиG write() чВ KLM QШX RШM HYRK ZɧS f2 = open('access_log', 'a+') f2.write('Attack detected') ɇɹRK JMPI чɪ QЮ
7EY OLM LSɧR XϴX GɨG XLES XɨG чМG KLM JMPI
XLиG close() чВ чɹRK JMPI чɪ QЮ :ɴ Hд f1.close() f2.close() ɇФM XɱR JMPI 7м HдRK TL
RK XLиG os.rename(old, new) чВ чФM XɱR Q ШX JMPI :ɴ Hд import os
os.rename('test.txt', 'test_new.txt') <ɹE JMPI 7м HдRK TL
RK XLиG os.remove(file) чВ \ɹE QШX JMP OLОM LЖ XLРRK :ɴ Hд import os os.remove('test.txt') 8L QдG (MVIGXSV] 8ϰS XL QдG 7м HдRK TL
RK XLиG os.mkdir(dir) чВ XϰS XL QдG Hд import os os.mkdir('test') <ɹE XL QдG 7м HдRK TL
RK XLиG os.rmdir(dir) чВ \ɹE QШX XL : ɴ Hд import os os.rmdir('test') ɇМG RШM HYRK XL QдG 7м HдRK TL
RK XLиG os.listdir(dir) чВ Pϴ] HERL WɨG XϼT XMR XL QдG GжE XL QдG dir /LM KМM
Q ϲRK HERL WɨGL GɨG XϼT XMR XL QдG :ɴ Hд import os
allfiles = os.listdir('/root/downloads') print allfiles 1SHYPI os
1 SHYPI os Pɧ QШX QSHYPI Gɹ RLMАY TL RK XLи
XVSRK ZMЖG PɧQ ZMЖG ZЪM GɨG JMPI Zɧ HMVIGX os.chdir(path) чФM XL QдG LMЖR LɧRL os.getcwd() XVϲ ZА XL QдG LMЖR LɧRL os.chmod(path, mode) ',13( QШX ч ЬRK HϺR os.chown(path, uid, gid) ',3;2 QШX ч ЬRK HϺR os.makedirs(path[, mode]) XϰS ч ЬRK HϺR Gɹ VIGYVWMZI os.removedirs(path) \ɹE QШX ч ЬRK HϺR Gɹ VIGYVWMZI HSGW T]XLSR SVK PM 1SHYPI os.path
1 SHYPI os.path LЦ XVв GɨG TL RK XLиG KMɾT XLE
RLERL GLɹRK Zɧ XLYϼR XMЖR L R XVɱR ч ЬRK H os.path.exists(path) OMВQ XVE ч ЬRK HϺR Gɹ XТ XϰM LE] OLɺRK os.path.getsize(path) Pϴ] JMPI WM^I F]XI os.path.isfile(path)
OMВQ XVE \IQ Gɹ TLϲM Pɧ QШX JMPI XLɺRK XL ЬRK os.path.isdir(path)
OMВQ XVE \IQ Gɹ TLϲM Pɧ QШX XL QдG os.path.dirname(path) XVϲ ZА XɱR XL QдG GжE TE os.path.getatime(path) XVϲ ZА XLЬM KMER XVY] GϼT QЪM RLϴX os.path.getmtime(path) XVϲ ZА XLЬM KMER GLИRL W GYРM GɽRK os.path.getctime(path) XVϲ ZА XLЬM KMER GLИRL W
GYРM GжE QIXEHEXE XVɱR QШX WР LЖ XLРR
XLЬM KMER XϰS JMPI XVɱR ;MRHS[W LXXTW HSGW T]XLSR SVK PMFVEV] SW TEXL 'L RK <м Pʁ LɳRL ϲ 7м HдRK XL ZMЖR 4MPPS[ 4-0 *SVO чВ XMЎR
XɨG \м Pʁ LɳRL ϲRL ч R KMϲR RL VIWM^I GVST 'ɧM чІX 4-0
: ɧS XVERK [IF WEY чВ HS[RPSEH GɧM чІX TEGO T]XLSR GжE FϰR LXXT
TMPPS[ VIEHXLIHSGW SVK IR PEXIWX MRW
7EY OLM GɧM чІX XLɳ Gɹ XLВ Wм HдRK GɨG QSH TEGOEKI -40 from PIL import Image 1Ю JMPI from PIL import Image im = Image.open("photo.jpg")
7EY OLM QЮ JMPI LɳRL XLɧRL GɺRK XLɳ Gɹ XLВ X вRK im +LM JMPI
8к чРM X вRK Image Gɹ XLВ P Y JMPI \YРRK Qɨ] X TL RK XLиG save(path, type) :ɴ Hд ...
im.save('photo_new.jpg', 'JPEG') 8ϰS XLYQFREMP 7м HдRK TL RK XLиG thumbnail RL WEY from PIL import Image im = Image.open('photo.jpg') im.thumbnail((100, 100))
im.save('photo_thumbnail.jpg', 'JPEG')
thumbnail OLɺRK XVϲ ZА MQEKI QЪM Qɧ XLрG LMЖR SFNIGX MQEKI чERK KМM
'ɨG XLES XɨG \м Pʁ LɳRL ϲ 8LEQ OLϲS XLɱQ XL ZMЖR 4-0 XϰM LXXT
TMPPS[ VIEHXLIHSGW SVK IR PEXIWX MRH 'L RK <м Pʁ JMPI .7
. 732 Pɧ QШX XVSRK RLоRK чКRL HϰRK JMPI XVES XLɺRK HдRK RLϴX LMЖR RE] :ЪM OMЎR XVɾG ч
чТRK ZЪM GϴY XVɾG GжE 4]XLSR RɱR ZMЖG XLE 4]XLSR VϴX HД LMВY 0SEH JMPI Xк -RXIVRIX
8LɺRK XL ЬRK Hо PMЖY .732 ч вG Pϴ] Xк RKYТR JMPI MRXIVRIX RɱR GL RK Rɧ] WЌ FϾX ч϶Y
L ЪRK HϺR HS[RPSEH QШX JMPI .732 Xк -RXIVRIX
Q ЪM TEVWMRK RШM HYRK .732 HS[RPSEH
7м HдRK QSHYPI urllib2 чВ HS[RPSEH JMPI Zɧ QSHYP
json чВ IRGSHI HIGSHI .732 HEXE :ɴ Hд import urllib2 import json
response = urllib2.urlopen('https://api.github.com/ users/voduytuan/repos') data = json.load(response) print data
: ɴ Hд XVɱR WЌ XVY] ZϴR ч ЬRK HϺR LXXTW ETM KMXLYF GSQ YWIVW ZSHY]XYER L VIT
WɨGL 6ITSWMXSV] XVɱR +MXLYF GжE QɳRL H ЪM ч . 732 7EY чɹ WЌ ч вG 4EVWMRK .732 (EXE 2 ЎY RL
FϰR чɪ Gɹ .732 HEXE H ЪM HϰRK GLYЦM
TEVWMRK GLYЦM Rɧ] XLɧRL (EXE XLɳ Wм HдRK R чɩ] import json
mystring = '{"a":1,"b":2,"c":3,"d":4,"e":5}' data = json.loads(mystring) print data
(HiӅn thӍ: {u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd ': 4}) )RGSHMRK .732 (EXE 2 ЎY RL
FϰR чɪ Gɹ QШX FMЎR Zɧ QYРR IRGSHI X
WXVMRK XLɳ Gɹ XLВ HɽRK XLIS GɨGL WEY import json mydata = { 'name': 'John', 'age': 10 }
jsonstring = json.dumps(mydata) print jsonstring
(hiӅn thӍ: {"age": 10, "name": "John"}) 'L RK <м Pʁ JMPI < 8VSRK TL϶R Rɧ] GLɾRK XE WЌ TEVWMRK RШM H Hо PMЖY чВ \м Pʁ ɇВ \м Pʁ <10 XE WЌ Wм Hд &IEYXMJYPWSYT ɇɩ] Pɧ QШX XL ZMЖR KMɾT ZMЖG TEVWMRK LXQP \QP ч вG RLERL GLɹRK Zɧ 'ɧM чІX &IEYXMJYPWSYT
&ϰR Gɹ XLВ XLEQ OLϲS L ЪRK HϺR GɨGL GɧM чІX LXXT
[[[ GVYQQ] GSQ WSJX[EVI &IEYXMJYP7SYT G FIEYXMJYP WSYT 8VɱR 1EG37 Gɹ XLВ GɧM FЀRK pip RL WEY
$ sudo pip install beautifulsoup4 'ɧM чІX lxml TEVWIV
ɇ В TEVWMRK xml Xк FIEYXMJYPWSYT XES Wм HдR \ QP Gɹ XɱR Pɧ lxml LXXT
[[[ GVYQQ] GSQ WSJX[EVI &IEYXMJYP7S E TEVWIV 8VɱR 1EG37 Gɹ XLВ GɧM FЀRK pip RL WEY sudo pip install lxml :ɴ Hд ZА TEVWMRK <10 ' LS Zɴ Hд WEY
from bs4 import BeautifulSoup as Soup note = ' '
<?xml version="1.0" encoding="UTF-8"?> Belgian Waffles $5.95
Two of our famous Belgian Waff
les with plenty of real maple syrup 650 Strawberry Belgian Waffles $7.95
Light Belgian waffles covered
with strawberries and whipped cream 900 ' ' soup = Soup(note, 'xml') foods = soup.findAll('food') for x in foods:
print x.find('name').string, ': ', x.price.stri ng
/ LM GLϰ] XLɳ WЌ LMВR XLК VE QɧR LɳRL RL W Belgian Waffles : $5.95
Strawberry Belgian Waffles : $7.95
ɇ РM X вRK XLYШG GPEWW Soup &IEYXMJYP7SYT
\ YϴX GɨG XLɧRL TL϶R GжE JMPI \QP RLERL GLɹRK
8VSRK Zɴ Hд Gɹ QШX WР GɨGL XVY] \YϴX чЎR findAll()
XVϲ ZА QϲRK GɨG XLЊ Gɹ XɱR G϶R X find()
XVϲ ZА TL϶R Xм ч϶Y XMɱR Gɹ XɱR G϶R
8VY] \YϴX XVрG XMЎT XLɺRK UYE XɱR XLЊ R x.price.string 4EVWMRK ,810 8 RK Xр RL xml
&IEYXMJYP7SYT Gɹ XLВ TEVW
, 810 XLɺRK UYE LɧQ OLЮM XϰS Zɧ GLМR html Ю XLи ...
soup = Soup(websitehtml, 'html') 'L RK /ЎX RРM 1]750 1 ]750 Pɧ QШX LЖ G WЮ Hо PMЖY UYER LЖ TL RE]
6ϴX RLMАY RKɺR RKо Gɹ XLВ OЎX RРM чЎR 4]XLSR GˢRK OLɺRK RKSϰM PЖ
1 ІG чКRL 4]XLSR OLɺRK Gɹ XL ZMЖR чВ OЎX RР WIVZIV 8VSRK TL϶R Rɧ] чВ OЎX RРM чЎR 1]750 4]XLSR
GLɾRK XE WЌ Wм HдRK QSHYPI MySQLdb 'ɧM чІX 1]750HF ' ɧM чІX XLɺRK UYE pip RL WEY
$ sudo pip install MySQL-python 8LEQ OLϲS XLɱQ XϰM LXXTW T]TM T]XLSR SV T]XLSR
/ LEM FɨS QSHYPI 1]750HF Pɧ Gɹ XLВ Wм HдRK import MySQLdb
8VSRK QШX WР XV ЬRK LвT чɪ GɧM 1]750HF RL R
FɨS PЦM XLMЎY JMPI libmysqlclient.18.dylib 2KY]ɱR RLɩR
Gɹ XLВ Pɧ HS LMЖR XϰM ч ЬRK HϺR чЎR JMPI O
XϰS W]QPMRO LSІG Wм HдRK GɩY PЖRL WEY чВ Xϰ
JMPI libmysqlclient.18.dylib чЎR XL QдG /usr/lib/
$ sudo ln -s /usr/local/mysql/lib/libmysqlclient.18
.dylib /usr/lib/libmysqlclient.18.dylib /ЎX RРM чЎR 1]750 7IVZIV
&ϰR G϶R Gɹ QШX 1]750 WIVZIV чERK GLϰ] Zɧ GLS чЎR
8VSRK XV ЬRK LвT Rɧ] Pɧ PSGEPLSWX RɱR LɳRL чІG FMЖX
GLИ G϶R GYRK GϴT YWIVREQI Zɧ
Gɹ XLВ OЎX RРM чЎR 1]750 7IVZIV 8LрG LMЖR KМM LɧQ RL WEY чВ XVϲ ZА OЎX import MySQLdb
dbcon = MySQLdb.connect(host = 'localhost', user =
'myusername', passwd = 'mypassword', db = 'mydbname ')
2 ЎY OЎX RРM OLɺRK XLɧRL GɺRK XLɳ WЌ FɨS PЦM GL RK XVɳRL
'ɨGL OЎX RРM ER XSɧR Pɧ ч E Z чВ FϾX PЦM RL WEY import MySQLdb db = None try:
db = MySQLdb.connect(host = 'localhost', user =
'root', passwd = 'root', db = 'mysql') except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0],e.args[1]) sys.exit(1) if db: cur = db.cursor()
cur.execute("SELECT VERSION()") ver = cur.fetchone()
print "Database version : %s " % ver /ЎX RРM ZЪM charset utf8
1 ІG чКRL OЎX RРM чЎR 1]750 WIVZIV Pɧ GLEVWIX
OLM Pϴ] Hо PMЖY YRMGSHI XLɳ LMВR XLК 8MЎRK
FϰR G϶R TLϲM GLМR GLEVWIX Pɧ utf8 OLM XϰS OЎ RL WEY 'L RK /ЎX RРM 1 IQGEGLIH
1 IQGEGLIH Pɧ QШX QIQSV] GEGLI WIVZIV XLɺRK H RE] 2ШM HYRK GL RK Rɧ] WЌ L ЪRK HϺR FϰR Q ШX 1IQGEGLIH WIVZIV чɪ ч вG GɧM чІX WЄR XL ZMЖR pylibmc 'ɧM чІX
' ɹ XLВ \IQ XLɱQ ZА L ЪRK HϺR GɧM чІX XL Z LXXT
WIRHETEXGL WI TVSNIGXW T]PMFQG MRWX
ɇ R KMϲR GɧM XLɺRK UYE pip Pɧ $ sudo pip install pylibmc
/ЎX RРM чЎR 1IQGEGLIH 7IVZI
ɇ В OЎX RРM чЎR 1IQGEGLIH WIVZIV XLɳ FϰRд Gɹ X WEY import pylibmc
mc = pylibmc.Client(["127.0.0.1"], binary=True, beh
aviors={"tcp_nodelay": True, "ketama": True}) 8LрG LMЖR PЖRL
8LрG LMЖR GɨG PЖRL FɳRL XL ЬRK XVɱR чРM X : ɴ Hд import pylibmc mc = pylibmc.Client(...) mc.set('foo', 'bar') print mc.get('foo') (HiӅn thӍ 'bar') 'L RK /ЎX RРM 6EF
6EFFMX15 Pɧ QШX TL϶R QАQ GLS TLɰT \ɩ] HрRK 1
5 YIYI XLIS TVSXSGSP %154 Zɧ OLɨ XLɺRK HдRK XV KMЪM
ɇВ OЎX RРM чЎR 6EFFMX15 XVɱR 4]XLSR XL ZMЖR pika 'ɧM чІX
' ɹ XLВ \IQ XLɱQ ZА L ЪRK HϺR GɧM чІX XL Z LXXTW TMOE VIEHXLIHSGW SVK IR
ɇ R KMϲR GɧM XLɺRK UYE pip Pɧ $ sudo pip install pika +ЮM QШX QIWWEKI чЎR 7IVZ 4 VSZMHIV
: ɴ Hд чВ KЮM QШX QIWWEKI чЎR WIVZIV import pika
connection = pika.BlockingConnection(pika.Connectio nParameters('localhost')) channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange=' , routing_key='hel lo', body='Hello World!')
print " [x] Sent 'Hello World!'" connection.close() ɇ В KЮM QШX QIWWEKI GLɾRK XE G϶R OЎX RРM OLEM FɨS QШX GLERRIP Ю чɩ] Pɧ GLERRIP Gɹ Xɱ 7EY OLM OLEM FɨS GLERRIP XES XMЎR LɧRL KЮ
RШM HYRK Hello World! XLɺRK UYE GLERRIP Rɧ] OɯQ
OLEM FɨS routing_key Pɧ hello 6SYXMRK /I] WЌ KMɾT
L ЪRK QIWWEKI Rɧ] чЎR чɾRK GɨG [SVOIV ч вG OL RLϼR QIWWEKI XLIS VSYXMRK OI] 'SRWYQIV 2LϼR QIWWEKI 'SRWYQIV Э F ЪG XV ЪG
XE чɪ XϰS QШX QIWWEKI PɱR U Rɧ]
XE WЌ OLEM FɨS QШX [SVOIV \м Pʁ GɨG QIW ч вG Xк GLERRIP hello import pika
connection = pika.BlockingConnection(pika.Connectio nParameters(host='localhost')) channel = connection.channel()
channel.queue_declare(queue='hello')
print ' [*] Waiting for messages. To exit press CTR L+C'
def callback(ch, method, properties, body):
print " [x] Received %r" % (body,)
channel.basic_consume(callback, queue='hello', no_a ck=True) channel.start_consuming()
ɇ SϰR GSHI Rɧ] GˢRK Gɹ TL϶R OLEM FɨS connection channel 8Y] RLMɱR Zɳ Pɧ GSRWYQIV RɱR W TL
RK XLиG basic_consume чВ PϾRK RKLI XVɱR UYIY hello
OLM Gɹ QIWWEKI чЎR WЌ KМM LɧQ callback() Pʁ
8VSRK XV ЬRK LвT Zɴ Hд Rɧ] XLɳ GEPPFEGO G
LMВR XLК GLYЦM XLɺRK FɨS чɪ RLϼR ч вG QIWWEK 8ɳQ LMВY XLɱQ ZА 6EFFMX 2 ШM HYRK GL
RK Rɧ] OLɺRK Gɹ ʁ чКRL KMЪM X RMЖQ GжE %154 GˢRK RL 6EFFMX15 Qɧ GLж ]ЎY XL
ZMЖR pika чВ PɧQ ZMЖG ZЪM 6EFFMX15 &ϰR
XдG XLIS HɻM GɨG L ЪRK HϺR ZА OLɨM RMЖQ Gж
4MOE XϰM [IFWMXI GLɴRL XLиG GжE 6EFFMX15 LXXTW
[[[ VEFFMXQU GSQ XYXSVMEPW XYXSVME T]XLSR LXQP 'L RK 6IWXJYP GPM 2 Kɧ] RE]
ZЪM Wр TLSRK TLɾ GжE GɨG иRK HдRK
OЎX RРM RKɧ] GɧRK PЪR XLɳ 6IWXJYP Pɧ QШX XV
LɳRL [IF WIVZMGI ч вG RLMАY GɺRK X] Wм HдRK
Gɹ XLВ OЎX RРM чЎR GɨG 6IWXJYP [IF WIVZMGI Pɧ
G϶R XLMЎX GLS GɨG PϼT XVɳRL ZMɱR ' L
RK Rɧ] WЌ KMЪM XLMЖY ZА QШX XVSRK R
XMЎRK RLϴX XVSRK 4]XLSR чВ PɧQ ZMЖG ZЪM Gɨ WIVZMGI чɹ Pɧ requests
; IFWMXI GLɴRL XLиG Zɧ GɨG Qɺ Xϲ ч϶] чж чАY ч XϰM LXXT [[[ T]XLSR VIUYIWXW SVK 'ɧM чІX
' ɧM чІX RLERL GLɹRK XLɺRK UYE pip RL WEY $ sudo pip install requests 6IUYIWX , Ц XVв WЄR GɨG TL RK XLиG X RK иRK GLS RL +)8 4378 498 ()0)8)ŷ import requests
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") +)8 5YIV] WXVMRK ɇ РM ZЪM GɨG VIUYIWX GET Gɹ XLВ XVY]АR XLEQ
XLɺRK UYE XLEQ WР params OLM KМM TL RK XLиG Hд import requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get("http://httpbin.org/get", params = payload) print(r.url)
(HiӅn thӍ: http://httpbin.org/get?key2=value2&key1= value1) 6IUYIWX &SH]
8VSRK L϶Y LЎX XV ЬRK LвT GɨG VIUYIWX RL 43 XL
RK G϶R XVY]АR Hо PMЖY OLM VIUYIWXQ Gɹ
WР data чВ XVY]АR HEXE PɱR OɯQ VIUYIWX :ɴ H import requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data = payload) 9TPSEH JMPI
' ɹ XLВ KЮM XLɱQ XLEQ WР files чВ YTPSEH JMPI VIUYIWX :ɴ Hд import requests
url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files) 6IWTSRWI 7EY OLM KМM GɨG TL RK XLиG X RK иRK чВ
Gɹ чРM X вRK XLYШG GPEWW Response ɇРM X вRK WР XLɺRK XMR RL WEY status_code ,884 7XEXYW WIVZIV XVϲ ZА headers
'ɨG XLɺRK XMR LIEHIV Qɧ WIVZIV XVϲ HϰRK (MGXMSREV] cookies
2ЎY WIVZIV Gɹ XVϲ ZА GSSOMI XLɳ Gɹ
HдRK XLYШG XɴRL Rɧ] чВ Pϴ] GɨG GSSOMI text 8Vϲ ZА RШM HYRK VIWTSRWI
8LEQ OLϲS ZА GɨG XɴRL RʆRK OLɨG GжE XL ZMЖ XϰM [IFWMXI GLɴRL XLиG LXXT HSGW T]XLSR 'L RK +ЮM IQEMP
7184 Pɧ KMES XLиG KЮM QEMP XLɺRK HдRK LMЖ Ц R XVв QІG чКRL XL
ZMЖR smtplib HɽRK чВ OЎX RРM 7184 7IVZIV Zɧ KЮM IQEMP 8Y] RLMɱR ZMЖG
ZMЖR Rɧ] WЌ Kɩ] OLɹ OLʆR GLS ZMЖG чКRL HϰRK
RɱR GLɾRK XE WЌ Wм HдRK XL ZMЖR sender Pɧ
KMɾT чКRL HϰRK Zɧ KЮM IQEMP ч R KMϲR L R 'ɧM чІX sender ' ɧM чІX Xк pip RL WEY $ sudo pip install sender +ЮM IQEMP ч R KMϲR ɇ В KЮM IQEMP ZЪM sender FϰR G϶R Gɹ XɧM OL
XLɺRK XMR GжE 7184 7IVZIV XV ЪG OLM KЮM :ɴ чВ KЮM
IQEMP Xк 7184 7IVZIV GжE %QE^SR
from sender import Mail, 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("msg subject")
msg.fromaddr = ("Vo Duy Tuan", "example@gmail.com") msg.to = "destuser@gmail.com"
msg.body = "this is a msg plain text body"
msg.html = "this is a msg text body"
msg.reply_to = "example@gmail.com" msg.charset = "utf-8" msg.extra_headers = {} msg.mail_options = [] msg.rcpt_options = [] # Send message mail.send(msg) +ЮM IQEMP Gɹ чɴRL OɯQ
&ϰR G϶R Wм HдRK XLɱQ GPEWW %XXEGLQIRX чВ EXXEGLQIRX
from sender import Mail, Message, Attachment mail = Main(...) msg = Message(..) ...
# Open attached file and create Attachment object with open("photo01.jpg") as f:
file01 = Attachment("photo01.jpg", "image/jpeg" , f.read()) msg.attach(file01) # Send message mail.send(msg) 8ɳQ LMВY XLɱQ
&ϰR Gɹ XLВ XɳQ LMВY XLɱQ ZА XL ZMЖR sender
GLɴRL XLиG XϰM чКE GLИ LXXT WIRHIV VI 'L RK 7SGOIX TVSKVEQQMRK ' L
RK Rɧ] WЌ Zɴ Hд ZMЖG \ɩ] HрRK QШX QɺM X 7IVZIV Wм HдRK 7SGOIX 7IVZIV WЌ PϾRK RKLI X
Zɧ OLM GPMIRX OЎX RРM ZɧS WЌ XLɺR XLɺRK XMR GжE GPMIRX -4 Zɧ 4SVX Zɧ KЮM GLS GPMIRX 7IVZIV WMHI
8ϰS JMPI server.py ZЪM RШM HYRK FɱR H ЪM import socket s = socket.socket() host = socket.gethostname() port = 12345 s.bind((host, port)) s.listen(5) while True: c, addr = s.accept()
print 'Got connection from', addr
c.send('Thank you for connecting') c.close()
ɇ SϰR GSHI XVɱR OLM XLрG XLM WЌ GLϰ] Zɧ PϾR 8'4
1ЦM OLM Gɹ QШX OЎX RРM Xк GPM
XLɺRK FɨS OЎX RРM Xк -4 Zɧ 4SVX RɧS Zɴ Hд G
f rom Got connection from ('192.168.1.104', 60018) 7EY чɹ
KЮM XVϲ QШX QIWWEKI ZЪM RШM HYRK c onnecting ZА GLS GPMIRX 7EY чɹ чɹRK OЎX RРM 'PMIRX WMHI
8ϰS JMPI client.py ZЪM RШM HYRK FɱR H ЪM import socket s = socket.socket() host = '127.0.0.1' port = 12345 s.connect((host, port)) print s.recv(1024) s.close
ɇ SϰR GSHI XVɱR WЌ OЎX RРM чЎR QШX WSGOIX
UYE LSWXREQI Pϴ] ч вG Xк TL RK XLиG socket.gethostname() Zɧ TSVX 7EY OLM OЎX RР
LMВR XLК VE OЎX UYϲ XVϲ ZА Xк WIVZIV 7EY 8ɨG KMϲ 8ɱR :ɻ (Y] 8YϴR )QEMP XYERQEWXIV $KQEMP GSQ *EGIFSSO LXXTW [[[ JEGIFSSO GSQ ZSHY]XYE