首页 > 编程 > Python > 正文

如何在django里上传csv文件并进行入库处理的方法

2020-02-16 00:26:41
字体:
来源:转载
供稿:网友

运维平台导入数据这一功能实在是太重要了,我敢说在没有建自己的cmdb平台前,大多数公司管理服务器信息肯定是表格,用表格最麻烦的就是有点更新就得每个人发一份,这样大家信息才能统一,很不方便,终于有一天受不了了,搞了一个服务器信息管理平台,那面临的第一个问题不是说功能好或不不好,而是怎么才能把表里的数据导入到数据库中,所以你说重要不重要,当然如果你就喜欢自己手工录入(找虐的感觉),这个咱也不能说啥,各有所好嘛,那具体如何录的最快,这个不在我们今天的讨论范围,我只讨论如何自动导入。

提到导入,那一般有二个方法,一个是在前端上传完后存储在服务器上的某个目录里,然后读取文件进行分析处理。

另一种是上传文件后直接读取文件内容而不存储在服务器上,这二种方法都可以实现我们得目的,这篇主要是讨论的后面这种。

上传文件,首先我们建一个html文件,内容代码如下:

<form action="{% url "myapp:upload_csv" %}" method="POST" enctype="multipart/form-data" class="form-horizontal"> {% csrf_token %}<div class="form-group">  <label for="name" class="col-md-3 col-sm-3 col-xs-12 control-label">File: </label>  <div class="col-md-8">    <input type="file" name="csv_file" id="csv_file" required="True" class="form-control">  </div>          </div><div class="form-group">            <div class="col-md-3 col-sm-3 col-xs-12 col-md-offset-3" style="margin-bottom:10px;">     <button class="btn btn-primary"> <span class="glyphicon glyphicon-upload" style="margin-right:5px;"></span>Upload </button>  </div> </div></form>

这些都是基本的Html,只要主要enctype=”multipart/form-data”这个参数就可以,其它无特别说明。

展示如图:

加入路由,

url(r'^upload/csv/$', views.upload_csv, name='upload_csv'),

那接下来就是处理上传的文件并入库了,这个代码在views.py文件里,代码如下:

def upload_csv(request):	data = {}	if "GET" == request.method:		return render(request, "myapp/upload_csv.html", data)  # if not GET, then proceed	try:		csv_file = request.FILES["csv_file"]		if not csv_file.name.endswith('.csv'):			messages.error(request,'File is not CSV type')			return HttpResponseRedirect(reverse("myapp:upload_csv"))    #if file is too large, return		if csv_file.multiple_chunks():			messages.error(request,"Uploaded file is too big (%.2f MB)." % (csv_file.size/(1000*1000),))			return HttpResponseRedirect(reverse("myapp:upload_csv")) 		file_data = csv_file.read().decode("utf-8")		 		lines = file_data.split("/n")		#loop over the lines and save them in db. If error , store as string and then display		for line in lines:									fields = line.split(",")			data_dict = {}			data_dict["name"] = fields[0]			data_dict["start_date_time"] = fields[1]			data_dict["end_date_time"] = fields[2]			data_dict["notes"] = fields[3]			try:				form = EventsForm(data_dict)				if form.is_valid():					form.save()									else:					logging.getLogger("error_logger").error(form.errors.as_json())															except Exception as e:				logging.getLogger("error_logger").error(repr(e))									pass 	except Exception as e:		logging.getLogger("error_logger").error("Unable to upload file. "+repr(e))		messages.error(request,"Unable to upload file. "+repr(e)) 	return HttpResponseRedirect(reverse("myapp:upload_csv"))            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表