django学习之 从服务端上传文档与下载文档接口

一.首先建立一个项目demo

关于建立一个django项目demo参照:Django继承drfuser模型的demo

相关的项目的个部分代码如下:

1.路由

1)总路由

from django.contrib import admin
from django.urls import path
from django.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    path(r'api/user/', include("user.urls")),  # 用户及用户管理的模块
]

2)子路由

from django.urls import path
from . import views

urlpatterns = [
    # 下载 API 接口文档
    path('upload_file/', views.UPLoadFile.as_view()),
    path('download_file/', views.DownFile.as_view()),

]

 

2.安装相应需要的库与依赖

asgiref==3.2.7
Django==3.0.6
djangorestframework==3.11.0
PyMySQL==0.9.3
pytz==2020.1
sqlparse==0.3.1
xlrd==1.2.0

 

.文件导入接口

1.视图view的代码

from django.contrib.auth.hashers import make_password
from django.db import transaction
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from .models import User
import xlrd


#
class UPLoadFile(APIView):

    def post(self, request):
        file_obj = request.FILES.get('demo_file')
        if file_obj:
            type_excel = file_obj.name.split('.')[1]
        else:
            return Response(status=status.HTTP_400_BAD_REQUEST,
                            data={'code': -2, 'data': '', 'msg': '请求参数错误!'})
        if 'xls' == type_excel or 'xlsx' == type_excel:
            # 开始解析上传的excel表格
            wb = xlrd.open_workbook(filename=None, file_contents=file_obj.read())
            # wb 为一个表对象
            # table 为这个文件里面第一个表格的对象
            table = wb.sheets()[0]
            nrows = table.nrows  # 行数
            # ncole = table.ncols  # 列数
            for i in range(1, nrows):
                row_value = table.row_values(i)  # 一行的数据
                if User.objects.filter(username=row_value[0]).first():
                    return Response(status=status.HTTP_400_BAD_REQUEST,
                                    data={'code': -2, 'data': '', 'msg': '导入表格失败,请检查并修改错误再次导入'})

            try:
                # 正常的数据库操作应该是原子性操作
                with transaction.atomic():
                    for i in range(1, nrows):  # 第二条数据开始读取
                        row_value = table.row_values(i)  # 一行的数据
                        user_data = dict()
                        user_data["username"] = row_value[0]
                        user_data["password"] = make_password(row_value[1])
                        user_data["phone"] = row_value[2]
                        User.objects.create(**user_data)
            except Exception as e:
                return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                                data={'code': -2, 'data': '', 'msg': '导入表格失败,服务异常'})

            return Response(status=status.HTTP_200_OK, data={'code': 0, 'data': '', 'msg': '导入数据成功!'})
        return Response(status=status.HTTP_400_BAD_REQUEST,
                        data={'code': -2, 'data': '', 'msg': '导入文件格式不对,请检查文件格式'})

 

2.接口测试

1postman测试

文件form-data  

文件格式为xls xlsx的表格

表格数据第一行不填写真实数据,第一行填写数据字段的表示内容

key为:demo_file  和视图的代码中的demo_file对应

value为文件,如下:

进行POST请求:http://192.168.109.156:8008/api/user/upload_file/

请求后返回成功的消息

2excel上的数据

注意password phone这种带纯数字的字段,最好再数据前加一个  ’  这个符号,英文形式下的单引号。

否则纯数字发送到服务端的时候的类型默认为float

三.文件下载接口

需要将配置文件存放的目录

项目settings.py中的配置为:

STATIC_URL = '/static/'

# 设置django的静态文件目录
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "statics")
]

然后在项目中添加如下项目目录:

1.视图view的代码

# 下载excel案例文档
class DownFile(APIView):

    def get(self, request):
        file = open('statics/demo_file/demo_file.xls', 'rb')
        response = HttpResponse(file)
        response['Content-Type'] = 'application/octet-stream'  # 设置头信息,告诉浏览器这是个文件
        response['Content-Disposition'] = 'attachment;filename="test_data.xls"'
        return response

2.接口测试

1)浏览器测试

使用浏览器直接访问:

http://192.168.109.156:8008/api/user/download_file/

结果是浏览器会下载到demo_file.xls文件

完成测试成功

注:不能再postman进行测试,postman测试只会返回乱码

原文地址:https://www.cnblogs.com/hszstudypy/p/13081367.html