0

I've got the following Python code

app = Flask(__name__)      
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://my_user_name:@localhost:5432/my_db'
db = SQLAlchemy(app)

@app.route("/submit_signup_email", methods=["POST"])
def submit_signup_email():
  email = request.form["email"]
  created_timestamp = int(time.time())
  signup            = Signup(email, created_timestamp)
  db.session.add(signup)
  db.session.commit()

  # not working...
  test = Signup.query.filter_by(email=email).first()

Which works fine and I can check that a row has been inserted correctly in my DB.

But if I run this code after "db.session.commit()".....

test = Signup.query.filter_by(email=email).first()

I get the following error.

OperationalError: (OperationalError) could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"?

I'm not sure what the problem is, my Signup model looks like this in "models.py"

from flask_sqlalchemy import SQLAlchemy
from app import app, db

class Signup(db.Model):
  __tablename__     = "signups"
  id                = db.Column(db.Integer, primary_key=True)
  email             = db.Column(db.String)
  created_timestamp = db.Column(db.Integer)

  def __init__(self, email, created_timestamp):
    self.email             = email
    self.created_timestamp = created_timestamp

  def __repr__(self):
    return self.email
ericbae
  • 9,604
  • 25
  • 75
  • 108

2 Answers2

0

db = SQLAlchemy()
db.init_app(app)
db.app = app

init_app(app) :
This callback can be used to initialize an application for the use with this database setup. Never use a database in the context of an application not initialized that way or connections will leak.

and "from app import app,db" is incorrect

Ying.Zhao
  • 154
  • 3
  • 13
-1

Seems like a PostfreSql Problem, ref. Maybe you should try to restart your server.

EDIT

After seeing your code (in the chat room), the problem might be "Circular Import". Try to prevent that

Community
  • 1
  • 1
waitingkuo
  • 89,478
  • 28
  • 112
  • 118