这两天在研究flask和antd,想把这俩个东西结合来使用,单独学antd的时候用的是dva来配置,但是发现这样与flask结合的话需要启动两个服务,作为flask只是作为数据的接口,并没用用到其强大的模板渲染功能,所以最后还是想能本地化antd,把它当做只是一个ui组件库来用的话可能就能实现了。下面是具体的流程。
在上一篇中写到了将antd本地化,在此基础上我们就可以用antd表单组件渲染一个登录页面,再将其放在flask的templates中。模板login.html:
欢迎登录!
Login.js是整个登录表单的渲染代码,在最后包含了表单的验证,其实主要就是把官网上的代码拿来用就行,只要在用到antd(大写开头的标签)组件的时候加上(antd.):
var FormItem = antd.Form.Item;var Login = React.createClass({ getInitialState: function() { return { username: "", userpass:"", namevalidateStatus:"", passvalidateStatus:"", lastvalidateStatus:"", nameHelp:"", passHelp:"", lastHelp:"" }; }, handleUsernameChange: function (event) { this.setState({ username: event.target.value }); }, handleUserpassChange: function (event) { this.setState({ userpass: event.target.value }); }, handleSubmit: function(event) { if(this.state.username == ''){ this.setState({ namevalidateStatus: 'error', nameHelp:'请输入用户名!' }); } else if(this.state.userpass == ''){ this.setState({ passvalidateStatus: 'error', passHelp:'请输入密码!' }); } else{ var obj = this; //提交表单数据到后端验证 $.post("/loginAction",{ username:this.state.username, userpass:this.state.userpass }, function(data,status){ var returnData = JSON.parse(data); if(returnData.infostatus=='T'){ obj.setState({ lastvalidateStatus:"success", lastHelp:returnData.infomsg }); location.href="/antd"; } else { obj.setState({ userpass: '', namevalidateStatus:"", passvalidateStatus:"", lastvalidateStatus:"error", nameHelp:"", passHelp:"", lastHelp:returnData.infomsg }); } }); } event.preventDefault(); }, render: function() { return (); }});ReactDOM.render( 欢迎登录
} placeholder="Username" /> } type="password" placeholder="Password" /> 记住我 忘记密码登录 注册, document.getElementById('loginBox'));
这样模板就渲染好了,通过mian.py中加载出模板,包括登录的处理:
# -*- coding:utf-8 -*-from flask import Flask, render_template, session, redirect, url_for, escape, requestfrom dpl import gradefrom dpl import userfrom dpl import userLogin# from dpl import selected_gradeimport jsonapp = Flask(__name__)@app.route('/login')def login(): return render_template('login.html')@app.route('/loginAction',methods=['GET', 'POST'])def login_action(): user_pass = request.form.get('userpass') user_name = request.form.get('username') print('username',user_name) print('user_pass',user_pass) result = userLogin.UserLogin.select_user(user_name,user_pass) if request.method == 'POST': if result['infostatus']=='T': session['username'] = user_name return json.dumps(result) else: return json.dumps(result)@app.route('/antd')def test_antd(): # session.pop('username',None) name = 0 if 'username' in session: name = session['username'] return render_template('antd.html',username=name)@app.route('/userlist')def get_user(): userlist = user.get_user() return json.dumps(userlist)@app.route('/backLogin')def back_login(): session.pop('username',0) return redirect('/login')# for sessionapp.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'if __name__ == '__main__': app.run(host='0.0.0.0',port=8001,debug=True)
实现登录在Login.js中有代码,后端返回数据成功以后直接跳转到登录以后的页面即可。