theKingOfNight's Blog

Flask学习笔记

字数统计: 2.2k阅读时长: 12 min
2019/02/01 Share

python Flask逐渐变的流行,有必要学习一哈,这里给予我浅显的一点讲解,如果理解不到位的地方,希望各位师傅斧正,感激不尽。


环境准备

1
sudo apt install python-pip
1
sudo pip3 install flask

1
2
mkdir flask
cd flask/

开始

hello-world.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/usr/bin/env python3
"""Out first Flask Application"""
from flask import Flask
app = Flask("__name__") #这里以接受包或者模块为参数,一般传递__name__
#这里定义了变量app赋值为Flask()
@app.route('/') #这里相当于定义了一个路由,具体访问一下本地就知道了
def index(): #路由的函数就是紧接着定义的函数
return "Hello World!" #访问http://127.0.0.1:5000/(默认端口)界面返回Hello World!
@app.route('/say_hello')
def say_hello():
return "Hello You are so Good!" #访问http://127.0.0.1:5000/say_hello界面返回Hello You are so Good!
if (__name__=="__main__"):
app.run() #端口可以修改app.run(host='0.0.0.0',port=8000)

一个非常简单的flask网页就已经搭建成功,直接运行该python程序

1
2
3
4
5
6
7
8
9
10
┌─[thekingofnight@parrot]─[~/flask]
└──╼ $chmod +x hello-world.py
┌─[thekingofnight@parrot]─[~/flask]
└──╼ $sudo ./hello-world.py
* Serving Flask app "__name__" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

当然也可以这样,效果是一样的

1
2
3
4
┌─[thekingofnight@parrot]─[~/flask]
└──╼ $FLASK_APP=hello-world.py flask run
* Serving Flask app "hello-world"
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

这里可以看到一些信息,并且可以看到Debug模式是关闭的,端口开放。
直接访问就好。
另外用户访问的信息都会显示在终端。

1
2
3
4
127.0.0.1 - - [28/Sep/2018 11:40:39] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [28/Sep/2018 11:40:41] "GET /aaa HTTP/1.1" 404 -
127.0.0.1 - - [28/Sep/2018 11:40:55] "GET /%60 HTTP/1.1" 404 -
127.0.0.1 - - [28/Sep/2018 11:40:59] "GET /_ HTTP/1.1" 404 -

直接访问 http://127.0.0.1:5000/ 就可以看到简单的页面。

Debug Mode

这里Debug模式可以开启,直接修改

1
2
if (__name__=="__main__"):
app.run(debug=True)

1
2
3
4
5
6
7
8
9
10
11
┌─[thekingofnight@parrot]─[~/flask]
└──╼ $./hello-world.py
* Serving Flask app "__name__" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 298-xxx-xx1

开启debug模式,可以看到这里会返回我们的pin码,18年安恒杯8月赛题目好像有一道
关于计算PIN码的,有兴趣的师傅们可以去看看。
所以将flask框架制作完成的产品放制到公网上时,千万不要开启Debug模式

简单的拓展

1
2
3
4
5
6
7
@app.route('/say_hello/<name>') #如果这里有可选参数,则需要注意下方需要定义一个函数来处理参数
def say_hello_to_someone(name):
return "Hello %s!"%name
------------------------------------------------------------------------------------------
然后访问http://127.0.0.1:5000/say_hello/theKingOfNight
界面返回Hello theKingOfNight!
------------------------------------------------------------------------------------------

这里添加的参数支持4种类型

1
2
3
4
5
string (default) accepts any text without a slash
int accepts positive integers
float accepts positive floating point values
path like string but also accepts slashes
uuid accepts UUID strings


Templates简介

在python中直接可以返回相应的html代码,例如

1
2
3
@app.route('/')
def index():
return "<h1>Hello World!</h1>"

但是代码会显示的稍微复杂一些,这里就需要用到Templates.

1
2
3
4
┌─[thekingofnight@parrot]─[~/flask]
└──╼ $mkdir templates
┌─[thekingofnight@parrot]─[~/flask]
└──╼ $vi templates/base_page.html

写入以下内容

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html>
<html>
<head>
<title>Test Flask</title>
<meta charset="utf-8">
</head>
<body>
<p>Hello World!</p>
</body>
</html>

修改hello-world.py为

1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/env python3
"""Out first Flask Application"""
from flask import Flask,render_template
app = Flask("__name__")
@app.route('/')
def index():
return render_template('base_page.html')
if (__name__=="__main__"):
app.run(debug=True)

访问 view-source:http://127.0.0.1:5000/

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html>
<head>
<title>Test Flask</title>
<meta charset="utf-8">
</head>
<body>
<p>Hello World!</p>
</body>
</html>

简单的扩展

案例一

hello-world.py

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/env python3
"""Out first Flask Application"""
from flask import Flask,render_template
app = Flask("__name__")
@app.route('/<name>')
def hello(name):
return render_template('base_page.html',name=name)
if (__name__=="__main__"):
app.run(debug=True)

/templates/base_page.html

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html>
<html>
<head>
<title>Test Flask</title>
<meta charset="utf-8">
</head>
<body>
<p>Hello {{name}}!</p>
</body>
</html>

访问 http://127.0.0.1:5000/theKingOfNight 即可显示出 Hello theKingOfNight!

案例二

hello-world.py

1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/env python3
"""Out first Flask Application"""
from flask import Flask,render_template
app = Flask("__name__")
@app.route('/<name>')
def hello(name):
return render_template('base_page.html',name=name)
if (__name__=="__main__"):
app.run(debug=False)

/templates/base_page.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html>
<head>
<title>Test Flask</title>
<meta charset="utf-8">
</head>
<body>
<p>
{% if name %}
Hello {{name}}!
{% else %}
Hello World!
{% endif %}
</p>
</body>
</html>

访问 http://127.0.0.1:5000/theKingOfNight

可以同样输出 Hello theKingOfNight!

案例三

hello-world.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/env python3
"""Out first Flask Application"""
from flask import Flask,render_template
app = Flask("__name__")
@app.route('/')
@app.route('/<name>')
def hello(name=None):
return render_template('base_page.html',name=name)
if (__name__=="__main__"):
app.run(debug=True)

/templates/base_page.html同上

访问 http://127.0.0.1:5000/ 即可输出 Hello World!
访问 http://127.0.0.1:5000/theKingOfNight 输出Hello theKingOfNight!

案例四 (继承)

hello-world.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/env python3
"""Out first Flask Application"""
from flask import Flask,render_template
app = Flask("__name__")
@app.route('/')
@app.route('/<name>')
def hello(name=None):
return render_template('home.html',name=name)
if (__name__=="__main__"):
app.run(debug=True)

/templates/base_page.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html>
<head>
<title>Test Flask</title>
<meta charset="utf-8">
</head>
<body>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Contact</a></li>
<li><a href="#">About</a></li>
</ul>
</nav>
<p>
{% block content %}{% endblock %}
</p>
</body>
</html>

/templates/home.html

1
2
3
4
5
6
7
{% extends "base_page.html" %}
{% block content%}
<h1>Welcome to my Blog.</h1>
<p>
This is home page.
</p>
{% endblock %}

访问 http://127.0.0.1:5000/ 即可得到如下效果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
<head>
<title>Test Flask</title>
<meta charset="utf-8">
</head>
<body>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Contact</a></li>
<li><a href="#">About</a></li>
</ul>
</nav>
<p>
<h1>Welcome to my Blog.</h1>
<p>
This is home page.
</p>
</p>
</body>
</html>

静态文件的加载

这里直接给出案例

1
2
3
4
5
6
7
8
9
┌─[thekingofnight@parrot]─[~/flask]
└──╼ $mkdir static
┌─[thekingofnight@parrot]─[~/flask]
└──╼ $cd static/
┌─[thekingofnight@parrot]─[~/flask/static]
└──╼ $mkdir img css font
┌─[thekingofnight@parrot]─[~/flask/static]
└──╼ $ls
css font img

hello-world.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/env python3
"""Out first Flask Application"""
from flask import Flask,render_template
app = Flask("__name__")
@app.route('/')
@app.route('/<name>')
def hello(name=None):
return render_template('home.html',name=name)
if (__name__=="__main__"):
app.run(debug=True)

/templates/base_page.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html>
<head>
<title>Test Flask</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='css/stylesheet.css')}}">
</head>
<body>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Contact</a></li>
<li><a href="#">About</a></li>
</ul>
</nav>
<p>
{% block content %}{% endblock %}
</p>
</body>
</html>

/templates/home.html

1
2
3
4
5
6
7
8
{% extends "base_page.html" %}
{% block content%}
<h1>Welcome to my Blog.</h1>
<p>
This is home page.
</p>
<img src="{{url_for('static',filename='img/test.png')}}">
{% endblock %}

/static/css/stylesheet.css

1
2
3
4
5
6
7
8
9
html{
width: 600px;
margin: 0 auto;
}
body{
border-left: 1px solid silver;
border-right: 1px solid silver;
}

访问 view-source:http://127.0.0.1:5000/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html>
<head>
<title>Test Flask</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="/static/css/stylesheet.css">
</head>
<body>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Contact</a></li>
<li><a href="#">About</a></li>
</ul>
</nav>
<p>
<h1>Welcome to my Blog.</h1>
<p>
This is home page.
</p>
<img src="/static/img/test.png">
</p>
</body>
</html>

参考

http://flask.pocoo.org/docs/1.0/*

https://www.youtube.com/watch?v=bNSz29Iqpxc&list=PL1H1sBF1VAKVtrhim9EDG7vFarkbo4V0C

CATALOG
  1. 1. 环境准备
  2. 2. 开始
  3. 3. Debug Mode
  4. 4. 简单的拓展
  5. 5. Templates简介
    1. 5.1. 简单的扩展
      1. 5.1.1. 案例一
      2. 5.1.2. 案例二
      3. 5.1.3. 案例三
      4. 5.1.4. 案例四 (继承)
  6. 6. 静态文件的加载
  7. 7. 参考