这两天在研究flask和antd,想把这俩个东西结合来使用,单独学antd的时候用的是dva来配置,但是发现这样与flask结合的话需要启动两个服务,作为flask只是作为数据的接口,并没用用到其强大的模板渲染功能,所以最后还是想能本地化antd,把它当做只是一个ui组件库来用的话可能就能实现了。下面是具体的流程。
在上一篇中写到了将antd本地化,在此基础上我们就可以用antd表单组件渲染一个登录页面,再将其放在flask的templates中。模板login.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>欢迎登录!</title>
<script src="/static/react/react.min.js"></script>
<script src="/static/react/react-dom.min.js"></script>
<script src="/static/react/browser.min.js"></script>
<script src="/static/antd/dist/antd.js"></script>
<link href="/static/antd/dist/antd.css" rel="stylesheet"/>
<link href="/static/css/login.css" rel="stylesheet"/>
<script src="/static/js/pagetools/jquery-1.11.3.min.js"></script>
</head>
<body>
<div id="loginBox"></div>
<script type="text/babel" src="/static/components/Login.js"> </script>
</body>
</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 (
<antd.Form onSubmit={this.handleSubmit} className="login-form">
<h1>欢迎登录</h1>
<FormItem validateStatus={this.state.namevalidateStatus} help={this.state.nameHelp}>
<antd.Input className="username" value={this.state.username} onChange={this.handleUsernameChange} prefix={<antd.Icon type="user" style={{ fontSize: 13 }} />} placeholder="Username" />
</FormItem>
<FormItem validateStatus={this.state.passvalidateStatus} help={this.state.passHelp}>
<antd.Input className="userpass" value={this.state.userpass} onChange={this.handleUserpassChange} prefix={<antd.Icon type="lock" style={{ fontSize: 13 }} />} type="password" placeholder="Password" />
</FormItem>
<FormItem validateStatus={this.state.lastvalidateStatus} help={this.state.lastHelp}>
<antd.Checkbox>记住我</antd.Checkbox>
<a className="login-form-forgot">忘记密码</a>
<antd.Button type="primary" htmlType="submit" className="login-form-button">
登录
</antd.Button>
<a>注册</a>
</FormItem>
</antd.Form>
);
}
}); ReactDOM.render(<Login />, document.getElementById('loginBox'));
这样模板就渲染好了,通过mian.py中加载出模板,包括登录的处理:
# -*- coding:utf-8 -*-
from flask import Flask, render_template, session, redirect, url_for, escape, request
from dpl import grade
from dpl import user
from dpl import userLogin
# from dpl import selected_grade
import json
app = 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 session
app.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中有代码,后端返回数据成功以后直接跳转到登录以后的页面即可。