1. 通过七牛云将照片存储在云端
# 网址:
https://developer.qiniu.com/kodo/1242/python
# 新建空间: 注册和登录七牛云-->管理控制台 --> 存储空间 --> 空间管理-->新建空间
# SDK代码实例: 对象存储-->SDK-->Python
# 安装库文件
pip install qiniu
2. settings.py 配置七牛云的 AccessKey 和 SecretKey
AccessKey="xxxxxxx" # 七牛云AccessKey
SecretKey="xxxxxx" # 七牛云SecretKey
3. util / qiniu.py 封装上传和删除 七牛云 函数
# access_key 和 secret_key 自行百度获取
import os
import random
from qiniu import Auth, put_file, etag, put_data, BucketManager
import qiniu.config
# 需要填写你的 Access Key 和 Secret Key
from settings import Config
# 上传相册到七牛云
def upload_qiniu(filestorage):
# access_key = 'access_key'
# secret_key = 'secret_key'
# 构建鉴权对象(Config里的Access Key 和 Secret Key)
q = Auth(Config.AccessKey, Config.SecretKey)
# 要上传的空间
bucket_name = 'myblog20230528'
# 上传后保存的文件名
filename = filestorage.filename
# filename = "1.png"
rran = random.randint(1, 1000)
suffix = filename.rsplit(".")[-1]
key = filename.rsplit(".")[0] + "_" + str(rran) + "." + suffix
# 生成上传 Token,可以指定过期时间等
token = q.upload_token(bucket_name, key, 3600)
# 要上传文件的本地路径
# localfile = os.path.join(Config.UPLOAD_ICON_DIR, "1683713252745.jpg")
#
# ret, info = put_file(token, key, localfile, version='v2')
# 参数: token,key,读取的二进制
ret, info = put_data(token, key, filestorage.read())
return ret, info
def delete_qiniu(filename):
# access_key = 'access_key'
# secret_key = 'secret_key'
# 构建鉴权对象
q = Auth(Config.AccessKey, Config.SecretKey)
# 要上传的空间
bucket_name = 'myblog20230528'
# 初始化BucketManager
bucket = BucketManager(q)
# key就是要删除的文件名字
key = filename
ret, info = bucket.delete(bucket_name, key)
return info
if __name__ == '__main__':
path=os.path.dirname(__file__).rsplit("\\",1)[0]+"\\static\\1.png"
# file=open(path,"rb",)
#
# print(upload_qiniu(file))
4. templates / user / center.html 填充管理相册功能
<!-- 管理相册-->
<div class="right1">
<form action="{{ url_for('user.upload_photo') }}" method="post" enctype="multipart/form-data"
class="form-inline">
<input type="file" name="photo" class="form-control">
<input type="submit" value="上传相册" class="form-btn btn-default">
</form>
<div class="row">
<div class="col-sm-12">
<h3>我的相册</h3>
<div class="row">
{% for photo in photos %}
<div class="col-xs-8 col-sm-4">
<img src="http://rveq0tjn6.hn-bkt.clouddn.com/{{ photo.photo_name }}"
class="img-rounded image">
<button class="btn btn-info btn-xs photo-del" tag="{{ photo.id }}">删除</button>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
5. apps / user / view.py 编写管理和删除相册函数
# 通过七牛云上传照片
@user_bp.route('/upload_photo', methods=["GET", "POST"])
def upload_photo():
# 获取上传的内容
phone = request.files.get('photo') # FileStorage类型
# photo.filename , photo.save(path)
# 工具模块中封装方法
ret, info = upload_qiniu(phone)
if info.status_code == 200:
photo = Photo()
photo.photo_name = ret["key"] # 上传的文件名
photo.user_id = g.user.id
db.session.add(photo)
db.session.commit()
return "上传成功"
else:
return "上传失败"
# 删除相册图片
@user_bp.route("/photo_del")
def photo_del():
pid = request.args.get('pid')
photo = Photo.query.get(pid)
filename = photo.photo_name
# 封装好的一个删除骑牛存储文件的函数
info = delete_qiniu(filename)
# 判断状态码
if info.status_code == 200:
# 删除数据库内容
db.session.delete(photo)
db.session.commit()
return redirect(url_for('user.user_center'))
else:
return render_template("500.html", err_msg="删除相册图片失败")
6. static / js / center.js 使用ajax操作相册删除
$(function () {
//相册图片删除
$('.photo-del').click(function () {
// 弹窗: 返回值是bool类型
flag = confirm("确定删除此图片吗")
if (flag) {
//获取属性值tag,tag属性就是图片的主键
let pid = $(this).attr("tag");
// 1. ajax , 2. location.href
location.href = '/user/photo_del?pid=' + pid
}
});
....
})
7. templates/500.html 编写错误页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>错误提示</title>
</head>
<body>
<p>{{ err_msg }}</p>
<!--根据浏览器跳转转的话,头部会有上一页的地址:referer:xxx-->
<a href="{% if referer %}{{ referer }}{% else %}{{ url_for('user.index') }}{% endif %}">返回上一页</a>
</body>
</html>
8. apps / user / view.py 编写错误页面函数
# 错误页面,返回上一页
@user_bp.route("/error")
def test_error():
# print(request.headers)
# print(request.headers.get("Host"))
referer = request.headers.get("Referer", None)
return render_template('500.html', err_msg="错误", referer=referer)