flask库

flask库

flask是python编写的轻量级框架,提供Werkzeug(WSGI工具集)和jinjia2(渲染模板)两个依赖库。

flask返回的html一定要放在python项目的templates文件夹里。

1. 基本使用

pip install flask

./templates/register.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Register</title>
</head>
<body>
    <h1>Register</h1>
    <form action="/register" method="post">
        <div>
            <label for="username">Username:</label>
            <input type="text" id="username" name="username" required>
        </div>
        <div>
            <label for="password">Password:</label>
            <input type="password" id="password" name="password" required>
        </div>
        <div>
            <input type="submit" value="Submit">
        </div>
    </form>
</body>
</html>

./main.py

from flask import Flask,url_for,request,render_template,make_response,redirect,jsonify,json

app = Flask(__name__)  # 用本脚本名实例化Flask对象

@app.route('/',methods=['GET','POST'])#url配置
def index():#视图函数
    #return 'hello world' 响应给浏览器的内容
    return redirect('/register')#重定向

@app.route('/register',methods=['GET','POST'])
def register():
    if request.method=='POST':
        print(request.form.get('username'),request.form.get('password'))
    return render_template('register.html')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9901, debug=1)

2. 路由路径和路由参数

from werkzeug.routing import BaseConverter

@app.route('/') #localhost:port/
def index():
    return 'hello world'

@app.route('/index1/') #localhost:port/index1/
def index1():
    return 'index1'

#命名路径也可以声明类型,比如<string:name>
#支持类型 string,int,float,path,uuid,any,default
@app.route('/index2/<name>') #命名路径 #localhost:port/index2/Tom
def index2(name):
    return name #Tom

class RegexConverter(BaseConverter):
    #1. 自定义正则转换器类
    def __init__(self,map,*args): #args=转换器的参数
        self.map=map
        self.regex=args[0]  # BaseConberter中的属性regex

# 2.注册转换器(字典添加键值)
app.url_map.converters['regex']=RegexConverter

@app.route("/index3/<regex('\d{2}'):age>/")
def index3(age):
    return age

@app.route() 用于装饰一个视图函数,函数返回需要在用户浏览器中显示的信息(默认html)。

返回值为字符类型或者是字典

路由参数如下

1. 位置参数
/index 
/index/<name> #动态路由参数,可接受字符串和数字类型
/index/<int:id> #指定变量类型
    
2. methods=['GET','POST']
	#当前视图函数支持的请求方式(默认GET)

3. endpoint=''
	# 路由映射函数,给url起名,依然绑定正下方函数。
	# 不指定默认起名为视图函数名(view_func.__name__)
    # 存储视图函数的view_funcs是以{endpoint:view_func}形式存储,因此视图函数不能同名

3. defaults={key:value}
	#默认参数设置,必须再视图函数中定义一个形参来接收。

4. redirect_to=''
	#永久重定向(301或308)

5. strict_slashes=True/False
	# 设置路由路径匹配是否为严格模式,默认不设置为严格路由匹配模式。
    # 严格模式,路由后面原本没/,加上就会报错

3. 请求跳转和请求参数

./templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <h1>Login</h1>
    <form action="{{url_for('index5')}}" method="get">
        <div>
            <label for="username">Username:</label>
            <input type="text" id="username" name="username" required>
        </div>
        <div>
            <label for="password">Password:</label>
            <input type="password" id="password" name="password" required>
        </div>
        <div>
            <input type="submit" value="Submit">
        </div>
    </form>
</body>
</html>

main.py

@app.route('/') #localhost:port/
def index():
    return render_template('index.html')
# 转发模板,渲染模板文件

@app.route('/index4')
def index4():
    url=url_for('index')# '/' 
    #url_for('视图函数名'),返回视图函数对应url
    return redirect(url) #重定向

@app.route('/index5')
def index5():
    u=request.args.get('username')
    p=request.args.get('password')
    # request是全局对象
    # get请求用args.get()
    # post请求用form.get()
    print(u,p)
    return '请求成功'

在这里插入图片描述

4. 模板渲染

​ 模板是一个包含响应文本的文件,其中用占位符(模板变量{{name}})表示动态部分内容,告诉模板引擎具体的值要从具体的数据中获取,用真实值替换变量,再返回最终得到的字符串,这个过程称为‘渲染’。flask使用jinjia2模板引擎渲染模板。

1. 模板变量

在视图(view)中,模板变量向模板中传递数据,动态生成页面内容。

@app.route('/index6')
def index6():
    return render_template('test.html',a=123,b=[4,5,6])

./templates/test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
</head>
<body>
    <p>{{a}}</p>
    <p>{{b}}</p>
    {{ config.__class__.__init__.__globals__['os'].listdir('.') }}
</body>
</html>
2. 过滤器
{{ name|upper }}
{{ name|lower }}
{{ name|length }}
{{ name|trim }}
{{ name|default('name不存在') }}
{{ name|default('name为None,0,false,""',true) }}
3. 测试器

if…elif…else…endif

for…endfor

{% if m is defined %}
	{{m}}
{% else %}
    999
{% endif %}

{% for i in range(10) %}
	{{i}}
{% endfor %}

5. 钩子函数与响应对象

Hook(钩子),是一种过滤(或叫挂钩)消息的技术。Hook的目的是过滤一些关键函数调用,在函数执行前,先执行自己的挂钩函数,达到监控函数调用,改变函数功能的目的。

Hook技术按照实现原理来分的话可以分为两种:

  • API HOOK:拦截Windows API;

  • 消息HOOK:拦截Windows消息。

Flask装饰器注册钩子函数说明
@app.before_request在每一次请求前调用,先绑定先执行,先flask app后blueprint
@app.before_first_request只在第一次请求之前调用(似乎没有这个)
@app.after_request每一次请求之后都会调用,接收response对象,执行完后记得归还,先绑定的后执行
@app.teardown_request每次请求之后都会调用,先绑定的后执行

在这里插入图片描述

@app.before_request
def first():
    print("Nice to meet you!")

@app.route('/') #localhost:port/
def index():
    data = {
        'name': '张三'
    }
    # json.dumps 将一个python数据结构转化为json
    # json.dumps 序列化时对中文默认使用的ascii编码.想输出真正的中文需要指定ensure_ascii=False
    # 生成一个response响应对象,而不是直接return来返回响应对象,便于执行更多的后续操作
    response = make_response(json.dumps(data, ensure_ascii=False))
    # 修改响应数据的MIME标准类型为json(在发送数据前会先发送该类型)
    response.mimetype = 'application/json'
    response.status = '200'  # 状态码
    response.headers['name'] = 'success!'
    return response

@app.errorhandler(404)
def page_not_found(e):
    return '页面没找到'

if __name__ == '__main__':
    print(app.url_map)# 查看所有的路由信息
    app.run(host='0.0.0.0', port=9901, debug=1)

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值