我正在使用flask和sqlalchemy开发应用程序。我正在使用html表单收集数据,我想自动计算并将年龄插入用户数据库中的age列。但是数据库中的插入操作无效。
以下是model.py
class Registration(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column('Name', db.String(50), nullable=False)
hosp_num = db.Column('Hospital number', db.String(15), nullable=False)
sex = db.Column('Sex', db.String(6), nullable=False)
dob = db.Column('Date of Birth', db.String(10), nullable=False)
age = db.Column('age', db.Integer)
...
def __init__(self, name, hosp_num, sex, dob, age):
self.name = name
self.hosp_num = hosp_num
self.sex = sex
self.dob = dob
self.age = age
...
在app.py
def calculate_age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
@app.route('/register', methods=['GET','POST'])
def register():
...
try:
date_of_birth = datetime.strptime(request.form['dob'], "%Y %m %d")
age = calculate_age(date_of_birth)
patient = Registration(request.form['name'], request.form['hosp_num'], request.form['sex'], request.form['dob'], age)
db.session.add(patient)
db.session.commit()
flash('Record was sucessfully saved')
return redirect(url_for('index'))
except:
db.session.rollback()
flash('Error in insert operation')
return render_template('register.html')
finally:
db.session.close()
return render_template('register.html')