Issue
I am trying to insert new data to my database but my web application returns this error. My codes are as follows:
models.py
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
...
class Patient(db.Model):
__tablename__ = "patients"
id = db.Column(db.Integer, primary_key=True)
lname = db.Column(db.String, nullable=False)
fname = db.Column(db.String, nullable=False)
mname = db.Column(db.String, nullable=True)
address = db.Column(db.String, nullable=False)
birthdate = db.Column(db.Date, nullable=False)
date_modified = db.Column(db.DateTime, nullable=False)
modified_by = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
date_created = db.Column(db.DateTime, nullable=False)
created_by = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
def __init__(self, fname, mname, lname):
self.fname = fname
self.mname = mname
self.lname = lname
application.py
import os
from flask import *
from flask_session import Session
from sqlalchemy import *
from sqlalchemy.orm import scoped_session, sessionmaker
from models import *
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL")
# Check for environment variable
if not os.getenv("DATABASE_URL"):
raise RuntimeError("DATABASE_URL is not set")
app.secret_key = '######'
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(app)
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))
...
@app.route("/submitpatient", methods=["POST"])
def submitpatient():
fname = request.form.get("fname")
mname = request.form.get("mname")
lname = request.form.get("lname")
patient = Patient(fname=fname, mname=mname, lname=lname)
db.session.add(patient)
db.session.commit()
return redirect(url_for('index'))
I'm new to python and I have been trying to find the error in my code for hours but I can't seem to find anything that would help me.
Solution
I guess the problem that u missed to create a constructor "Session" after using it,
The code will be:
# create a configured "Session" class
Session = scoped_session(sessionmaker(bind=engine))
@app.route("/submitpatient", methods=["POST"])
def submitpatient():
fname = request.form.get("fname")
mname = request.form.get("mname")
lname = request.form.get("lname")
patient = Patient(fname=fname, mname=mname, lname=lname)
#create a Session
session = Session()
session.add(patient)
session.commit()
return redirect(url_for('index'))
for more information, see this
Answered By - Mahrez BenHamad
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.