每个web应用都需要使用表单来采集用户数据。现在让我们使用Flask框架创建一个简单的表单来收集用户的基本信息,例如名称、年龄、邮件、兴趣爱好等,我们将这个模板文件命名为bio_form.html

    1. <!DOCTYPE html><html>
    2. <head>
    3. <title></title>
    4. </head>
    5. <body>
    6. <h1>Bio Data Form</h1>
    7. <form action="showbio">
    8. <label>Username</label>
    9. <input type="name" name="username"><br>
    10. <label>Email</label>
    11. <input type="email" name="email"><br>
    12. <label>Hobbies</label>
    13. <input type="name" name="hobbies"><br>
    14. <input type="submit" name="">
    15. </form>
    16. </body>
    17. </html>

    以及show_bio.html的内容:

    1. <!DOCTYPE html><html>
    2. <head>
    3. <title>Bio-Data Details</title>
    4. </head>
    5. <body>
    6. <h1>Bio-Data Details</h1>
    7. <hr>
    8. <h1>Username: {{ username }}</h1>
    9. <h1>Email: {{ email }}</h1>
    10. <h1>Hobbies: {{ hobbies }}</h1>
    11. </body>
    12. </html>

    源码文件如下:

    1. from flask import Flask, request, redirect, url_for, render_template
    2. app = Flask(__name__)
    3. @app.route('/form', methods=['POST', 'GET'])
    4. def bio_data_form():
    5. if request.method == "POST":
    6. username = request.form['username']
    7. age = request.form['age']
    8. email = request.form['email']
    9. hobbies = request.form['hobbies']
    10. return redirect(url_for('showbio',
    11. username=username,
    12. age=age,
    13. email=email,
    14. hobbies=hobbies))
    15. return render_template("bio_form.html")
    16. @app.route('/showbio', methods=['GET'])
    17. def showbio():
    18. username = request.args.get('username')
    19. age = request.args.get('age')
    20. email = request.args.get('email')
    21. hobbies = request.args.get('hobbies')
    22. return render_template("show_bio.html",
    23. username=username,
    24. age=age,
    25. email=email,
    26. hobbies=hobbies)
    27. if __name__ == "__main__":
    28. app.run(debug=True, port=8080

    视图函数bio_data_form同时支持POST和GET请求。GET请求将渲染bio_form.html模板,而POST请求将重定向到showbio

    web访问表单页面如下:

    Untitled.gif