2

I'm currently writing an program using Flask python. But I can not connect my database with my program. I'm use Postgresql for database.

import os

from sqlalchemy import create_engine

from sqlalchemy.orm import scoped_session, sessionmaker

engine = create_engine(os.getenv("DATABASE_URI"))

db = scoped_session(sessionmaker(bind=engine))

This is the code what I'm using for it, But it didn't work. So please help me to connect my database

This is the error message that what I have got, Error message

1

3 Answers 3

2

Configure database string

from sqlalchemy import create_engine
engine = create_engine('postgresql+psycopg2://user:password@hostname/database_name')

Connect db then:

import psycopg2
conn_string = "host='localhost' dbname='my_database' user='postgres' password='secret'"
conn = psycopg2.connect(conn_string)
1

db.py File which contains db connection(postgres url)

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://postgres:postgres@localhost/DB_NAME'

db = SQLAlchemy(app)

app.py This is your main file database tables will create when your server hits the first request.

from db import *
@app.before_first_request
def before():
    db.create_all()

enter code here......

table_structure.py This file contains your table structure

from db import db
class UserProjects(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(140), nullable=False)

1

step1:

from sqlalchemy import create_engine 

step2: use following command

db=create_engine("postgresql://username:passwd@localhost:port/database_name")

It will connect to the postgresql

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.