python - 使用 Bottle 上传和处理 CSV 文件;可能的编码问题

标签 python python-3.x csv bottle

我正在尝试使用 Bottle 通过 HTML 表单上传和处理 CSV 文件。我已经用 Tkinter 创建了一个工作示例; CSV 上传很好,所有数据(包括散列密码)都进入了 Sqlite3 数据库。

正在运行 TKINTER 代码 ...

import os
import sqlite3
import csv
from pbkdf2 import crypt
from tkinter import *
from tkinter import filedialog
root = Tk()
root.geometry("500x500")

def open1():
    filename = filedialog.askopenfilename()
    with open(filename,"r") as s_info:
        reader = csv.reader(s_info)
        for x in reader:
            pwhash = crypt(x[1])
            connection = sqlite3.connect("users.db")
            cursor_v = connection.cursor()
            cursor_v.execute("insert into users (cemail, cpassword) values (?,?)", (x[0],pwhash))
            connection.commit()
            cursor_v.close()
        else:
            print("CSV Uploaded")

x = Button(text="Open",command=open1).pack()

问题是当我尝试在 Bottle 中重新创建代码时,出现以下错误:

Bottle 代码 - HTML:

<form action="/panel" method="post" enctype="multipart/form-data">
  <input type="file" name="data" />
  <input type="submit">
</form>

Bottle 代码 - 路线:

@route('/panel', method='POST')
def do_upload():
    data = request.files.data
    with open(data,"r") as s_info:
        reader = csv.reader(s_info)
        for x in reader:
            pwhash = crypt(x[1])
            connection = sqlite3.connect("users.db")
            cursor_v = connection.cursor()
            cursor_v.execute("insert into users (cemail, cpassword) values (?,?)", (x[0],pwhash))
            connection.commit()
            cursor_v.close()
        else:
            return "<p>CSV Uploaded</p>"

错误:

with open(data,"r") as s_info:
TypeError: invalid file: <bottle.FileUpload object at 0x105cb84d0>

感谢任何帮助

最佳答案

request.files.data 是一个 FileUpload目的。它有一个名为 file 的属性,因此:

编辑:更新为处理 urllib 与 python-3.x 给出的字节流。

import codecs

def do_upload():
    reader = csv.reader(codecs.iterdecode(request.files.data.file, 'utf-8'))
    for x in reader:
        ...

应该可以工作,让你的 bottle 代码看起来像这样:

import codecs

@route('/panel', method='POST')
def do_upload():
    reader = csv.reader(codecs.iterdecode(request.files.data.file, 'utf-8'))
    for x in reader:
        pwhash = crypt(x[1])
        connection = sqlite3.connect("users.db")
        cursor_v = connection.cursor()
        cursor_v.execute("insert into users (cemail, cpassword) values (?,?)", (x[0],pwhash))
        connection.commit()
        cursor_v.close()
    else:
        return "<p>CSV Uploaded</p>"

关于python - 使用 Bottle 上传和处理 CSV 文件;可能的编码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36958214/

相关文章:

python - 为什么排序列表比未排序列表大

python-3.x - Pandas groupby,对行求和,并将求和除以组中的行数

csv - Pig 如何使用过滤器格式化半结构化 CSV

python - 处理文本 : change all letters to lowercase in a CSV file

python - 将每个值放在 Pandas 的百分位数中

python - 按多列分组的值的线图

python - 将时间列表转换为总时间

python - Shutil.rmtree(...) 在我的脚本中不起作用

python-3.x - Python3 表情符号字符作为 unicode

arrays - 在 JMeter 中从 CSV 文件传递​​数组