This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

Connecting PostgreSQL with python sqlalchemy orm.


On this tutorial I’ll present you create a CRUD script through the use of python sqlalchemy orm.python is a multipurpose and hottest language on the planet. when writing a python script, we have to retailer knowledge in a unique database. Sqlalchemy, finest orm for python, can assist us to attach with a unique kind of SQL database nonetheless I this tutorial I’ll present you create CRUD script through the use of PostgreSQL database.

Let’s assume you already know python digital atmosphere and also you already set up in your computer.

You have to set up the next library.

pip set up sqlalchemy
pip set up psycopg2
Enter fullscreen mode

Exit fullscreen mode

Should you face any drawback to put in psycopg2 in your computer, you’ll be able to attempt for this

pip set up psycopg2-binary
Enter fullscreen mode

Exit fullscreen mode

you will have efficiently put in library in your computer now we will begin writing the script

from sqlalchemy import (
    Desk,
    Column,
    Index,
    Integer,
    Textual content,
    String,
    DateTime,
    Date,
    ForeignKey,
    create_engine,
    desc,
    asc,
    Boolean,
    and_
)
from sqlalchemy.orm import load_only
# from sqlalchemy import create_engine, Column, Integer, String, DateTime,Textual content, DATE, Boolean, Desk, ForeignKey, TIMESTAMP
from sqlalchemy.dialects.postgresql import ARRAY, UUID
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.engine.url import URL
import datetime
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 utilizing database settings from settings.py.
    Returns sqlalchemy engine occasion
    """
    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 Matter(DeclarativeBase):
    """
    outline a desk title of matter
    """
    __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)
    is_published = Column(Boolean, default=False)
Now join with database and crate desk

# perform calling
if __name__ == '__main__':
    engine = db_connect()
    create_deals_table(engine)
Enter fullscreen mode

Exit fullscreen mode

Outline crude performance for Matter desk

class Matter(DeclarativeBase):
    """
    opinion of a remark retailer on this desk.
    """
    __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)
    is_published = Column(Boolean, default=False)
    # get all merchandise from a desk
    @classmethod
    def by_all(cls):
        question = DBSession.question(Matter).all()
        question = DBSession.question(Matter).order_by(desc(Matter.created_on)).restrict(10)
        return question
     # get all with descending order and restrict from a desk
    @classmethod
    def by_all_limit(cls):
        question = DBSession.question(Matter).order_by(desc(Matter.created_on)).restrict(10)
        return question
    # get all with a number of filter and a number of subject choice
    @classmethod
    def by_all_filter(cls, created_by):
        question = DBSession.question(Matter).filter(and_((Matter.created_by == created_by), (Matter.is_published == True))).choices(load_only( "title", "description", "created_by", "created_on")).order_by(desc(Matter.content_timestamp)).restrict(10)
        return question
    # get single merchandise name by id
    @classmethod
    def by_id(cls, id):
        question = DBSession.question(Matter).filter_by(id=id).first()
        return question
    # replace single matter by id
    @classmethod
    def update_topic(cls, topic_id, **kwargs):
        DBSession.question(Matter).filter_by(id=topic_id).replace(kwargs)
        DBSession.commit()
        return 'matter up to date'
    # delete single matter by id
    @classmethod
    def delete_topic(cls, topic_id):
        DBSession.question(Matter).filter_by(topic_id=topic_id).delete()
        DBSession.commit()
        return 'matter deteted'
    # create matter by merchandise
    @classmethod
    def create_topic(cls, **kwargs):
        api = Matter(**kwargs)
        DBSession.add(api)
        DBSession.commit()
        return 'matter created'
Enter fullscreen mode

Exit fullscreen mode

You may name these capabilities in your script, wherever you need.

The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?