【发布时间】:2019-05-18 03:11:41
【问题描述】:
我之前因另一个错误发布了此代码,但之后我收到了一个新错误,所以在新帖子中发布。
我有一个基本的 Flask 应用程序,它在数据库中记录用户代理字符串和用户本地时钟时间。我的模板文件(templates/home.html)如下:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type=text/javascript>
$(document).ready(function () {
console.log('Date Being Posted');
var clock = new Date();
console.log(JSON.stringify(clock));
$.ajax({
url:"/home",
clock: JSON.stringify(clock),
type:'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
</script>
</head>
<body>
<p>Your clock is being recorded on the loading of the webpage!</p>
{% for user in users %}
<p>{{user.clock}}</p>
{% endfor %}
</body>
</html>
而我的main.py如下:
import os
from flask import Flask
from flask import render_template
from flask import request
from sqlalchemy import exc
from flask_sqlalchemy import SQLAlchemy
project_dir = os.path.dirname(os.path.abspath(__file__))
#path to the database
database_file = "sqlite:///{}".format(os.path.join(project_dir, "userdatabase.db"))
app = Flask(__name__)
#indicate to the web application where the database will be stored
app.config["SQLALCHEMY_DATABASE_URI"] = database_file
#initialize a connection to the database; use the db variable to interact with the databse
db = SQLAlchemy(app)
##define a model for the user
class User(db.Model):
user_id = db.Column(db.Integer, primary_key=True)
user_agent = db.Column(db.String(1024), index=True)
clock = db.Column(db.String(1024), index=True)
def __repr__(self):
return "<User-Agent: {}, Clock: {}".format(self.user_agent, self.clock)
@app.route("/home", methods=["GET", "POST"])
def home():
if request.method == "POST":
user_agent_received = request.headers.get('User-Agent')
clock_received = request.json['clock']
user = User(user_agent=user-agent_received, clock=clock_received)
print (user)
try:
db.session.add(user)
db.session.commit()
except exc.IntegrityError as e:
db.session().rollback()
users = User.query.all()
return render_template("home.html", users=users)
if __name__ == "__main__":
app.run(debug=True)
我在这里:
a) 初始化数据库并为用户创建模型
b) 在home.html 中接收通过ajax 请求发布的时钟时间并将其存储在数据库中,同时将其发送到home.html 页面以进行显示。
数据库是在Python3 Interpretor 上单独创建的。
但是,在服务器上,我收到 500 Internal Server 错误。此错误显示在控制台上,而我尝试查看开发工具内部以找出原因。我不知道为什么会这样,有人可以帮忙吗?
【问题讨论】:
-
另外,在
user = User(user_agent=user-agent_received, clock=clock_received)中你犯了一个错误user-agent_received应该是user_agent_received。
标签: python-3.x flask flask-sqlalchemy