说明
最近的项目需要用到flask,貌似3年前用过,不过很久没搞了
以前java web比较熟。这里做个简单的入门记录
官网:
http://docs.jinkan.org/docs/flask/
下载与安装
pip install flask
建议用virtualenv
一个例子
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
例子2
带参数
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % username
@app.route('/post/<int:post_id>')
def show_post(post_id):
# show the post with the given id, the id is an integer
return 'Post %d' % post_id
访问:
http://127.0.0.1:5000/post/122
http://127.0.0.1:5000/user/jjjjj
一个简易登陆逻辑
三个文件 :
效果示意:
index.html
<!DOCTYPE html>
<!-- saved from url=(0022)https://i.huanqiu.com/ -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>
首页
</title>
</head>
<body>
<div class="publicHeader">
<div class="header">
<span class="pageTitle"><b>
{% if uname %}
<a href="/logout">登出</a>
{% else %}
<a href="/login_page">登陆</a>
{% endif %}
</b></span>
</div>
</div>
<div class="loginWarp">
{% if uname %}
<h1>Hello {{ uname }}!</h1>
{% else %}
<h1>你没有登陆,请先登陆!</h1>
{% endif %}
</div>
<div class="publicFooter">
<div class="footer">
</div>
<div class="copyright">这是首页</div>
</div>
</body>
</html>
login.html
<!DOCTYPE html>
<!-- saved from url=(0022)https://i.huanqiu.com/ -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>
登录
</title>
</head>
<body>
<div class="publicHeader">
<div class="header">
<span class="pageTitle"><b>
登录
</b></span>
<span class="loginBar">
</span>
</div>
</div>
<div class="loginWarp">
<div class="loginMain">
<div class="login">
<form method="post" action="/login">
<span class="title">用户登录</span>
<em class="loginError"></em>
<span class="userEmail"><input type="text" name="uname" value="dgm" style="ime-mode:disabled;"
placeholder="unmae"></span>
<span class="userPassword"><input type="password" name="pwd" value="123456" placeholder="pwd"></span>
<span class="loginBtn">
<input type="submit" value="登 录" name="submit">
</span>
</form>
</div>
</div>
</div>
<div class="publicFooter">
<div class="footer">
</div>
<div class="copyright">这是登陆页</div>
</div>
</body>
</html>
app.py
from flask import Flask, escape, request, session, redirect, url_for,render_template
app = Flask(__name__)
app.secret_key = "123456"
@app.route('/')
def hello_world():
return redirect(url_for('index'))
@app.route('/index')
def index():
if 'uname' in session:
uname = session['uname']
return render_template('index.html', uname=uname)
else:
return render_template('index.html')
@app.route('/login_page')
def login_page():
return render_template('login.html')
@app.route('/logout')
def logout():
session.clear()
return redirect(url_for('index'))
@app.route('/login', methods=['GET', 'POST'])
def login():
# 判空
if (not 'uname' in request.form) or not ( 'pwd' in request.form):
errmsg = "uname and pwd can not be null"
print(errmsg)
return errmsg
uname = request.form['uname']
pwd = request.form['pwd']
# 判断 method
if request.method == 'POST':
print("yes,post")
else:
errmsg = "no,method is wrong," + request.method
print(errmsg)
return errmsg
if uname == 'dgm' and pwd == '123456':
# 放到session中
# 这一行可能 会抛,The session is unavailable because no secret ,需要增加 app.secret_key = "123456" 这样的配置
session['uname'] = uname
return redirect(url_for('index'))
else:
return "wrong uname or pwd"
if __name__ == '__main__':
# app.run()
app.run(debug=True)
app.py的说明
@app.route(’/’) 进首页跳到index
@app.route(’/index’) 为首页, session中有用户则显示 用户,无用户则提示用户登陆
@app.route(’/login_page’) 进登陆界面
@app.route(’/logout’) 登出请求,把session给清空
@app.route(’/login’, methods=[‘GET’, ‘POST’]) 登陆提交,成功则进index
filter或拦截器之类
可以用
before_request,after_request
如:
@app.before_request
def print_request_info():
print("请求地址:" + str(request.path))
print("请求方法:" + str(request.method))
print("---请求headers--start--")
print(str(request.headers).rstrip())
print("---请求headers--end----")
print("GET参数:" + str(request.args))
print("POST参数:" + str(request.form))
每次请求都会打印 上面的内容
把路由的内容分到多个文件
我们现在是把 route都加到了app.js,如果 业务变得很多这个内容就会很大,不好维护,所以我们需要多个文件来拆分,使用flask的 blueprint 模块
我们还是用之前的逻辑,
但尝试把 下面三个请求 扔到 auth.js中,
@app.route(’/login_page’)
@app.route(’/logout’)
@app.route(’/login’, methods=[‘GET’, ‘POST’])
[外链图片转存失败(img-25mITl06-1568452641771)(en-resource://database/3157:0)]
auth.py :
from flask import Flask, escape, request, session, redirect, url_for,render_template,Blueprint
mod = Blueprint('auth',__name__)
@mod.route('/login_page')
def login_page():
return render_template('login.html')
@mod.route('/logout')
def logout():
session.clear()
return redirect(url_for('index'))
@mod.route('/login', methods=['GET', 'POST'])
def login():
# 判空
if (not 'uname' in request.form) or not ( 'pwd' in request.form):
errmsg = "uname and pwd can not be null"
print(errmsg)
return errmsg
uname = request.form['uname']
pwd = request.form['pwd']
# 判断 method
if request.method == 'POST':
print("yes,post")
else:
errmsg = "no,method is wrong," + request.method
print(errmsg)
return errmsg
if uname == 'dgm' and pwd == '123456':
# 放到session中
# 这一行可能 会抛,The session is unavailable because no secret ,需要增加 app.secret_key = "123456" 这样的配置
session['uname'] = uname
return redirect(url_for('index'))
else:
return "wrong uname or pwd"
app.py 有变化:
from flask import Flask, escape, request, session, redirect, url_for,render_template
from views import auth
app = Flask(__name__)
app.secret_key = "123456"
app.register_blueprint(auth.mod,url_prefix='/')
@app.route('/')
def hello_world():
return redirect(url_for('index'))
@app.route('/index')
def index():
if 'uname' in session:
uname = session['uname']
return render_template('index.html', uname=uname)
else:
return render_template('index.html')
if __name__ == '__main__':
# app.run()
app.run(debug=True)
留意上面的 app.register_blueprint(auth.mod,url_prefix=’/’),即把其它模块的 路由加上.
其它不变.