轻量级框架 后端框架

  • flask路由用来匹配url
  • request对象
  • 模板
  • flask数据库
  • 表单

​pip install flask -i https://pypi.douban.com ​

from flask import Flask
# 实例化
app = Flask(__name__)
# 装饰器
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
app.run()

__name__指的是当前文件
两种路由请求,get请求和post请求

@app.route("/hi",methods=['GET','POST'])
def hello_world():
return "<p>Hello, World!</p>"

flask路由-变量规则
127.0.0.1:5000/user/1

@app.route("/user/<id>")
def index(id):
if id == 1:
return 'python'
return "<p>Hello, World!</p>"

string接受任何不包含斜杠的文本
int接受正整数
float接受正浮点数
path接受包含斜杠的文本

@app.route("/user/<int:id>")
def index(id):
if id == 1:
return 'python'
return "<p>Hello, World!</p>"

自定义转换器
{‘re’,RegexConverter}

from werkzeug.routing import BaseConverter
from flask import Flask
app = Flask(__name__)
class RegexConverter(BaseConverter):
def __init__(self,url_map,regex):
#调用父类方法
super(RegexConverter, self).__init__(url_map)
self.regex = regex
def to_python(self, value):
#父类的方法功能已经实现好了
print('to_python方法被调用')
return value
# 将自定义的转换器类添加到flask应用中
app.url_map.converters['re'] = RegexConverter
@app.route('/index/<re("123"):value>')
def index(value):
print(value)
return 'hello'
if __name__ == '__main__':
app.run()

重定向到自己路由(函数)中

from flask import  Flask,redirect,url_for
app = Flask(__name__)
@app.route('/index')
def index():
return redirect(url_for('hello'))
@app.route('/')
def hello():
return 'nb'
if __name__ == '__main__':
app.run()

返回json数据给前端

from flask import  Flask,make_response,json,jsonify
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
@app.route('/index')
def index():
data = {
'name': 'zhangsan'
}
# response = make_response(json.dumps(data,ensure_ascii=False))
# response.mimetype = 'application/json'
# return response
return jsonify(data,)
if __name__ == '__main__':
app.run()

abort函数

from flask import Flask,abort,request,render_template
app = Flask(__name__)
@app.route('/index',methods=['GET','POST'])
def index():
if request.method == 'GET':
return render_template('index.html')
if request.method =='POST':
name = request.form.get('name')
password = request.form.get('password')
if name == 'zhangsan' and password == '123':
return 'login success'
else:
abort(404)
return None
return '123'
if __name__ == '__main__':
app.run()

自定义异常

from flask import Flask,abort,request,render_template
app = Flask(__name__)
@app.route('/index',methods=['GET','POST'])
def index():
if request.method == 'GET':
return render_template('index.html')
if request.method =='POST':
name = request.form.get('name')
password = request.form.get('password')
if name == 'zhangsan' and password == '123':
return 'login success'
else:
abort(404)
return None
#自定义错误处理方法
@app.errorhandler(404)
def handle_404_error(err):
return '出现了404错误 错误信息是%s'%err
if __name__ == '__main__':
app.run()

自定义过滤器

flask快速上手_后端


定义表单模型类