flask

https://www.cnblogs.com/wupeiqi/articles/7552008.html
from flask import Flask, render_template, request

app = Flask(__name__)


@app.route('/')
def hello_world():
s = "hello world"
return render_template('hello.html', s=s) #给html传参 也可以将传参写入一个字典, data={"a":"1","b":"2"} return render_template('hello.html',**data)


@app.route('/login')
def login():
return render_template('login.html')


@app.route('/check', methods=['POST'])
def check():
usrname = request.form.get('username')
pwd = request.form.get('pwd')
return usrname,pwd


if __name__ == '__main__':
app.run(debug=True)


login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<form action="/check" method="post">
用户名: <input type="text" name="username">
密码: <input type="text" name="pwd">
<input type="submit" value="提交">
</form>

</body>
</html>

=======================================

1.配置文件
2.路由
1.添加路由的两种方式:
@app.route('/index',methods=['post','get']) (装饰器,如果要添加新的装饰器
,一定要放在这个装饰器之后,保证建立url对应,不然会执行不成功)
def index():
return "xxx"
等价于==
def index():
return "xxx"
app.add_url_rule('/index',view_func=index)
2.反向生成url:url_for
不起别名,默认的是函数名
@app.route('/index',endpoint='别名')
def index():
bieming = url_for("别名")
3.自定义路由转换器--p10
@app.route('/index/<index_name>') #可以传入字符串,int,float,path
4.其他参数
重定向
5.重点:
-url
-methods
-endpoint
-@app.route('/index/<int:nid>')
-url_for

3.视图
4.请求和响应
request.xxx
5.模板
局部定义函数 在函数内部写
全局定义函数 加一个装饰器
@app.template_global()
def add(a1,a2)
return a1+a2
直接在html文件中调用该方法 <h1> {{add(1,2)}} </h1>
6.session
流程:1.请求刚刚到达的时候
ctx =

7.特殊的装饰器
@app.before_request 执行前执行 在代码中有多个该装饰器,按顺序执行
@app.after_request 执行后执行 相当于创建了一个列表,将带有装饰器的方法从上至下append到list中,然后做一个翻转(reversed)
所以执行顺序是从后往前的,跟before相反
@app.before_first_request 只执行一次
8.闪现
数据只查看一次
10.中间件
app.run() --> 执行过程 1.执行app.__call__方法 2.再调用app.wsgi_app方法


如果一个方法可以 key['name']='jack' 它的类里面一定是有 __setitem__ 方法,或者继承了dict类

posted @ 2020-12-22 22:08  聪明的大嘴花  阅读(91)  评论(0编辑  收藏  举报