1. Flask的简单使用
import flask
app = flask.Flask(__name__) # 初始化Flask对象
@app.route("/") # 装饰器装饰flask方法
def hello():
return '你好,我是flask'
if __name__ == "__main__":
app.run() # 启动web服务器
2. 同一个方法可同时使用多个装饰器
"""
import flask
app = flask.Flask(__name__)
@app.route("/") # 装饰器1
@app.route("/hello") # 装饰器2
def hello():
return "你好,我是Flask!"
if __name__ == "__main__":
app.run()
装饰器1的访问结果:
装饰器2的访问结果:
控制台显示:
3. 接收并返回GET数据和POST数据
import flask
html_txt = """
<!DOCTYPE html>
<html>
<body>
<h2>收到GET请求</h2>
<form method="post">
<input type="submit" value="发送POST请求" />
</form>
</body>
</html>
"""
app = flask.Flask(__name__)
@app.route("/hello", methods=['GET', 'POST'])
def hello():
if flask.request.method == 'GET':
return html_txt
else:
return '收到POST请求,我是Flask'
if __name__ == "__main__":
app.run()
接收get方法传来的数据
点击”发送POST请求”按钮,接收post方法传来的数据。
控制台显示:
4. 获取url的参数(即获得get方法的参数)
import flask
app = flask.Flask(__name__)
@app.route('/hello/<name>')
def helo(name):
return "你好," + name + "!"
if __name__ == "__main__":
app.run()
5. 获得POST方法传入的参数
import flask
html_txt = """
<!DOCTYPE html>
<html>
<body>
<h2>收到GET请求</h2>
<form method="post">
<input type="text" name="name" placeholder="请输入你的姓名" />
<input type="submit" value="发送POST请求" />
</form>
</body>
</html>
"""
app = flask.Flask(__name__)
@app.route('/hello', methods=['GET', 'POST'])
def hello():
if flask.request.method == 'GET':
return html_txt
else:
name = 'name' in flask.request.form and flask.request.form['name']
print(type(name))
if name:
return '你是:' + name + '!'
else:
return '你没有输入姓名!'
if __name__ == "__main__":
app.run(debug=True)
输入:lvche
不输入,则结果如下: