Python Web Servers

Web Servers

Flask是Python 用来打造网页应用的一个库.Facebook和Google都是网页应用的例子.

Flask的使用方法,从flask中导入Flask:

1
from flask import Flask

导入Flask之后,就可以创建一个Flask app.

1
2
from flask import Flask
app = Flask(__name__)

这个变量__name __ 是用来说明,这个应用是主应用还是其他程序的应用.

我们用app.route()来决定用什么来触发一个函数,这里,我们用一个URL来触发这个函数.

1
2
3
4
5
from flask import Flask
app = Flask(__name__)
# '/' indicates the default URL of the app
@app.route('/')
#put a function here

举例

定义一个hello_world的方法:

1
2
3
4
5
6
7
8
9
10
from flask import Flask
app = Flask(__name__)
# '/' indicates the default URL of the app
@app.route('/')
#put a function here
def hello_world():
return 'Hello,world!'
if __name__ == "__main__":
app.run()

不同的URLs返回不同页面:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from flask import Flask
app = Flask(__name__)
# '/' indicates the default URL of the app
#http://127.0.0.1:5000/
@app.route('/')
#put a function here
def home():
return 'Home Page'
@app.route('/about')
#put a function here
def about():
return 'About Us'
if __name__ == "__main__":
app.run()

打开网址,如图:

home_page

在网址后加上about,如图:

about

在URLs后面添加变量

1
2
3
4
@app.route('/user/<username>')
#put a function here
def show_user_profile(username):
return 'User %s' % username

打开网址,输入变量:

user

加上其他变量:

1
2
3
4
5
6
@app.route('/post/<int:post_id>')
def show_post(post_id):
return 'Post %d' % post_id
@app.route('/example/<float:ex>')
@app.route('/example/<any:ex>')

真诚地希望能帮到你!