1. 程式人生 > 其它 >flask頁面的get與post請求

flask頁面的get與post請求

get請求

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首頁</title>
</head>
<body>
<h1>歡迎來到京東購物網站</h1>
<div>
    <ul>
        <li>hello</li>
        <li>abc</li>
        <li>world</li>
    </ul>
    <form action="/register1" method="get">
        <p><input type="text" name='username' placeholder="請輸入使用者名稱"></p>
        <p><input type="text" name='address' placeholder="請輸入地址"></p>
        <P><input type="submit" value="提交"></P>
    </form>

</div>
</body>
</html>

flask解析get請求

from flask import Flask
import setting

app = Flask(__name__)
app.config.from_object(setting)
@app.route('/register')
def register():

    return render_template('index.html')

@app.route('/register1')
def register1():
    #如果請求是get,需要用request.args來取值
    print(request.args.get('username'))
    print(request.args.get(
'address')) return '進來了' if __name__ == '__main__': print(app.url_map) app.run(host='127.0.0.1', port=5000)

結果

post請求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首頁</title>
</head>
<body>
<h1>歡迎來到京東購物網站</h1>
<div>
    <ul>
        <li>hello</li>
        <li>abc</li>
        <li>world</li>
    </ul>
    <form action="/register1" method="post">
        <p><input type="text" name='username' placeholder="請輸入使用者名稱"></p>
        <p><input type="text" name='address' placeholder="請輸入地址"></p>
        <P><input type="submit" value="提交"></P>
    </form>

</div>
</body>
</html>

flask解析post請求

from flask import Flask
import setting

app = Flask(__name__)
app.config.from_object(setting)
@app.route('/register')
def register():

    return render_template('index.html')

@app.route('/register1',methods =['get','post'])
def register1():
#如果請求是post,則需要用request.form取值
print(request.form.get('username'))
print(request.form.get('address'))
return '進來了'


if __name__ == '__main__':
print(app.url_map)
app.run(host='127.0.0.1', port=5000)

結果: