python服務器文件上傳下載+GUI【tkinter】

大概就是一個經過應用程序來和服務器打交道的這麼一個,小東西web

1.GUI

用的是tkinter服務器

 1 # -*- coding: UTF-8 -*-
 2 from tkinter import *
 3 import tkinter.filedialog
 4 import requests
 5 
 6 
 7 def Upload():
 8     print('upload')
 9     selectFileName = tkinter.filedialog.askopenfilename(title='選擇文件')#選擇文件
10     
11     r = requests.post('http://127.0.0.1:8000/upload', files={'file':open(selectFileName,'rb')})
12     print(r.content.decode('utf-8'))
13     setText = r.content.decode('utf-8')
14     print(setText.__class__)
15     e1.delete(0,END)
16     e1.insert(0,setText)
17 
18 def Download():
19     link = e1.get()
20     files = requests.get(link)
21     files.raise_for_status()
22     path = tkinter.filedialog.asksaveasfilename()
23     print(files.content)
24     with open(path, 'wb') as f:
25         f.write(files.content)
26 
27 
28 root = Tk()
29 root.title('Download')
30 root.geometry('+500+300')
31 
32 e1 = Entry(root,width=50)
33 e1.grid(row=0, column=0)
34 
35 btn1 = Button(root,text=' 上傳 ', command=Upload).grid(row=1, column=0,pady=5)
36 btn2 = Button(root,text=' 下載 ', command=Download).grid(row=2, column=0,pady=5)
37 btn3 = Button(root,text=' 複製 ', ).grid(row=3, column=0,pady=5)
38 
39 mainloop()

服務器對中文文件名很不友好,只要出現中文文件名,必報錯,搞得我很沒心情,因此Copy函數就沒實現app

還有,一大堆亂七八糟的編碼,反正我如今也沒搞明白框架

一會必須用bytes()轉二進制碼,一會又要decode又要encode,有點迷。。。函數

2.服務器

用的是巨簡易的框架,簡單的返回一兩個頁面就能夠了,畢竟是模擬oop

 1 # -*- coding: UTF-8 -*-
 2 import web
 3 urls = (
 4     '/','Index',
 5     '/upload','Upload',
 6 )#路由
 7 
 8 render = web.template.render('template')
 9 
10 class Index:
11     def GET(self):#函數名時請求方式
12         return render.index()
13 
14 class Upload:
15     def POST(self):
16         info = web.input(file = {})#接收數據
17         filename = info['file'].filename
18         thisfile = info['file'].file.read()
19         with open('static/%s' %filename, 'wb') as f:
20             f.write(thisfile)
21         s = format('http://127.0.0.1:8000/static/%s' %filename)
22         return s
23 
24 
25 app = web.application(urls, globals())
26 
27 if __name__ == '__main__':#入口函數判斷
28     app.run()
29 
30 #'Server.py 127.0.0.1:8000'

以前用Django寫了一個簡單的音樂網站,好多細節都忘了,這個用的時候感受有點像,也算是小小地回憶了一下post

總結

放假是真的無聊,想學點比較實踐的知識,但發現無從下手,真的很迷茫網站

這回就當隨便搞搞小東西,練練手了吧this

中文真的不友好!!!!!!!!!!!!!!!!!!!!!!!!!!google

太tm麻煩了,要不是這些個亂七八糟的編碼問題,我能把花費時間縮短80%!!!

多麼可怕的數字,但就是這無腦的問題,能折騰的人死去活來

哦對了requsets包裏的post方法,當參數有files=的時候,這個上傳的文件名不能是中文

不然服務器那別收不到參數

最後改了urllib3.py源碼下的一個函數的解碼方式,從‘ascll’改爲了‘utf-8’,才能上傳中文文件名的文件

可是,下載中文文件的時候仍是會出錯好比訪問

http://127.0.0.1:8000/static/你好.txt的時候,服務器那邊會報錯「WSGI啥啥」,這個錯誤,baidu,google都沒有,無解,放棄,心情不好

相關文章
相關標籤/搜索