Professional Documents
Culture Documents
thiu
Hin nay, Python l mt trong nhng ngn ng lp trnh
ang c ch bi tnh a dng v ng dng, th vin
phong ph v cng ng ng o.
Mc lc
Sch c chia lm 15 chng, mi chng s trnh by 1
kha cnh ca Python m mnh s gp phi v s hu ch
khi bit cc kin thc ny trong vic p dng Python vo
cng vic trong tng lai.
1. Hello world
2. C php
3. Phn chia module
4. Class
5. Thao tc trn tp tin
6. X l hnh nh
7. X l file JSON
8. X l file XML
9. Kt ni MySQL
10. Kt ni Redis
11. Kt ni Memcached
12. Kt ni RabbitMQ
13. Restful Client
14. Gi email vi SMTP
15. Socket Programming
Tc gi
Tn: V Duy Tun
Email: tuanmaster2012@gmail.com
Facebook: https://www.facebook.com/voduytuan
Chng 1. Hello world
Python l mt ngn ng phin dch (Interpreter Language),
tc l khng cn build thnh file thc thi m chy trc tip
nh PHP.
Ci t
Python h tr hu ht cc nn tng v rt d tm thy sn
trn mt s h iu hnh nh Mac OS
$ python --version
Nu ci t python th s hin th thng tin phin bn
python. Nu bo li th ng ngha vi bn cha ci t
Python.
Hello world
To mt file c tn l helloworld.py v c ni dung nh
sau:
$ python helloworld.py
a = 1
a = 1
a = 'Hello World'
a = [1, 2, 3]
a = [1.2, 'Hello', 'W', 2]
2.2. Ton t s hc
Python cng h tr mt s ton t ton hc thng dng
nh:
+ php cng
- php tr
* php nhn
/ php chia
not o gi tr.
2.4.2. Switchcase
2.4.3. Forin
V d:
for letter in 'Python': # First Example
print 'Current Letter :', letter
Kt qu hin th ca v d trn:
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!
2.4.4. While
while expression:
statement(s)
V d:
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"
Kt qu hin th ca v d trn:
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!
2.5. Hm
Khai bo hm theo c php:
Hm nu khng tr d liu th mc nh s tr v gi tr
None
Cch gi hm:
sum(1, 2)
(tr v gi tr l 3)
Nu gi hm trn nh sau:
plus(2)
(kt qu tr v l 12)
sum(b = 1, a = 10)
2.6. X l chui
Mt chui c th khai bo bng du nhy i " hoc n
' . V d cc chui sau:
str1 = "Hello"
str2 = 'world'
2.6.1. Ni chui
2.6.3. Ly di ca chui
2.6.8. Mt s hm x l chui
2.7. List
List trong Python l cu trc mng v cc phn t c index
c th t. Khng nh PHP, key ca mt mng c th va
l s, va l chui (associated array).
print numbers[0]
(Hin th 1)
print numbers[-3]
(Hin th 3)
print names[1]
(Hin th 'Peter')
numbers = [1, 2, 3, 4, 5]
del numbers[0]
print numbers
(Hin th [2, 3, 4, 5])
2.7.4. Ni 2 mng
a = [1, 2]
b = [1, 3]
print a + b
(Hin th [1, 2, 1, 3])
numbers = [1, 2, 3]
mynumber = numbers.pop()
print mynumber
(Hin th 3)
print numbers
(Hin th [1, 2])
2.7.9. Sp xp gi tr cc phn t
2.9. Dictionary
Dictionary cng l mt cu trc mng, nhng cc phn t
bao gm key v value. Nu bn c bit JSON th cu trc
Dictionary tng t nh mt object json. Mt Dictionary
c khai bo bng cp du ngoc {...} . V d:
point = {'x': 1, 'y': 2}
import modulename
import mymath
num1 = 1
num2 = 2
print 'Tong hai so la: ', mymath.cong(num1, num2)
|-- mypack
| |-- __init__.py
| |-- mymodule1.py
| |-- mymodule2.py
|
hoc
hoc
import mypack.mysubpack.mysubsubpack.module
Chng 4. Class
Lp trnh hng i tng l mt khi nim khng th
thiu trong hu ht cc ngn ng thng dng hin nay.
Python cng h tr lp trnh hng i tng vi cc khi
nim Class, Object, Override
class myclass([parentclass]):
assignments
def __init__(self):
statements
def method():
statements
def method2():
statements
V d mt class:
class animal():
name = ''
name = ''
age = 0
def __init__(self, name = '', age = 0):
self.name = name
self.age = age
def show(self):
print 'My name is ', self.name
def run(self):
print 'Animal is running...'
def go(self):
print 'Animal is going...'
class dog(animal):
def run(self):
print 'Dog is running...'
myanimal = animal()
myanimal.show()
myanimal.run()
myanimal.go()
mydog = dog('Lucy')
mydog.show()
mydog.run()
mydog.go()
Sau khi thc thi s cho ra kt qu:
My Name is
Animal is running...
Animal is going...
My Name is Lucy
Dog is running...
Animal is going...
fh = open(filepath, mode)
w : m ghi ni dung
V d:
f1 = open('test.txt', 'r')
f2 = open('access_log', 'a+'
name : tn ca file
f1 = open('test.txt', 'r')
data = f1.read();
f2 = open('log.txt', 'r')
buffdata = f2.read(1024)
5.1.4. ng file m
f1.close()
f2.close()
5.1.5. i tn file
import os
os.rename('test.txt', 'test_new.txt')
5.1.6. Xa file
import os
os.remove('test.txt')
5.2. Th mc (Directory)
5.2.1. To th mc
import os
os.mkdir('test')
5.2.2. Xa th mc
import os
os.rmdir('test')
5.2.3. c ni dung th mc
import os
allfiles = os.listdir('/root/downloads')
print allfiles
5.3. Module os
Module os l mt module c nhiu phng thc hu ch
trong vic lm vic vi cc file v directory, nh:
os.makedirs(path[, mode]) : to ng dn (c
recursive)
os.removedirs(path) : xa mt ng dn (c
recursive)
ti hay khng
os.path.getsize(path) : ly file size (byte)
th mc
os.path.dirname(path) : tr v tn th mc ca path
mi nht
os.path.getmtime(path) : tr v thi gian chnh sa
cui cng
os.path.getctime(path) : tr v thi gian chnh sa
Xem thm ti
https://docs.python.org/2/library/os.path.html
Chng 6. X l hnh nh
S dng th vin Pillow (PIL Fork) tin hnh cc thao
tc x l hnh nh n gin nh resize, crop, rotate
6.1. Ci t PIL
Vo trang web sau download / ci t package PIL cho
python ca bn
http://pillow.readthedocs.org/en/latest/installation.html
6.2. M file
from PIL import Image
im = Image.open("photo.jpg")
Sau khi m file hnh thnh cng th c th thao tc trn i
tng im .
...
im.save('photo_new.jpg', 'JPEG')
6.4. To thumbnail
S dng phng thc thumbnail nh sau:
V d trn s truy vn ng dn
https://api.github.com/users/voduytuan/repos ly danh
sch Repository trn Github ca mnh di nh dng
JSON. Sau , s c
mystring = '{"a":1,"b":2,"c":3,"d":4,"e":5}'
data = json.loads(mystring)
print data
(Hin th: {u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd
': 4})
import json
mydata = {
'name': 'John',
'age': 10
}
jsonstring = json.dumps(mydata)
print jsonstring
(hin th: {"age": 10, "name": "John"})
Chng 8. X l file XML
Trong phn ny, chng ta s parsing ni dung XML thnh
d liu x l. x l XML, ta s s dng th vin
Beautifulsoup 4. y l mt th vin gip vic trin khai
vic parsing html, xml c nhanh chng v tin li.
8.1. Ci t Beautifulsoup
Bn c th tham kho hng dn cch ci t ti website
http://www.crummy.com/software/BeautifulSoup/bs4/doc/#ins
beautiful-soup.
note = '''
<?xml version="1.0" encoding="UTF-8"?>
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>Two of our famous Belgian Waff
les with plenty of real maple syrup</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>Light Belgian waffles covered
with strawberries and whipped cream</description>
<calories>900</calories>
</food>
</breakfast_menu>
'''
soup = Soup(note, 'xml')
foods = soup.findAll('food')
for x in foods:
print x.find('name').string, ': ', x.price.stri
ng
findAll() : tr v mng cc th c tn cn tm
...
soup = Soup(websitehtml, 'html')
Chng 9. Kt ni MySQL
MySQL l mt h c s d liu quan h ph bin nht hin
nay. Rt nhiu ngn ng c th kt ni n MySQL v
Python cng khng ngoi l.
9.1. Ci t MySQLdb
Ci t thng qua pip nh sau:
$ sudo ln -s /usr/local/mysql/lib/libmysqlclient.18
.dylib /usr/lib/libmysqlclient.18.dylib
import MySQLdb
db = MySQLdb.connect(host = 'localhost', user = 'ro
ot', passwd = 'root', db = 'mysql');
cursor = db.cursor()
sql = 'SELECT * FROM user'
cursor.execute(sql)
myusers = cursor.fetchall()
import MySQLdb
9.6. ng kt ni
Sau khi kt ni v truy vn th c th ng kt ni theo v
d sau:
import MySQLdb
db = MySQLdb.connect(...)
db.close()
...
cur.execute("UPDATE Writers SET Name = %s WHERE Id
= %s", ("John", "4"))
...
10.1. Ci t
C th xem thm v hng dn ci t th vin ny ti
https://github.com/andymccurdy/redis-py
10.2 Kt ni n Redis
kt ni n Redis server th bn c th xem v d sau:
import redis
r = redis.StrictRedis(host='localhost', port=6379,
db=0)
import redis
r = redis.StrictRedis(...)
r.set('foo', 'bar')
print r.get('foo')
(Hin th 'bar')
10.4. Pipeline
Pipeline l k thut c dng trong trng hp bn mun
tng performance bi gp nhiu lnh vo mt request thay
v mi lnh l mt request nh thng thng. Xem v d
sau hiu cch s dng pipeline bng redis-py :
import redis
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()
11.1. Ci t
C th xem thm v hng dn ci t th vin ny ti
http://sendapatch.se/projects/pylibmc/install.html
import pylibmc
mc = pylibmc.Client(...)
mc.set('foo', 'bar')
print mc.get('foo')
(Hin th 'bar')
Chng 12. Kt ni RabbitMQ
RabbitMQ l mt phn mm cho php xy dng Message
Queue theo protocol AMQP v kh thng dng trn th
gii. kt ni n RabbitMQ trn Python, ta s s dng
th vin pika .
12.1. Ci t
C th xem thm v hng dn ci t th vin ny ti
https://pika.readthedocs.org/en/0.10.0/
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()
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()
https://www.rabbitmq.com/tutorials/tutorial-one-
python.html
Chng 13. Restful client
Ngy nay, vi s phong ph ca cc ng dng v nhu cu
kt ni ngy cng ln th Restful l mt trong nhng m
hnh web service c nhiu cng ty s dng. Do , vic
c th kt ni n cc Restful web service l mt k nng
cn thit cho cc lp trnh vin.
13.1. Ci t
Ci t nhanh chng thng qua pip nh sau:
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")
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data =
payload)
import requests
url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
13.3. Response
Sau khi gi cc phng thc tng ng request, bn s
c i tng thuc class Response . i tng ny c mt
s thng tin nh sau:
dng Dictionary.
cookies : Nu server c tr v cookie th c th s
14.1. Ci t sender
Ci t t pip nh sau:
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)
import socket
s = socket.socket()
host = '127.0.0.1'
port = 12345
s.connect((host, port))
print s.recv(1024)
s.close