【问题标题】:Save a writable file into database?将可写文件保存到数据库中?
【发布时间】:2017-03-16 08:09:26
【问题描述】:

我正在使用 django 1.8 和 python 3.4 并尝试创建一个 json 文件然后写入它,之后我需要将它保存到我的数据库中,但保存时它返回一个错误 '_io.TextIOWrapper' 对象没有属性“_committed”。谁能帮助我做错了什么? 这是我的models.py

class ConvertedFile(models.Model):
    file = models.FileField(upload_to='json/upload', max_length=5000)
    created_on = models.DateTimeField(auto_now_add=True)

我的views.py是-

def convert_file(request):
    url = request.GET.get('q', None)
    r = requests.get(url, stream=True)
    with open('file.csv', 'wb') as out_file:
        shutil.copyfileobj(r.raw, out_file)
    csvfile = open("file.csv", "r")
    jsonfile = open("file.json", "w")
    csv_rows = []
    reader = csv.DictReader(csvfile)
    title = reader.fieldnames
    try:
        for row in reader:
            csv_rows.extend([{title[i]: row[title[i]] for i in range(len(title))}])
    except:
        pass

    jsonfile.write(json.dumps(csv_rows, sort_keys=False, indent=4, separators=(',', ': '), ensure_ascii=False))

    os.remove("file.csv")
    jsonfile.close()

    new_json = ConvertedFile.objects.create()
    new_json.file = jsonfile
    new_jsone.save()

【问题讨论】:

  • 可能不相关,但您必须先关闭csvfile,然后才能将其删除。例如,这会在 Windows 上崩溃。
  • @Jean-FrançoisFabre 谢谢,有什么建议可以解决我的问题吗?
  • Jsonfile 是一个封闭的文件。您正在将它传递给您的 new_json 对象。它不是正确的类型,即使它是一个关闭的文件。
  • 不要将文件保存在数据库中。 stackoverflow.com/a/38829952/267540

标签: python django file-io


【解决方案1】:

最后一行的model.save() 出现错误,对吗? new_json.file = jsonfile 上面的那行是问题所在。您将从 django 对已关闭(普通 python)文件对象的引用传递给 FileField,但它不知道如何处理它(例如,缺少_commited)。

看看Django - how to create a file and save it to a model's FileField?

【讨论】:

    猜你喜欢
    • 2021-06-05
    • 2017-10-25
    • 2012-07-11
    • 2013-07-11
    • 2012-03-27
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    相关资源
    最近更新 更多