无法将烧瓶数据发送到数据库

时间:2018-07-16 11:25:39

标签: python flask flask-sqlalchemy

如何将烧瓶数据发送到数据库。我创建了 .html表单,但是无法执行连接。所有功能都写在app.py中。

.html代码:

<div id="registration">
<h2 style = "text-align: center;">Registration Form</h2>
    <form class="website form-horizontal container-fluid mt32" action=" " method="post">
        <div class="col-md-3 col-sm-4 text-right" style="padding:1%;">
          <label class="control-label" for="name"> Your Name*</label>
        </div>
        <div class="col-md-7 col-sm-8" style="padding:1%;">
          <input class="form-control o_website_form_input" name="username" required="True" autocorrect="off" type="text"/>
        </div>

        <div class="col-md-3 col-sm-4 text-right" style="padding:1%;">
          <label class="control-label" for="email_from">Your Email*</label>
        </div>
        <div class="col-md-7 col-sm-8" style="padding:1%;">
          <input class="form-control o_website_form_input" name="email" required="True" autocorrect="off" type="email"/>
        </div>
    </form>
</div>

如何使用mysql,SQLAlchemy等提供连接性

1 个答案:

答案 0 :(得分:1)

您需要使用route方法创建一个POST,以便可以将html表单中的数据发布到其中。

@app.route('/add_post', methods=['POST'])
def add_post():
    # get the form from request and add it to db

它是可选的,但最好使用wtformsFlask-WTF)来形成表格。它会以一种易于阅读且更安全的方式处理表单创建。

然后,您需要使用sqlalchemy甚至更简单,更好的flask-sqlalchemy扩展名。创建类型为class的{​​{1}}(如果使用裸Model,则创建Base)。此类将表示数据库中的表。

sqlalchemy

然后,您可以向数据库添加帖子,例如:

class Post(db.Model):
    __tablename__ = 'posts'
    id = db.Column(db.Integer, primary_key= True)
    title = db.Column(db.String(120)

,您可以使用以下查询数据库:

post = Post(title="my post title")
db.session.add(post)
db.session.commit()

posts = Post.query.all() sqlalchemy会将您连接到诸如flask-sqlalchemymysqlpostgresql等引擎。

您可以阅读有关如何执行所有这些操作的框架文档。