使用阿里云镜像仓库安装flask
pip install flask -i "http://mirrors.aliyun.com/pypi/simple" --trusted-host "mirrors.aliyun.com"
创建一个flask项目
from flask import Flask
#实例化一个Flask对象
app = Flask(__name__)
#路由
@app.route('/')
def hello_world():
return 'Hello Flask!'
if __name__ == '__main__':
#debug=True 开启Debug模式
#port=7000 设置端口号
#host='0.0.0.0' 监听所有网卡请求
app.run(debug=True,port=7000,host='0.0.0.0')
使用Bootstrap样式
#安装bootstrap-flask
pip install bootstrap-flask
from flask_bootstrap import Bootstrap5
#实例化一个Bootstrap5对象并关联flask
bootstrap = Bootstrap5(app=app)
#本地加载bootstrap,默认使用CDN加载bootstrap
app.config['BOOTSTRAP_SERVE_LOCAL'] = True
#在base.html中导入bootstrap
{{ bootstrap.load_css() }}
{{ bootstrap.load_js() }}
响应类型
#返回字符串,可以包含html标签
@app.route('/')
def hello_world():
return '<h1>Hello Flask!<h1/>'
#返回html页面
from flask import render_template
@app.route('/')
def hello_world():
return render_template('index.html')
#返回json
from flask import jsonify
@app.route('/')
def hello_world():
data = {'text':'Hello!'}
return jsonify(data)
#返回文件
from flask import send_file
@app.route('/')
def hello_world():
return send_file('filename')
接收参数
#path传参
@app.route('/data/<name>')
def hello_world(name):
return 'hello'+name
#get传参
from flask import request
#url = 127.0.0.1/?name=mek&aeg=10
@app.route('/')
def hello_world():
name = request.args.get('name')
aeg = request.args.get('aeg')
return name+aeg
#post传参
from flask import request
@app.route('/', methods=['GET', 'POST'])
def hello_world():
if request.method == 'POST':
name = request.from.get('name')
passwd = request.from.get('passwd')
return name
模板传参
from flask import render_template
@app.route('/')
def hello_world():
return render_template('index.html', name='Mek')
#index.html
#继承父模板
{% extends 'Base.html' %}
#使用对象
{{ name }}
#遍历
{% for i in name %}
{{ i }}
{% endfor %}
#if判断
{% if name == 'Mek' %}
<h1>OK<h1/>
{% endif %}
#调用对象属性
{{ name.aeg }}
钩子函数
#请求前需要做什么操作
@app.before_request
def before_request():
database.connect()
#请求完成后需要做什么操作
@app.after_request
def after_request(response):
database.close()
return response