flask 入门
1.安装 flask
pip3 install flask
2.代码:
import flask
app = flask.Flask(__name__)
@app.route('/')
def testABC():
return '你好,我是Flask!'
if __name__ == '__main__':
app.run()
可以在浏览器上看到效果:
3.其他链接
4.修改代码
import flask
app = flask.Flask(__name__)
@app.route('/')
@app.route('/test')
def testABC():
return '你好,我是Flask!'
if __name__ == '__main__':
app.run()
其他链接维持 Not Found 的页面。
5.简单的GET、POST
import flask
html_text = """
<!DOCTYPE HTML>
<html>
<body>
<h2>收到GET请求</h2>
<form method='post'>
<input type='submit' value='发送 POST 请求' />
</form>
</body>
</html>
"""
app = flask.Flask(__name__)
@app.route('/test', methods=['GET','POST'])
def testABC():
if flask.request.method == 'GET':
return html_text
else:
return '收到 POST 请求,我是Flask!'
if __name__ == '__main__':
app.run()
6.URL 的参数
import flask
app = flask.Flask(__name__)
@app.route('/test/<name>')
def testABC(name):
return "你好," + name + "!"
if __name__ == '__main__':
app.run()
GET 与 POST 请求的参数传递
import flask
html_text = """
<!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('/test', methods=['GET','POST'])
def testABC():
if flask.request.method == 'GET':
return html_text
else:
name = 'name' in flask.request.form and flask.request.form['name']
if name:
return '你是:' + name + '!'
else:
return "你没有输入姓名!"
if __name__ == '__main__':
app.run()
路由的设置
import flask
app = flask.Flask(__name__)
@app.route('/')
def testABC():
return '你好,我是Flask!'
@app.route('/hello')
def testHello():
return 'Hello World!'
if __name__ == '__main__':
app.run()