都說Django是重量級的web框架,而web.py是輕量級的,django給我印象最深刻的還是它的admin管理,由於是django自帶的,其它方面還沒看出來怎麼樣,但是web.py也很有趣,寫起應用來,短小而精悍。
官網上有一個文件上傳的示例程序,代碼如下:
import web
urls = ('/upload', 'Upload')
class Upload:
def GET(self):
web.header("Content-Type","text/html; charset=utf-8")
return """<html><head></head><body>
<form method="POST" enctype="multipart/form-data" action="">
<input type="file" name="myfile" />
<br/>
<input type="submit" />
</form>
</body></html>"""
def POST(self):
x = web.input(myfile={})
filedir = '/path/where/you/want/to/save' # change this to the directory you want to store the file in.
if 'myfile' in x: # to check if the file-object is created
filepath=x.myfile.filename.replace('\\','/') # replaces the windows-style slashes with linux ones.
filename=filepath.split('/')[-1] # splits the and chooses the last part (the filename with extension)
fout = open(filedir +'/'+ filename,'w') # creates the file where the uploaded file should be stored
fout.write(x.myfile.file.read()) # writes the uploaded file to the newly created file.
fout.close() # closes the file, upload complete.
raise web.seeother('/upload')
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
(html文字還是模板的形式比較好)。在windows下小試了一把,發現在上傳中文名文件時會出現亂碼,以爲是程序的編碼出問題了,於是把程序的編碼改成了uft8,在程序開頭加了幾句
default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
reload(sys)
sys.setdefaultencoding(default_encoding)
結果還是不行,納悶了,於是查看了一下文件名保存後的編碼方案,還是utf-8,由於我是在xp運行的,文件上傳保存在本機上,這下找着原因了,原來是windows不認識utf-8編碼的漢字了,於是加上一句
filename = filename.encode("gb2312")
結果漢字就是漢字了,沒有亂碼。看來文字的編碼方式在網絡傳輸中很重要。這讓我想到了協議,類似於printf函數參數入棧順序,printf的參數是從左到右入棧,而printf的函數調用方以從右至左的入棧順序去識別它,那肯定就會出錯了,一點聯想。
關於文字編碼的問題我已經遇到不止一次了,前有mysql不能正常顯示漢字,php頁面文字亂碼,還是unicode好,一統天下了,不過貌似浪費了很多空間。嗯,編碼方案,要再細細研究研究。