【问题标题】:Storing some small files with MongoDB in Flask WITHOUT GridFS在没有 GridFS 的 Flask 中使用 MongoDB 存储一些小文件
【发布时间】:2017-01-17 23:30:31
【问题描述】:

我正在尝试将 PDF 文件插入 MongoDB 数据库。这些文件足够小(flask_pymongo 做到这一点(或者甚至使用pymongo 的基本示例会很棒)。

这是我目前所拥有的,但我收到以下错误:

bson.errors.InvalidStringData:文档中的字符串必须是有效的 UTF-8

flask_app.py:

from flask import Flask, render_template_request
from flask_pymongo import PyMongo

app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'records'
app.config['MONGO_URI'] = 'mongodb://localhost:27017/records'
mongo = PyMongo(app)

@app.route('/', methods=['GET', 'POST'])
def upload():
    if request.method = 'POST':
        files_collection = mongo.db.files_collection  # connect to mongodb collection
        input_file = request.files['input_file']  # get file from front-end
        files_collection.insert_one({'data': input_file.read() })  # error occurs here
        return 'File uploaded'
return render_template('index.html')

index.html:

<form method='POST' action="{{ url_for('upload') }}" enctype='multipart/form-data'>
    <input type='file' name='input_file'>
    <input type='submit' value='Upload'>
</form>

似乎我只需要在将数据输入到 mongodb 之前将其转换为正确的数据类型,这似乎是基于此答案 herebinData 类型

【问题讨论】:

    标签: python mongodb flask pymongo


    【解决方案1】:

    使用bson.Binary 类来存储无类型数据:

    from bson import Binary
    my_pdf_data = b'xxx'  # bytes, can be anything, not just UTF-8
    
    db.collection.insert({'data': Binary(my_pdf_data)})
    document = db.collection.find_one()
    print(repr(document['data']))
    print(type(document['data']))
    

    二进制类型继承自 Python 的内置“字节”类型,因此您可以在任何使用字节的地方使用它 - 例如,将其保存到文件中,将其传递给 PDF 解析器。在 Python 2 中,此代码打印:

    Binary('xxx', 0)
    <class 'bson.binary.Binary'>
    

    在 Python 3 中,Binary 的实例将直接解码为“字节”,因此会打印:

    b'xxx'
    <class 'bytes'>
    

    【讨论】:

      猜你喜欢
      • 2012-07-11
      • 1970-01-01
      • 2014-05-11
      • 2013-10-27
      • 2016-04-05
      • 2015-04-06
      • 2015-12-21
      • 2019-06-19
      • 1970-01-01
      相关资源
      最近更新 更多