def get_db(): """ Basic connection with the database. :return: """ try: db = SessionLocal() yield db finally: db.close()
def get_db(): try: db = SessionLocal() yield db finally: db.close()
def get_db(): models.Base.metadata.create_all(bind=engine) db = SessionLocal() return db
from typing import Dict from fastapi import HTTPException, status from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.orm import Session, Query from src.database import SessionLocal session: Session = SessionLocal() class ModelMixin(object): @classmethod def create(cls, body: Dict): try: # Create an object in the database obj: cls = cls(**body) session.add(obj) session.commit() session.refresh(obj) return obj except SQLAlchemyError as err: print("Database error:", err) raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR) @classmethod def get(cls, **kwargs): obj: cls = session.query(cls).filter_by(**kwargs).first()
def callback(cb, method, properties, body): print('Received in main') data = json.loads(body) db = SessionLocal() if properties.content_type == 'product_created': product = Product(**data) db.add(product) db.commit() db.refresh(product) print('Product created') elif properties.content_type == 'product_updated': product = db.query(Product).get(data['id']) product.title = data['title'] product.image = data['image'] product.likes = data['likes'] db.commit() db.refresh(product) print('Product updated') elif properties.content_type == 'product_deleted': product = db.query(Product).get(data['id']) db.delete(product) db.commit() print('Product deleted')
def get_db_session(self): db = SessionLocal() try: yield db finally: db.close()
def configureDB(self): ''' INIT SQLITE DB ''' Base.metadata.create_all(engine) db = SessionLocal() database.init_defaults(db)