在我的localhost上使用Flask和SQLAlchemy,我希望能够提交一个简单的联系表单,并使用AJAX将提交的数据传递给我的Flask API,然后将其插入我的本地数据库,名为{{1 }}
为了设置我的数据库,我整理了一个名为contact.db
的脚本,该脚本在我的工作目录中成功创建了一个数据库。其内容如下:
setup.py
我的简单联系页面收集数据并使用AJAX将其提交到我的烧瓶路线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)
(我已经通过控制台确认了这一点)。但是,作为参考,这里是我在/contact/request
中使用的代码:
contact.html
最后,我运行了我运行的实际Flask API脚本,以便在localhost上启动我的服务。 <!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>
路由正常。但是,当我通过表单提交发送数据时,我收到内部服务器错误。毫无疑问,这是由于我将解析后的JSON插入我的联系人数据库的错误尝试造成的。以下是我/contact
中使用的代码:
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()
替换它们,我的控制台成功返回我发送的JSON。我完全迷失了在将数据插入数据库时出错的原因以及为什么我的尝试向我抛出错误。
您可以给予我任何帮助,我将非常感激 - 希望这是一件简单的事情,我在对这件事情不熟悉时会被忽视。谢谢!
答案 0 :(得分:2)
在烧瓶中,你必须为你的路线返回一些东西,否则会导致奇怪的行为。在您的情况下,您可以返回一些简单的“OK”,让您的AJAX知道函数已成功完成。