Created
October 30, 2019 11:32
-
-
Save giasuddin90/0910e08ee0d0fc5773c04181cf311294 to your computer and use it in GitHub Desktop.
Sqlalchemy and postgresql connection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# pre rehnquist: | |
# >psycopg2 | |
# >python version 3.* | |
#> SQLAlchemy | |
# | |
# Outcome: | |
# >using Sqlalchemy create table and call data from database | |
# >Table sync in postgresql | |
from sqlalchemy import ( | |
Table, | |
Column, | |
Index, | |
Integer, | |
Text, | |
String, | |
DateTime, | |
Date, | |
ForeignKey, | |
create_engine, | |
) | |
from sqlalchemy.ext.declarative import declarative_base | |
from sqlalchemy.engine.url import URL | |
from sqlalchemy.orm import sessionmaker | |
DeclarativeBase = declarative_base() | |
DATABASE = { | |
'drivername': 'postgres', | |
'host': '127.0.0.1', | |
'port': '5432', | |
'username': 'admin', | |
'password': '789', | |
'database': 'tesdb' | |
} | |
def db_connect(): | |
""" | |
Performs database connection using database settings from settings.py. | |
Returns sqlalchemy engine instance | |
""" | |
return create_engine(URL(**DATABASE)) | |
def create_deals_table(engine): | |
"""""" | |
DeclarativeBase.metadata.create_all(engine) | |
def db_session(): | |
engine = db_connect() | |
Session = sessionmaker(bind=engine) | |
session = Session() | |
return session | |
DBSession = db_session() | |
class Mymobel(DeclarativeBase): | |
""" | |
opinion of a comment store in this table. | |
""" | |
__tablename__ = "mymodel" | |
id = Column(Integer, primary_key=True) | |
title = Column(String(36)) | |
description = Column(String(36)) | |
created_by = Column(String(36)) | |
created_on = Column(DateTime) | |
if __name__ == '__main__': | |
engine = db_connect() | |
create_deals_table(engine) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment