Python 实现MongoDB Gridfs图片存取

Python 同时被 2 个专栏收录
38 篇文章 1 订阅
11 篇文章 0 订阅

 Python 实现MongoDB Gridfs图片存取

Gridfs官方文档链接:http://api.mongodb.com/python/current/api/gridfs/index.html?highlight=gridfs#module-gridfs

# -*- coding:utf-8 -*-

from gridfs import GridFS
from pymongo import MongoClient
import urllib
import os


def write_file(data_host='localhost', data_db='gridfs_check', data_col='pic', file_name=None, data_link=None):
    """
    上传图片到MongoDB Gridfs
    :param data_host mongodb 服务器地址
    :param data_db: 数据库地址
    :param data_col:集合
    :param file_name: (图片)文件名称
    :param data_link: (图片)原始链接
    :return:
    """
    the_db = MongoClient(data_host).get_database(data_db)
    gridfs_col = GridFS(the_db, collection=data_col)
    filter_condition = {"filename": file_name, "url": data_link}

    """下载图片到本地后上传到MongoDB Gridfs后删除本地文件"""
    urllib.urlretrieve(data_link, "%s" % file_name)  # 将图片下载到本地
    with open("%s".decode('utf-8') % file_name, 'rb') as my_image:
        picture_data = my_image.read()
        file_ = gridfs_col.put(data=picture_data, **filter_condition)  # 上传到gridfs
        print file_
        my_image.close()

        os.remove("%s" % file_name)  # 删除本地图片


def read_data(data_host='localhost', data_db='gridfs_check', data_col='pic', file_name=None):
    """
    从MongoDB Gridfs下载图片
    :param data_host mongodb 服务器地址
    :param data_db: 数据库地址
    :param data_col:集合
    :param file_name: (图片)文件名称
    :return:
    """
    the_db = MongoClient(data_host).get_database(data_db)
    gridfs_col = GridFS(the_db, collection=data_col)
    data = gridfs_col.get_version(filename=file_name, version=0).read()
    # print data
    out = open(('F:/%s' % file_name).decode('utf-8'), 'wb')   # .decode('utf-8')
    out.write(data)
    out.close()


if __name__ == "__main__":
    link = "https://media.licdn.com/dms/image/C4E03AQGhU6VJLcn9xA/profile-displayphoto-shrink_800_800/0?e=1558569600&" \
           "v=beta&t=esCQZeqoQCrBkqVo44RH7HkjOLPSM9rrsyJ2ZUwOFn4"

    write_file(file_name='people1.jpg', data_link=link)
    # read_data(file_name='people1.jpg')

 

  • 1
    点赞
  • 0
    评论
  • 6
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值