如何使用django上传.txt文件,然后读取它,并将其存储到Mysql数据库中?

时间:2016-10-13 09:21:12

标签: python mysql django

像这样的ip.txt文件:

192.168.49.132  test  1
192.168.49.133  test  2

现在我可以将它上传到我的django项目中,

  def handle_upload(f):                  
    path = os.path.join(BASE_DIR, 'upload/').replace('\\', '/')
    filename=path+f.name
    with open(filename,'wb+') as desction:
        for chunk in f.chunks():
            desction.write(chunk)

阅读列表并插入mysql

 def mysql_insert(iplist,userlist,passwordlist):

    try:
         conn=MySQLdb.connect(host='localhost',user='root',passwd='123',port=3306)
       cur =conn.cursor()
       cur.execture('create database if not exists python')
       conn.select_db('mmot')
       for ip,user,password in zip(iplist,userlist,passwordlist):
           cur.execture('insert into ip_iptable(ip,user,password) values(%s,%s,%s) ' %(ip,user,password))
       cur.close()
       conn.close()
    except MySQLdb.Error,e:
        print ('Some error!')

读取文件并将其存储到三个列表中

def open_file(filename):
  iplist=[]
  userlist=[]
  passwordlist=[]
  try:
    if str(filename).endswith('.txt'):
        with open(filename) as f:
            data =f.readlines()
            for line in data:
                line=line.replace('\n','').split()
                iplist.append(line[0])
                userlist.append(line[1])
                passwordlist.append(line[2])
            mysql_insert(iplist,userlist,passwordlist) #insert into databases
    else:
        print ("The file is not txt file")

  except Exception,ex:
        print ("Sorry,some error!")

views.py

def upload(req):
if req.method=="POST":
    upfile=UploadFile(req.POST,req.FILES)
    if upfile.is_valid():
      handle_upload(upfile.cleaned_data['file'])  #read it and write 
      open_file(upfile.cleaned_data['file'])      #open it 
      return HttpResponse('successful!')
else:
    upfile=UploadFile()
return render_to_response('ip/ipadd.html',locals())

但它不起作用,我该如何纠正呢?

0 个答案:

没有答案