8. Django系列之上传文件与下载-djang为服务端,requests为客户端
preface
运维平台新上线一个探测功能,需要上传文件到服务器上和下载文件从服务器上,那么我们就看看requests作为客户端,django作为服务器端怎么去处理? 对于静态文件我们不建议通过django下载,而是建议通过django返回一个重定向URL(下载文件的URL)给client,这个url是nginx提供下载,众所周知,nginx是非常牛逼的静态web-server。
以下代码都是简单的代码,可以正常使用,只是实现最基本的要上传文件到服务器上和下载文件从服务器上,不涉及到公司的业务逻辑。文件可以通过md5校验,反正我测试都是一致的MD5值。
Author:温柔易淡
代码如下
使用的python2.7的版本,其他的如果没有做特殊说明是python2.7的版本,那么我的其他博客都是python3.5的版本
- 先看客户端的代码:
#!/usr/bin/env python
# encode:utf-8
import requests
def post_file(): #文件上传(post方法)
post_url='http://127.0.0.1/file/post/'
data=[]
fr=open(r'/tmp/Python-2.7.13.tgz','rb')
file = {'file':('Python-2.7.13.tgz',open(r'/tmp/Python-2.7.13.tgz','rb'),'application/x-tar')}
m = {'act': 'avatar', 'save': '1'}
rt =requests.post(url=post_url,files=file,data=m)
print(rt.status_code,rt.text)
def get_file(): #文件下载(get方法)
get_url = 'http://127.0.0.1/file/get/'
get_params = {'filename':'Python-2.7.13.tgz'}
rt = requests.get(url=get_url,params=get_params)
with open('/tmp/vmware-root/Python-2.7.13.tgz','wb') as f:
# it's not img or others and so on ,if it is ,we need to use BytesIO to save
# for example:
# from io import BytesIO
# i = Image.open(BytesIO(r.content)) # r is a return object
for chunk in rt.iter_content():
f.write(chunk)
print('ok')
#post_file()
get_file()
- 再看服务器端的代码:
from django.shortcuts import render,HttpResponse
from django.http import StreamingHttpResponse
# Create your views here.
def file_get(request): #文件下载(get方法)
print(request.GET)
file_name = request.GET.get('filename')
file_path = "/root/%s"%(file_name)
def file_read(file_name,chunk_size=1024):
# itertor return the file's chunk, if the file size is very large,it must be useful, so server won't OOM
with open(file_name,'rb') as f:
while True:
chunks = f.read(chunk_size)
if chunks:
print(chunks)
yield chunks
else:
break
response_data = StreamingHttpResponse(file_read(file_path))
response_data['Content-Type'] = 'application/octet-stream' # set the type as stream then PC will save it in their disk
response_data['Content-Disposition'] = 'attachment;filename="%s"'%(file_name) # set the file name
return response_data
def file_post(request):
print(request.POST,request.FILES)
file_obj = request.FILES.get('file')
print(type(file_obj))
if file_obj:
save_file_path='/root/%s'%(file_obj.name)
with open(save_file_path,'wb') as f:
for chunks in file_obj.chunks():
f.write(chunks)
return HttpResponse('ok')
其他的url代码就不赘述了。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构