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
  • What seems to be the problem? Please include a minimal, reproducible example. Showing the error message would be a good start. Commented May 31, 2020 at 8:57

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)

Comments

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)

Comments

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 Comment

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.