如何使用Django上传一个.txt文件,然后读取,并存储到Mysql数据库中?

2024-09-20 22:52:14 发布

您现在位置:Python中文网/ 问答频道 /正文

安ip.txt文件像这样的文件:

192.168.49.132  test  1
192.168.49.133  test  2

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

^{pr2}$

阅读列表并插入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!")

在视图.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())

但它不起作用,我该怎么纠正呢?在


Tags: ipdataiflineopenconnreqfile

热门问题