
Flask Todo代办事项项目
1.创建基本视图
2.注册功能
2.1 基本注册
2.2 邮箱注册(1)
2.3 邮箱注册(2)
2.4 手机注册
2.5 第三方注册
2.6 用户权限
3.修改个人页面
3.1 个人页面展示(1)
3.1个人页面展示(2)
3.1个人页面展示(3)
3.1 个人页面展示(4)
3.增加personal.html
中各种修改
0.示例代码
https://github.com/ningwenyan/Flask_Todo_Demo/tree/v1.08
5.修改邮箱
修改注册邮箱.它的逻辑是填写必要信息后,发送邮件到原注册邮箱,修改成功.
为修改邮箱添加一个 id
<!-- personal.html -->
<a class="text-success" href="#" id="personalReEmail">修改邮箱</a>
为其创建相应的 js
请求文件, 点击按钮,会生成一个弹出框,填写信息后,会发送一份邮件给自己的邮箱,注意preConfirm
它是在点击确定
之前执行的操作.要配合showLoaderOnConfirm:true
一起使用.在这个函数里面使用AJAX
请求了一个api
,用以验证请求的邮箱是否在服务器上存在.AJAX
内部不能return
,这有一个公共变量来保存结果.而且AJAX
是异步请求的,这里希望它同步返回结果async:false,
.验证成功,就返回填写的参数.最后请求修改邮箱的API
,并验证权限.// auth.js
// 修改邮箱
$('#personalReEmail').click(function(e){
e.preventDefault();
swal.fire({
icon : 'warning',
title: '修改邮箱?',
inputLabel: '点击确定将发送一份邮件到您的新邮箱.',
input: 'email',
inputPlaceholder : '新邮箱',
inputAttributes: {
autocapitalize: 'off'
},
confirmButtonText: '确定',
showCancelButton: true,
cancelButtonText:'取消',
showLoaderOnConfirm: true,
preConfirm: (raw_email) => {
showValidataflag = true; //全局变量
csrfAjax.ajax({
async:false,
url : `http://api.kwenyan.online:8080/email/${raw_email}/`,
type: 'GET',
contentType: 'application/json',
success: function (rst) {
if (rst != null){
Swal.showValidationMessage('此邮箱已存在!');
showValidataflag = false;
}
}
});
if (showValidataflag){
return raw_email;
}else{
return false;
}
},
allowOutsideClick: () => !Swal.isLoading()
}).then(function(rst){
console.log(rst);
if (rst.isConfirmed){
const Uid = $('#showID').data('user-id');
const updateURL = '/api/v1/userUpdateEmail/' + Uid + '/';
$.getJSON(updateURL, function(result){
result.email = rst.value;
result.url = '/api/v1/userUpdateEmail/';
csrfAjax.ajax({
url : updateURL,
type: 'POST',
contentType : 'application/json',
data : JSON.stringify(result),
success: function(e){
if (e.success){
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
didOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer);
toast.addEventListener('mouseleave', Swal.resumeTimer);
}
});
Toast.fire({
icon: 'success',
title: '发送成功,请在5分钟之内完成修改!'
})
}else{
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
didOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer);
toast.addEventListener('mouseleave', Swal.resumeTimer);
}
});
Toast.fire({
icon: 'info',
title: '你没有权限!'
})
}
}
})
})
}
})
})
这个 Api
请求使用的符号不是引号,是中文~
的英文状态.这个API
是公共API
,是可以放出去供大家使用的API
.不需要用户登录,也不用高级的权限分配`http://api.kwenyan.online:8080/email/${raw_email}/`
# api/v3 公共API
└── v3
├── commons.py
├── __init__.py# __init__.py
from flask import Blueprint
from flask_restful import Api
v3_bp = Blueprint('ap1_v3', __name__, subdomain='api')
v3_api = Api(v3_bp)
from .commons import ExistEmail
v3_api.add_resource(ExistEmail, '/email/<string:raw_email>/', endpoint='email')from flask_restful import Resource
from app.commons.sqlModel import User
from flask import jsonify
class ExistEmail(Resource):
def get(self, raw_email):
user = User.query.filter_by(email=raw_email).first()
if user is not None:
to_dict = {
'email': raw_email,
'exist':True
}
return jsonify(to_dict)
如果你使用的是 subdomain
,需要在hosts
中添加api.kwenyan.online
的指示.在 kwenyan.online
中访问api.kwenyan.online
涉及到跨域访问,可以使用插件“flask-cors`.# exts.py 初始化
from flask-cors import CORS
cors = CORS()# app/__init__.py
from exts import cors
def create_app():
cors.init_app(app, supports_credentials=True)
更改邮箱 API
,它的方法和注册类似,都是把唯一的token
包装并发送给邮箱.# api/v1/user.py
class User_update_email(Resource):
def get(self, id):
user = User.query.get_or_404(id)
if user is not None:
return jsonify(user.to_dict())
def post(self, id):
user = User.query.get_or_404(id)
if user is not None and request.json.get('email') and user.have_permission(request.json.get('url')):
# 生成邮箱token
token = user.generate_change_email_token(request.json.get('email'))
# 发送邮件
sendMail(user.email, '修改邮箱地址', 'changeEmail', user=user, token=token)
to_dict = {
'success': '发送邮件成功'
}
return jsonify(to_dict)
else:
to_dict = {
'error': '你没有权限'
}
return jsonify(to_dict)
sqlModel.py
,同样的,这里指示db.session.add()
,并没有直接提交数据.# -- 发送更改邮箱token
def generate_change_email_token(self, new_email, expiration=3600):
s = Serializer(current_app._get_current_object().config['SECRET_KEY'], expires_in=expiration)
return s.dumps({'id':self.id, 'new_email': new_email}).decode('utf-8')
def check_change_email_token(self, token):
s = Serializer(current_app._get_current_object().config['SECRET_KEY'])
try:
data = s.loads(token.encode('utf-8'))
except:
return False
new_email = data.get('new_email')
if data.get('id') != self.id:
return False
if new_email is None:
return False
# 判断重复
if self.query.filter_by(email=new_email).first() is not None:
return False
# 修改
self.email = new_email
db.session.add(self)
return True
邮件内容 <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>修改邮箱</title>
</head>
<body>
<p>您好,{{ user.username }}</p>
<p>点击<a href="{{ url_for('auth.change_email', token=token, _external=True) }}">修改邮箱</a>按钮修改.</p>
<p>您也可以双击以下连接激活账户:</p>
<p>{{ url_for('auth.change_email', token=token, _external=True) }}</p>
<p>如果不修改,请忽略此邮件.</p>
</body>
</html>
邮件中指向的路由, 在这里会执行 db.session.commit()
,并跳转登录.# 修改邮箱 token
@auth_bp.route('/change_email/<token>')
@login_required
def change_email(token):
if current_user.check_change_email_token(token):
db.session.commit()
flash("您的邮箱已经更改.")
else:
flash("链接已过期,请从新修改.")
return redirect(url_for('auth.auth_login'))
6.添加权限
有以上内容,还是不能修改的,因为没有权限,这就需要在后台中为
api/v1/userUpdateEmail/
添加到普通会员权限中.

– END –
原文始发于微信公众号(Flask学习笔记):Flask Todo项目:个人事项(4)
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/36342.html