0 前言
轻量级后端框架
学习内容:
- flask路由 用来匹配url
- request对象 abort函数
- 模板
- flask数据库 使用插件
- 表单 (账号密码提交等操作)
- ajax
- 管理系统小案例
1 最简单的应用-helloworld
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run()
2 什么是路由
url网址与flask的路由是映射关系。
01 固定路由
仅有url参数
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/12/7 上午11:00
# @Author : hqc
# @File : helloworld_flask.py
# @Software: PyCharm
from flask import Flask # 导入包
app = Flask(__name__) # 实例化
@app.route('/') # 关于route()里面可以写url,提交的方式。 / 代表根目录
def hello():
return "hello world"
@app.route('/flask') # 本机IP+暴露端口+/flask 可以访问到
def flask():
return "hello flask"
if __name__ == '__main__':
app.run(host='172.27.196.77',port=5001,debug=True)
# 172.27.196.77 is localhost
# if there is no specific ip , default to 127.0.0.1:5000
# but this code cant be ask from other machine,because the machine's IP is not right
加入method参数
GET和POST
GET:接受请求
POST:表单操作可能会用到
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/12/7 上午11:00
# @Author : hqc
# @File : helloworld_flask.py
# @Software: PyCharm
from flask import Flask
app = Flask(__name__)
@app.route('/',methods=['GET','POST']) # 关于route()里面可以写url,提交的方式
def hello():
return "hello world"
@app.route('/flask',methods=['POST']) # 不含'GET'参数
def flask():
return "hello flask"
if __name__ == '__main__':
app.run(host='172.27.196.77',port=5001,debug=True)
# 172.27.196.77 is localhost
# if there is no specific ip , default to 127.0.0.1:5000
# but this code cant be ask from other machine,because the machine's IP is not right
hello()函数仍可以正常访问
但是flask()函数不允许request,因为没有’GET’参数。
02 变量路由
from flask import Flask
app = Flask(__name__)
@app.route('/hqc/<number>') # <>包含的为变量名
def count(number):
if number == '1' :
return 'python'
if number == str(2) :
return 'flask'
if int(number) == 3 : # 要保证是字符串数据类型
return 'python + flask'
return 'hello world' # 若前面都不生效,则输出helloworld
if __name__ == '__main__':
app.run()
转换数据类型
事先限定数据类型就不用每个都进行转换
from flask import Flask
app = Flask(__name__)
@app.route('/hqc/<float:number>') # <>包含的为变量名
def count(number):
if number == 1.1 :
return 'python'
if number == 2.1 :
return 'flask'
if number == 3.1 :
return 'python + flask'
return 'hello world' # 若前面都不生效,则输出helloworld
if __name__ == '__main__':
app.run()
转换器规则:
string:接受所有不包含斜杠的字符
int: 接受正整数
float: 接受正浮点数
path: 能接受所有包含斜杠的字符
3 前端表单
表单属于前端(html),要如何和后端交互起来呢?
01 创建templates (python package)
右键新建包,与创建目录的操作不同的是:新建包会自动产生一个init.py
的文件
虽然,咱也不知道有沙用。
02 创建html表单文件
03 编写表单文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Calculator</title>
</head>
<body>
<div align="center" style="margin-top:30px">
<form method="POST" name = "form1">
<input type="text" name = "left" placeholder = "left"/>+
<input type="text" name = "right" placeholder = "right"/>=
<input type="text" name = "result" placeholder = "result" readonly="readonly" value = "{{ RESULT }}"/>
<input type="submit" value = "submit"/>
</form>
</div>
</body>
</html>
04 copy path 先查看一下是否成功
粘贴到浏览器中进行访问:
成功!
05 编写python程序与表单进行关联
from flask import Flask
from flask import render_template
from flask import url_for
from flask import request
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == "POST":
a = request.form['left']
b = request.form['right']
c = int(a) + int(b)
return render_template('index.html', RESULT = str(c))
return render_template('index.html')
if __name__ == "__main__":
app.run(port = 8881)
from flask import render_template
导入的render_template
包用来渲染html页面
06 设置jinja2模板
由于时pycharm是社区版,不是专业版,没有这个功能,因此不设置了。
07 运行python程序
可见,可以在
http://127.0.0.1:8881/
进行访问
输入11+24按下enter键可计算得到35。
4 后端接收前端输入的数据(request)
- 前端输入的数据一般可通过两种方式进行传输:
GET
和POST
- 后端进行接收时首先要判断前端是那种传输方式
就拿之前表单操作中的代码来看,也进行了判断
5 重定向(redirect)
01 重定向到特定网址,比如百度
from flask import Flask,redirect
app = Flask(__name__)
@app.route('/index')
def index():
return redirect('https://www.baidu.com/')
if __name__ == '__main__':
app.run()
注意:网址得写全,前面加上https://
02 重定向到自己定义的函数
from flask import Flask,redirect,url_for
app = Flask(__name__)
@app.route('/index')
def index():
return redirect(url_for('question'))
@app.route('/')
def question():
return redirect('https://www.zhihu.com/')
# return 'https://www.zhihu.com/'
if __name__ == '__main__':
app.run()
双重重定向:index()通过url_for 重定向至question(),question()再重定向至知乎官网
6 flask返回数据给前端
可以用JSON格式、XML格式、文本格式、html格式。但相比XML的重量、规范繁琐,JSON显得非常小巧和易用。
from flask import Flask
# from flask import make_response # import a package used to return data to front-end
# from flask import json # need to use json data
from flask import jsonify
app = Flask(__name__)
@app.route('/')
def index():
data = {'name':'郭泓'} # define a dictionary
# return make_response(data) # input data
return jsonify(data)
if __name__ == '__main__':
app.run()
不需要像教程里一样,考虑中文转换的问题(可能时flask改进了?)
右键->检查->网络
7 abort函数
使用abort函数可以立即终止视图函数的执行,并可以返回给前端特定的信息。在网页中抛出异常。
补充知识:raise函数:主动抛出异常
from flask import Flask,request,render_template,abort
app = Flask(__name__)
@app.route('/index',methods=['GET','POST'])
def index():
if request.method == 'GET' : # 'GET' means get data from the front-end
return render_template('index.html') # if 'request.method' is "GET" , associate template-'index.html'.
if request.method == 'POST': # 'POST' I understand this as: export information to front-end
number1 = request.form.get('left') # get the value of the first number box
number2 = request.form.get('right') # get the value of the second number box
if number1 == '1' and number2 == '1':
return 'plus success' # judge, if it is '1+1',if true ,return 'plus success'
else:
abort(404) # else,return 404 error
return None
if __name__ == '__main__':
app.run()
else:
8 自定义错误
01 自定义错误信息表头
from flask import Flask,request,render_template,abort
app = Flask(__name__)
@app.route('/index',methods=['GET','POST'])
def index():
if request.method == 'GET' : # 'GET' means get data from the front-end
return render_template('index.html') # if 'request.method' is "GET" , associate template-'index.html'.
if request.method == 'POST': # 'POST' I understand this as: export information to front-end
number1 = request.form.get('left') # get the value of the first number box
number2 = request.form.get('right') # get the value of the second number box
if number1 == '1' and number2 == '1':
return 'plus success' # judge, if it is '1+1',if true ,return 'plus success'
else:
abort(403) # else,return 403 error
return None
@app.errorhandler(403)
def handle_404_error_info(err):
return '出现了403错误,错误信息:%s'%err
if __name__ == '__main__':
app.run()
02 自定义错误信息返回404图片
.py文件:
from flask import Flask,request,render_template,abort
app = Flask(__name__)
@app.route('/index',methods=['GET','POST'])
def index():
if request.method == 'GET' : # 'GET' means get data from the front-end
return render_template('index.html') # if 'request.method' is "GET" , associate template-'index.html'.
if request.method == 'POST': # 'POST' I understand this as: export information to front-end
number1 = request.form.get('left') # get the value of the first number box
number2 = request.form.get('right') # get the value of the second number box
if number1 == '1' and number2 == '1':
return 'plus success' # judge, if it is '1+1',if true ,return 'plus success'
else:
abort(404) # else,return 404 error
return None
# @app.errorhandler(403)
# def handle_403_error_info(err):
# return '出现了404错误,错误信息:%s'%err
@app.errorhandler(404)
def handle_404_error_pic(err):
return render_template('error404.html')
if __name__ == '__main__':
app.run()
error404.html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>error404</title>
</head>
<body>
<img src="/static/error404.jpeg" width="1080px" height="720px">
</body>
</html>
**注意:**图片须放到新建的static文件夹中
当不符合条件时,返回错误界面:
9 使用变量
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/index')
def index():
list = [1,2,3,4,5,6]
return render_template('index.html',list = list)
if __name__ == '__main__':
app.run()
变量list也可换成dictionary
简单的html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>plus in [1 2 3 4 5 6]</title>
</head>
<body>
list is :{{list}}
<br>
<br>
{{list[1]}}+{{list[2]}} = {{list[1]+list[2]}}
</body>
</html>
注意:html中采用的是{{}}
双大括号来引用变量
展示了两数相加的功能。