简体   繁体   中英

How to save small png images to Mongodb database using pymongo

I want to save png file to my Mongodb Database. I am trying this with code like this:

    with open(SCREENCAP_FILE_NAME, 'rb') as f:
    page_info_tuple = {
        "page_hash": _page_hash,
        "ativity_name": _activity_name,
        "screen_shot": f
    }
    Mongo.coll_pageinfo.insert_one(page_info_tuple)

However, it gives me

bson.errors.InvalidDocument: Cannot encode object: open file 'screen.png', mode 'rb' at 0x109d3ced0

I solved this problem by using code like this:

from bson import Binary

with open(SCREENCAP_FILE_NAME, mode='rb') as f:
    page_info_tuple = {
        "page_hash": _page_hash,
        "ativity_name": _activity_name,
        "screen_shot": Binary(f.read())
    }
    Mongo.coll_pageinfo.insert_one(page_info_tuple)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM