Python基础知识总结六:Web开发之Flask

常见的Python Web框架

  • Flask:一个轻量级Web应用框架。
  • Django:一个全能型Web框架。
  • Tornado:Facebook的开源异步Web框架。
  • web.py:一个小巧的Web框架。
  • web2py:Google在web.py基础上二次开发而来的。
  • Bottle:Bottle和Flask都属于轻量级的Web框架。

Flask是一个使用 Python 编写的轻量级 Web 应用框架。Flask 依赖着两个外部库:Jinja2 模板引擎以及 Werkzeug WSGI 工具集。

一个简单的使用Flask的例子:

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
28
29
30
from flask import Flask
from flask import request

app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def home():
return '<h1>Home</h1>'


@app.route('/signin', methods=['GET'])
def signin_form():
return '''<form action="/signin" method="post">
<p><input name="username"></p>
<p><input name="password" type="password"></p>
<p><button type="submit">Sign In</button></p>
</form>'''



@app.route('/signin', methods=['POST'])
def signin():
# 需要从request对象读取表单内容:
if request.form['username'] == 'admin' and request.form['password'] == 'password':
return '<h3>Hello, admin!</h3>'
return '<h3>Bad username or password.</h3>'


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

一个使用Flask开发的MVC模式的例子:

项目结构

  • app.py
  • templates
    • home.html
    • form.html
    • result.html

app.py

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
28
from flask import Flask, request, render_template

app = Flask(__name__)


# Flask通过render_template()函数来实现模板的渲染。

@app.route('/', methods=['GET', 'POST'])
def home():
return render_template('home.html')


@app.route('/signin', methods=['GET'])
def signin_form():
return render_template('form.html')


@app.route('/signin', methods=['POST'])
def signin():
username = request.form['username']
password = request.form['password']
if username == 'admin' and password == 'password':
return render_template('result.html', username=username)
return render_template('form.html', message='Bad username or password', username=username)


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

home.html

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<h1 style="font-style:italic">Home</h1>
</body>
</html>

form.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Please Sign In</title>
</head>
<body>
{% if message %}
<p style="color:red">{{ message }}</p>
{% endif %}
<form action="/signin" method="post">
<legend>Please sign in:</legend>
<p><input name="username" placeholder="Username" value="{{ username }}"></p>
<p><input name="password" placeholder="Password" type="password"></p>
<p>
<button type="submit">Sign In</button>
</p>
</form>
</body>
</html>

result.html

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome, {{ username }}</title>
</head>
<body>
<p>Welcome, {{ username }}!</p>
</body>
</html>

八宝粥 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!