分布式文件存储系统之小文件上传/下载(python3.8+MongoDB 4.2.3)

参考:

  1. Python3 File(文件) 方法
  2. MongoDB and PyMongo Tutorial

分布式文件存储环境:
Python3.8,PyMongo 3.10.1,MongoDB 4.2.3

小文件上传方法:

#!/usr/bin/python3
 
from pymongo import MongoClient

# connecting to database. db:testfile, collection:hello 
myclient = MongoClient('mongodb://localhost:40009/')
db = myclient.testfile
collection = db.hello

# open a file to upload
myfile = open(file='D:/workspace/language.pdf',mode='rb')
data = myfile.read()

doc = [{
     "userid":"5",
        "filename":"language",
        "filettype":"pdf",
        "content":data,
        "size":"3000"
    }]

# insert document
result = collection.insert_many(doc)
print(result)

myfile.close()


小文件下载方法:

#!/usr/bin/python3
 
from pymongo import MongoClient

# connecting to database. db:testfile, collection:hello  
myclient = MongoClient('mongodb://localhost:40009/')
db = myclient.testfile
collection = db.hello

# find a file to download with "content" value. Stored in test.pdf 
mydoc = collection.find_one({
     "userid":"5"},{
     "_id":0,"content":1})
myfile = open(file='D:/workspace/test.pdf',mode='ab')
data = myfile.write(mydoc["content"])

myfile.close()

你可能感兴趣的:(MongoDB,mongodb,python)