圖片上傳頁(yè)面和代碼的改進(jìn)(十九)

一、為什么要進(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屬性
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • javascript設(shè)計(jì)模式與開發(fā)實(shí)踐 設(shè)計(jì)模式 每個(gè)設(shè)計(jì)模式我們需要從三點(diǎn)問題入手: 定義 作用 用法與實(shí)現(xiàn) 單...
    穿牛仔褲的蚊子閱讀 4,489評(píng)論 0 13
  • 就在母親節(jié)這天,外婆去世了。前一天媽媽就有所察覺,所以舅舅小姨們都聚到我家… 外婆去年就中風(fēng)癱瘓?jiān)诖?,爸媽為了好?..
    Leonor_Z閱讀 302評(píng)論 0 0
  • 天下大勢(shì),合久必分,分久必合。緣來則聚,緣去則散。 正如你出生時(shí),身邊人都在笑,而去世時(shí),身邊人都在哭一樣。緣來時(shí)...
    米安_Laura閱讀 362評(píng)論 0 1
  • 駕馬車跑得如何? 出口不弱,消費(fèi)分層,投資倚重房地產(chǎn) 2018年以來,全球制造業(yè)PMI大幅下滑,經(jīng)濟(jì)明顯減速,主要...
    MON2017閱讀 216評(píng)論 1 2

友情鏈接更多精彩內(nèi)容