一、為什么要進(jìn)行改進(jìn)?
在實(shí)際的開發(fā)過程中,我們?cè)陂_發(fā)期間要對(duì)代碼反復(fù)的進(jìn)行查看(重構(gòu)過程),這里將上傳代碼的過程用面向?qū)ο蟮木幋a方式來進(jìn)行對(duì)代碼的操作。
二、具體代碼實(shí)現(xiàn)如下所示(用面向?qū)ο蟮姆绞絹韺?shí)現(xiàn))
1、photo.py模板中來進(jìn)行編寫圖片上傳的主要代碼
import uuid
import os
from PIL import Image
class UploadImage(object):
"""
輔助保存用戶上傳的圖片,生成對(duì)應(yīng)的縮略圖,記錄圖片相關(guān)的url,保存到數(shù)據(jù)庫(kù)中
"""
upload_dir = 'upload'
thumb_dir = 'thumbs'
thumb_size = (200, 200)
def __init__(self, ext, static_path):
self.ext = ext #文件的后綴名
self.new_name = self.get_new_name() + self.ext #形成新的文件名
self.static_path = static_path #獲取settings中的static_path的值
def get_new_name(self):
return uuid.uuid4().hex #用 uuid 庫(kù)生成的字符串使上傳圖片的名字變得唯一
@property
def image_url(self):
return os.path.join(self.upload_dir, self.new_name)#保存到數(shù)據(jù)庫(kù)中的圖片路徑
@property
def save_to(self):
return os.path.join(self.static_path, self.image_url)#將上傳的圖片保存到相關(guān)的路徑中
def save_content(self, content):
with open(self.save_to, 'wb') as f:
f.write(content)
@property
def thumb_url(self):
name, ext = os.path.splitext(self.new_name)#獲取擴(kuò)展名,這是一個(gè)元組對(duì)象
thumb_name = '{}_{}X{}{}'.format(name, self.thumb_size[0], self.thumb_size[1], ext)
return os.path.join(self.thumb_dir, thumb_name)
def make_thumb(self):
im = Image.open(self.save_to) #生成相應(yīng)的縮略圖,第一步打開圖片獲取其內(nèi)容
im.thumbnail(self.thumb_size)
path = os.path.join(self.static_path, self.thumb_url)
im.save(path)
2、main.py中的相關(guān)處理類
class UploadHandler(BaseHandler):
"""
用戶上傳圖片信息
"""
@tornado.web.authenticated
def get(self):
self.render('user/upload.html', username=self.current_user)
@tornado.web.authenticated
def post(self):
try:
files = self.request.files['picture']#list類型中包含一個(gè)字典
if files[0]:
dict_img = files[0]
filename = dict_img['filename']
print(filename)
print(dict_img['content_type'])
content = dict_img['body']
_, ext = os.path.splitext(filename)
upload_im = UploadImage(ext, self.application.settings['static_path'])
upload_im.save_content(content)
upload_im.make_thumb()
post_id = self.orm.add_post(self.current_user, upload_im.image_url, upload_im.thumb_url)
if post_id:
self.redirect('/post/{}'.format(str(post_id)))
else:
self.write("上傳失敗,系統(tǒng)不聽話")
except Exception as e:
print(e)
self.redirect('/upload')
三、property屬性的相應(yīng)文章
- 將一個(gè)方法當(dāng)作一個(gè)屬性來進(jìn)行調(diào)用
- property屬性