python服务器文件上传下载+GUI【tkinter】,,大概就是一个通过应用


技术分享

技术分享

大概就是一个通过应用程序来和服务器打交道的这么一个,小东西

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函数就没实现

还有,一大堆乱七八糟的编码,反正我现在也没搞明白

一会必须用bytes()转二进制码,一会又要decode又要encode,有点迷。。。

2.服务器

用的是巨简易的框架,简单的返回一两个页面就可以了,毕竟是模拟

 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‘].filename18         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 s23 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写了一个简单的音乐网站,好多细节都忘了,这个用的时候感觉有点像,也算是小小地回忆了一下

总结

放假是真的无聊,想学点比较实践的知识,但发现无从下手,真的很迷茫

这回就当随便搞搞小东西,练练手了吧

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

太tm麻烦了,要不是这些个乱七八糟的编码问题,我能把花费时间缩短80%!!!

多么可怕的数字,但就是这无脑的问题,能折腾的人死去活来

哦对了requsets包里的post方法,当参数有files=的时候,这个上传的文件名不能是中文

否则服务器那别收不到参数

最后改了urllib3.py源码下的一个函数的解码方式,从‘ascll’改成了‘utf-8’,才能上传中文文件名的文件

但是,下载中文文件的时候还是会出错比如访问

http://127.0.0.1:8000/static/你好.txt的时候,服务器那边会报错“WSGI啥啥”,这个错误,baidu,google都没有,无解,放弃,心情很差

python服务器文件上传下载+GUI【tkinter】

评论关闭