【发布时间】:2019-10-23 10:47:05
【问题描述】:
背景和问题
当用户使用 Flask 在 Web 应用程序上正确和错误地输入表单时,我正在尝试实现消息闪烁功能。
当我执行以下程序时,成功从表单向数据库插入数据。
但是,调用消息闪烁失败,没有错误消息。单击“创建”按钮后仅显示插入的数据,并且在我当前的程序上没有消息闪烁。
我应该如何修复我的程序?
官方文档
阅读the official document of Flask Message Flashing!,我不确定我应该如何为我的程序使用密钥。
程序
执行
$ FLASK_APP=app.py FLASK_DEBUG=true flask run
app.py
from flask import Flask, flash, render_template, request, redirect, url_for, abort, jsonify
from flask_sqlalchemy import SQLAlchemy
import sys
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://username@localhost:5432/sample'
db = SQLAlchemy(app)
class Todo(db.Model):
__tablename__ = 'todos'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
city = db.Column(db.String(120))
# TODO: implement any missing fields, as a database migration using Flask-Migrate
def __repr__(self):
return f'<Todo {self.id} {self.name} {self.city}>'
db.create_all()
@app.route('/todos/create', methods=['POST'])
def create_todo():
error = False
body = {}
try:
name = request.form['name']
city = request.form['city']
todo = Todo(name=name, city=city)
if name == "":
flash("write your name", "failed")
elif city == "":
flash("write your city", "failed")
db.session.add(todo)
db.session.commit()
body['name'] = todo.name
body['city'] = todo.city
flash("submitted", "success")
except:
error = True
db.session.rollback()
print(sys.exc_info())
finally:
db.session.close()
if error:
abort (400)
else:
return jsonify(body)
@app.route('/')
def index():
return render_template('index.html', data=Todo.query.all())
index.html
<html>
<head>
<title>Text App</title>
<style>
.hidden{
display: none;
}
</style>
</head>
<body>
<form method="post" action="/todos/create">
<h4>name</h4>
<input type= "text" name="name" />
<h4>city</h4>
<input type= "text" name="city" />
<input type= "submit" value="Create" />
</form>
<div id= "error" class="hidden">Something went wrong!</div>
<ul>
{% for d in data %}
<li>{{d.name}}</li>
<li>{{d.city}}</li>
{% endfor %}
</ul>
<script>
const nameInput = document.getElementById('name');
const cityInput = document.getElementById('city');
document.getElementById('form').onsubmit = function(e) {
e.preventDefault();
const name = nameInput.value;
const city = cityInput.value;
descInput.value = '';
fetch('/todos/create', {
method: 'POST',
body: JSON.stringify({
'name': name,
'city': city,
}),
headers: {
'Content-Type': 'application/json',
}
})
.then(response => response.json())
.then(jsonResponse => {
console.log('response', jsonResponse);
li = document.createElement('li');
li.innerText = name;
li.innerText = city;
document.getElementById('todos').appendChild(li);
document.getElementById('error').className = 'hidden';
})
.catch(function() {
document.getElementById('error').className = '';
})
}
</script>
</body>
</html>
环境
Python 3.6.0
烧瓶 1.1.1
SQLAlchemy 1.3.10
psql 11.5
【问题讨论】:
标签: python html postgresql flask sqlalchemy