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的版本

  1. 先看客户端的代码:
#!/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()
  1. 再看服务器端的代码:
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代码就不赘述了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值