Flask实战第46天:完成前台登录功能
Posted sellsa
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flask实战第46天:完成前台登录功能相关的知识,希望对你有一定的参考价值。
后台逻辑
首先进行表单验证, 编辑front.froms.py
... class SignInForm(BaseForm): telephone = StringField(validators=[Regexp(r‘1[35678]d{9}‘, message=‘手机号码格式错误‘)]) password = StringField(validators=[Length(5, 30, message=‘密码格式错误‘)]) remember = StringField()
在config.py中配置一个用作保存前台session的常量
FRONT_USER_ID = ‘WFQQ132FEVFW‘
然后写视图了,编辑front.view.py
... import config from .forms import SignInForm class SignInViews(views.MethodView): def get(self): return_to = request.referrer if return_to and return_to != request.url and safeutils.is_safe_url(return_to): return render_template(‘front/front_signin.html‘, return_to=return_to) return render_template(‘front/front_signin.html‘) def post(self): signin_form = SignInForm(request.form) if signin_form.validate(): telephone = signin_form.telephone.data password = signin_form.password.data remember = signin_form.remember.data user = FrontUser.query.filter_by(telephone=telephone).first() if user and user.check_password(password): session[config.FRONT_USER_ID] = user.id if remember: session.permanent = True return xjson.json_success(‘登录成功‘) else: return xjson.json_param_error(‘手机号或密码错误‘) else: return xjson.json_param_error(signin_form.get_error()) bp.add_url_rule(‘/signin/‘, view_func=SignInViews.as_view(‘signin‘))
前端逻辑
在static/front/js下新建个js文件front_signin.js(获取注册按钮,配置它的点击事件)
$(function(){ $("#submit-btn").click(function (event) { event.preventDefault(); var telephone_input = $("input[name=‘telephone‘]"); var password_input = $("input[name=‘password‘]"); var remember_input = $("input[name=‘remember‘]"); var telephone = telephone_input.val(); var password = password_input.val(); var remember = remember_input.checked ? 1 : 0; //如果有选择返回1否则返回0 bbsajax.post({ ‘url‘: ‘/signin/‘, ‘data‘: { ‘telephone‘: telephone, ‘password‘: password, ‘remember‘: remember }, ‘success‘: function (data) { if(data[‘code‘] == 200){ var return_to = $("#return-to-span").text(); if(return_to){ window.location = return_to; }else{ window.location = ‘/‘; } }else{ xtalert.alertInfo(data[‘message‘]); } } }); }); });
把front_signin.js引入到front_signin.html中
{% block head %} <script src="{{ url_for(‘static‘, filename=‘front/js/front_signin.js‘) }}"></script> {% endblock %}
把front_signbase中的front_signup.js引入去掉,在front_signup.html中引入它
{% block head %} <script src="{{ url_for(‘static‘, filename=‘front/js/front_signup.js‘) }}"></script> {% endblock %}
以上是关于Flask实战第46天:完成前台登录功能的主要内容,如果未能解决你的问题,请参考以下文章