flask 入门

1.安装 flask

pip3 install flask

2.代码:

import flask

app = flask.Flask(__name__)

@app.route('/')
def testABC():
    return '你好,我是Flask!'

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

可以在浏览器上看到效果:

C8FF8E8F-0803-42EB-8B48-2F27BB7C0BCF

3.其他链接

19B3B8A5-7470-47AC-95F1-3D26643659DE

4.修改代码

import flask

app = flask.Flask(__name__)

@app.route('/')
@app.route('/test')
def testABC():
    return '你好,我是Flask!'

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

6FB7B79C-EE34-46C4-9652-D1FAE4E43333

其他链接维持 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()

DEEA3DE3-DC59-446A-8A40-43DCD3CCF934

8E4F6897-89CF-4504-AB95-5A4273489974

6.URL 的参数

import flask

app = flask.Flask(__name__)

@app.route('/test/<name>')
def testABC(name):
    return "你好," + name + "!"

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

F30F52AC-A351-4584-8FFE-B2D2BA748BE2

45829216-F182-4D0D-A006-CB034331BD7D

8A5A7AC3-6522-4AED-953F-6E59D3

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()

09212F37-5827-4E63-8D58-18595CDD7154

BF88ABC0-BE98-4B3F-9764-086A67923F95

E94BEDD8-27AB-46BF-A99D-A1B8915B7735

路由的设置

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()

589D009B-7545-432C-B3E8-872DE1EF7860

AF1D0EFE-4EF2-4C18-BCBC-78BF43A4B2E3