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

参考:

  1. Python3 File(文件) 方法
  2. MongoDB and PyMongo Tutorial
  3. Tools for working with GridFS
  4. 基于Python使用MongoDB及其GridFS进行文档管理

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

大文件GridFS上传方法:

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

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

# Create a new instance of GridFS
gridfs_col = GridFS(db)

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

# upload file to GridFS
myfile = gridfs_col.put(data=mydata,filename="books.pdf")

print(myfile)

大文件GridFS下载方法:

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

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

# Create a new instance of GridFS
gridfs_col = GridFS(db)

# find a file to download with "books.pdf" value. Stored in 111.pdf
mydata = gridfs_col.get_version("books.pdf").read()
myfile = open(file='D:/workspace/111.pdf',mode='wb')
rs = myfile.write(mydata)

print(rs)

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