簡體   English   中英

Flask / SQLAlchemy插入數據庫

[英]Flask/SQLAlchemy Insert Into Database

我希望在我的本地主機上使用Flask和SQLAlchemy,希望能夠提交一個簡單的聯系表單,並使用AJAX將提交的數據傳遞到我的Flask API中,然后將其插入到名為contact.db本地數據庫中。

為了設置數據庫,我編寫了一個名為setup.py的腳本,該腳本成功在工作目錄中創建了一個數據庫。 其內容如下:

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)

我的簡單聯系頁面會收集數據,並使用AJAX將其提交到我的燒瓶路徑/contact/request (我已經確認這可以通過控制台運行)。 作為參考,這是我在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>

最后,我運行了我的實際Flask API腳本,以便在本地主機上啟動服務。 /contact路由工作正常。 但是,當我通過表單提交發送數據時,出現內部服務器錯誤。 毫無疑問,這是由於我將解析后的JSON插入我的聯系人數據庫中的錯誤嘗試引起的。 以下是我的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()

如果我注釋掉這兩行:

session.add(new_contact)
session.commit()

並用return str(request.json)替換它們,我的控制台成功返回了我發送的JSON。 我完全迷失了將數據插入數據庫的過程中出錯的地方,以及為什么我的嘗試會向我拋出錯誤。

您能給我的任何幫助將不勝感激-希望這對我來說是新事物變得簡單,而我卻忽略了。 謝謝!

在燒瓶中,您必須為自己的路線返回一些東西,否則會導致異常行為。 在您的情況下,您可以返回一個簡單的“ OK”,讓您的AJAX知道該功能已成功完成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM