1. 简单的启动文件
flask_app.py
from flask import Flask, render_template, request, redirect, session
app = Flask( __name__)
app.secret_key = 'ashfjuyruiqwhmndmzdfkifofi' #使用session时候用的加密key
app.debug = True
#登录入口,支持get,post请求
@app.route('/login', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
return render_template("login.html")
user = request.form.get("user")
passwrd = request.form.get("passwrd")
print("request.form = ", request.form)
print("user = ", user)
print("passwrd = ", passwrd)
if user == '11' and passwrd == 'ii':
session['user_info'] = user
return redirect('/index')
else:
# return render_template('login.html', **{'msg': '用户名或密码错误'})
return render_template('login.html',msg='用户名或密码错误')
#登录后的index页面入口
@app.route('/index', methods=['GET', 'POST'])
def index_func():
if session.get('user_info'):
return '欢迎登录'
else:
return redirect('/login')
#退出登录
@app.route('/logout', methods=['GET', 'POST'])
def logout():
del session['user_info']
return redirect('login')
#启动flask server入口
if __name__ == "__main__":
app.run()
templates文件夹下的login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试登录</title>
</head>
<body>
<form method="post" >
用户名<input name="user" type="text" />
密码<input name="passwrd" type="password" />
<input id="submit" type="submit" value="提交" />
</form>
</body>
</html>
2. 配置文件写法:
settings.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 配置写法参考 https://www.cnblogs.com/wupeiqi/articles/7552008.html
class BaseConfig(object):
DEBUG = False
TESTING = False
DATABSE_URI = "sqlite://memory"
class ProductionConfig(BaseConfig):
DATABSE_URI = "mysql://user@localhost/foo"
class DevelopmentConfig(BaseConfig):
DEBUG = True
DATABSE_URI = "mysql://user@dev/foo"
class TestingConfig(BaseConfig):
TESTING = True
DATABSE_URI = "mysql://user@test/foo"
配置使用:
from flask import Flask, render_template, request, redirect, session
app = Flask( __name__)
app.config.from_object("settings.DevelopmentConfig")
@app.route('/login', methods=['GET', 'POST'])
def index():
return render_template('login.html')
if __name__ == "__main__":
app.run()
3. 添加路由的两种方式:
from flask import Flask, render_template, request, redirect, session
app = Flask( __name__)
'''
1. 执行decorator=app.route('/index', methods=['GET', 'POST'])
2. @执行decorator
-decorator(index)
'''
# 添加路由的方式一: (一般都是用这种)
@app.route('/index', methods=['GET', 'POST'])
def index():
return 'Index'
# 添加路由的方式二: (不常用)
def order():
return "Order"
app.add_url_rule('/order', view_func=order())
if __name__ == "__main__":
app.run()
3. 路由带参数,(也可以自定义转换器,匹配参数类型)
#index/后面写数字,会自动传到nid参数里去
@app.route('/index/<int:nid>', methods=['GET', 'POST'])
def index(nid):
print("nid = ", nid)
return 'Index'
参考博客: