Flask入门
Flask是python的一个简单易用的web框架
用Flask很容易就写出一个简单的web应用
一个简单的例子
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
把代码保存到hello.py中,在命令行中输入以下命令
$ exportFLASK_APP=hello.py
$ flask run
* Running on http://127.0.0.1:5000/
好了,一个简单的helloworldweb应用就实现了,在浏览器输入
http://127.0.0.1:5000/,就会看到Hello, World!了
路由
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
def hello():
return 'Hello, World'
@app.route(‘/’)把下面的函数当作参数传入,当访问网页首页时,
就会调用index函数来处理,当访问/hello页面时,会调用hello函数
来处理,这样,我们就可以对每个url实现它的处理函数
HTTP方法
我们可以以不同的http方法访问同一个url,http方法有
GET,HEAD,POST,PUT,DELETE,OPTIONS.
from flask import request
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
do_the_login()
else:
show_the_login_form()
当我们用GET方法访问/login时,就会调用show_the_login_form(),
当我们用POST时,就会调用do_the_login()