Python Web框架Flask中使用七牛云存储实例

对于小型站点,使用七牛云存储的免费配额已足够为站点提供稳定、快速的存储服务

七牛云存储已有Python SDK,对它进行简单封装后,就可以直接在Flask中使用了,项目代码见GitHub上Flask-QiniuStorage

使用示例代码:


from flask import Flask

from flask_qiniustorage import Qiniu

 

QINIU_ACCESS_KEY = '七牛 Access Key'

QINIU_SECRET_KEY = '七牛 Secret Key'

QINIU_BUCKET_NAME = '七牛空间名称'

QINIU_BUCKET_DOMAIN = '七牛空间对应域名'

 

app = Flask(__name__)

app.config.from_object(__name__)

qiniu_store = Qiniu(app)

# 或者

# qiniu_store = Qiniu()

# qiniu_store.init_app(app)

 

# 保存文件到七牛

@app.route('/save')

def save():

    data = 'data to save'

    filename = 'filename'

    ret, info = qiniu_store.save(data, filename)

    return str(ret)

 

# 删除七牛空间中的文件

@app.route('/delete')

def delete():

    filename = 'filename'

    ret, info = qiniu_store.delete(filename)

    return str(ret)

 

# 根据文件名获取对应的公开URL

@app.route('/url')

def url():

    filename = 'filename'

    return qiniu_store.url(filename)