• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Flask框架如何使用表单

python 搞java代码 1个月前 (05-24) 3次浏览 已收录 0个评论

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

<!DOCTYPE html><html><head>
    <title></title></head><body>
    <h1>Bio Data Form</h1>
    <form action="showbio">
        <label>Username</label>
        <input type="name" name="username"><br>
        <label>Email</label>
        <input type="email" name="email"><br>
        <label>Hobbies</label>
        <input type="name" name="hobbies"><br>
        <input type="submit" name="">
    </form></body></html>

www#gaodaima.com来源gao@[email protected]!网搞代码

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

@app.route('/form', methods=['POST', 'GET'])def bio_data_form():    
    if request.method == "POST":
        username = request.form['username']        
        age = request.form['age']        
        email = request.form['email']        
        hobbies = request.form['hobbies']        
        return redirect(url_for('showbio',                              
                                username=username,
                                age=age,
                                email=email,   
                                hobbies=hobbies))    
    return render_template("bio_form.html")

相关推荐:《Python相关教程》

下面是showbio的实现:

@app.route('/showbio', methods=['GET'])
def showbio():    
    username = request.args.get('username')    
    age = request.args.get('age')    
    email = request.args.get('email')    
    hobbies = request.args.get('hobbies')    
    return render_template("show_bio.html",
                           username=username,                         
                           age=age,                          
                           email=email,                         
                           hobbies=hobbies)

以及show_bio.html的内容:

<!DOCTYPE html><html><head>
    <title>Bio-Data Details</title></head><body>
    <h1>Bio-Data Details</h1>
    <hr>
    <h1>Username: {{ username }}</h1>
    <h1>Email: {{ email }}</h1>
    <h1>Hobbies: {{ hobbies }}</h1></body></html>

相关推荐:

Flask框架如何使用HTML模板

来源:搞代码网:原文地址:https://www.gaodaima.com


喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址