flask代码知识点

flask代码的小知识:

HTML5中的新元素标签

<a href="{{ url_for('.services') }}">services</a>

其中 .services中的点的意思是对python当前的python包的相对路径,最终就会输出指向services这个路径的url
render_template 函数是用来渲染的

下面是flask最简单的路由定义方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template('index.html', title='World!')
@app.route('/services/')
def services():
return 'Services'
@app.route('/about')
def about():
return 'About'
if __name__ == '__main__':
app.run(debug=True)

/services//about的区别:
/services/表示的是services文件夹下的一个默认文件,假如没有打最后的斜杠,它也会自动重定向添加上斜杠
/about表示的是about文件,如果在输入时在about的后面多加一个斜杠,将会出现404.(这些操作是在浏览器的地址栏里执行)

在templates文件夹下创建一个名为index.html的文件:

</html><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <div style="color:Aqua"><h1>{{ title }}</h1></div>   #定义title字体的颜色
<nav>
    <a href="{{ url_for('.services') }}">services</a>
    <a href="{{ url_for('.about') }}">about</a>
</nav>
</body>

最简单的定义路由的方式:

1
2
3
@app.route('/user/<username>')
def user(username):
return 'User %s' % username

要向浏览器中输入/user/name
<username>变量

定义传参的类型:(int-整型 float-浮点数 path-路径)

1
2
3
@app.route('/user/<int:user_id>')
def user(user_id):
return 'User %d' % user_id

文章目录