Bell9999
Bell9999

Reputation: 31

How connect Postgresql database with sqlalchemy python

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

Upvotes: 2

Views: 13000

Answers (3)

Shilpa Jayant Patil
Shilpa Jayant Patil

Reputation: 21

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

Upvotes: 1

user16298377
user16298377

Reputation: 31

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)

Upvotes: 2

Akshay Jain
Akshay Jain

Reputation: 790

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)

Upvotes: 1

Related Questions