简体   繁体   English

Flask / SQLAlchemy插入数据库

[英]Flask/SQLAlchemy Insert Into Database

Using Flask and SQLAlchemy on my localhost, I am looking to be able to submit a simple contact form and, using AJAX, pass the submitted data along to my Flask API and then insert it into my local database, named contact.db . 我希望在我的本地主机上使用Flask和SQLAlchemy,希望能够提交一个简单的联系表单,并使用AJAX将提交的数据传递到我的Flask API中,然后将其插入到名为contact.db本地数据库中。

To set up my database, I put together a script named setup.py , which successfully creates a database in my working directory. 为了设置数据库,我编写了一个名为setup.py的脚本,该脚本成功在工作目录中创建了一个数据库。 Its contents look as follows: 其内容如下:

from sqlalchemy import create_engine, ForeignKey
from sqlalchemy import Column, Date, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref

engine = create_engine('sqlite:///contact.db', echo=True)
Base = declarative_base()

########################################################################
class Contact(Base):
    """"""
    __tablename__ = "contact"

    id = Column(Integer, primary_key=True)
    f_name = Column(String)
    l_name = Column(String)
    email = Column(String)
    message = Column(String)

    #----------------------------------------------------------------------
    def __init__(self, f_name, l_name, email, message):
        """"""
        self.f_name = f_name
        self.l_name = l_name
        self.email = email
        self.message = message

# create tables
Base.metadata.create_all(engine)

My simple contact page collects the data and submits it to my flask route /contact/request using AJAX (I have confirmed this to work via the console). 我的简单联系页面会收集数据,并使用AJAX将其提交到我的烧瓶路径/contact/request (我已经确认这可以通过控制台运行)。 For reference, however, here is the code I use in contact.html : 作为参考,这是我在contact.html使用的代码:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Contact</title>

    <!-- Bootstrap -->
    <link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://code.jquery.com/jquery.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>




<script>
  $(document).ready(function(){
      $("#submitForm").click(function()
      {
        var firstName = $("#f_name").val();
        var lastName = $("#l_name").val();
        var email = $("#email").val();
        var mess = $("#mess").val();

        var nud = {
          "f_name" : firstName,
          "l_name" : lastName,
          "email" : email,
          "message" : mess
        }


        $.ajax({
          type: "POST",
          url: "/contact/request",
          data: JSON.stringify(nud, null, '\t'),
          contentType: 'application/json;charset=UTF-8',
          success: function(result) {
            console.log(result);
          }
        })
      });
  })
</script>



</head>
<body>
<div class="row">
  <div class="col-md-3"></div>
  <div class="col-md-6">
    <div class="panel panel-default">
      <div class="panel-heading">
        <h1 style="text-align: center">Contact Me</h1>
      </div>
      <div class="panel-body">
        <form role="form">
          <div class="form-horizontal" class="form-group" style="width:50%">
            <label for="name has-success">First Name</label>
            <input class="form-control input-md" type="text" class="form-control" id="f_name" placeholder="Matthew">
          </div><br />
          <div class="form-horizontal" class="form-group" style="width:50%">
            <label for="email">Last Name</label>
            <input class="form-control input-md" type="text" class="form-control" id="l_name" placeholder="Gross">
          </div><br />
           <div class="form-horizontal" class="form-group" style="width:50%">
            <label for="email">Email</label>
            <input class="form-control input-md" type="email" class="form-control" id="email" placeholder="mattkgross@gmail.com">
          </div><br />
          <div class="form-group">
            <label for="aboutMe">Message</label>
            <textarea class="form-control" id="mess" placeholder="What's up?" rows="3" ></textarea>
          </div>
          <div>
           <button type="button" input type "submit" class="btn btn-success" id="submitForm">Submit</button>
          </div>
        </form>
      </div>
    </div>
  </div>
  <div class="col-md-3"></div>
</div>
</body>
</html>

Finally, I have my actual Flask API script that I run in order to start up my service on localhost. 最后,我运行了我的实际Flask API脚本,以便在本地主机上启动服务。 The /contact route works fine. /contact路由工作正常。 However, when I send the data via my form submission, I get an internal server error. 但是,当我通过表单提交发送数据时,出现内部服务器错误。 This is undoubtedly being caused by my incorrect attempt at inserting the parsed JSON into my contact database. 毫无疑问,这是由于我将解析后的JSON插入我的联系人数据库中的错误尝试引起的。 Below is the code used in my api.py : 以下是我的api.py使用的代码:

from flask import Flask
from flask import request
from flask import render_template

import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from setup import Contact

app = Flask(__name__)

@app.route('/contact')
def contact():
    return render_template('contact.html')

@app.route('/contact/request', methods=["POST"])
def contact_request():
    if request.method == "POST":
        engine = create_engine('sqlite:///contact.db', echo=True)

        # Create a Session
        Session = sessionmaker(bind=engine)
        session = Session()

        new_contact = Contact(request.json['f_name'],
                              request.json['l_name'],
                              request.json['email'],
                              request.json['message'])

        # Add the record to the session object
        session.add(new_contact)
        # commit the record the database
        session.commit()

        #return str(request.json)

app.debug = True
app.run()

If I comment out the two lines: 如果我注释掉这两行:

session.add(new_contact)
session.commit()

and replace them with return str(request.json) , my console successfully returns the JSON I sent. 并用return str(request.json)替换它们,我的控制台成功返回了我发送的JSON。 I am just completely lost as to where I am going wrong in inserting my data into the database and why it is throwing an error at me for my attempt. 我完全迷失了将数据插入数据库的过程中出错的地方,以及为什么我的尝试会向我抛出错误。

Any help you can give me would be very much appreciated - hopefully it's something simple I overlooked in being new to this whole thing. 您能给我的任何帮助将不胜感激-希望这对我来说是新事物变得简单,而我却忽略了。 Thanks! 谢谢!

In flask you have to return something for your route otherwise it will lead to odd behavior. 在烧瓶中,您必须为自己的路线返回一些东西,否则会导致异常行为。 In your case you could return something as simple as an "OK" to let your AJAX know the function completed successfully. 在您的情况下,您可以返回一个简单的“ OK”,让您的AJAX知道该功能已成功完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM