Untitled
unknown
plain_text
25 days ago
2.7 kB
2
Indexable
Never
from sqlalchemy import create_engine from sqlalchemy.orm import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy import Column, Integer, String, DateTime from contextlib import contextmanager from fastapi import FastAPI from strawberry.fastapi import GraphQLRouter from sqlalchemy.orm import column_property import strawberry from strawberry.types import Info from typing import List from datetime import datetime Base = declarative_base() # MySQL Database connection string DATABASE_URL = "mysql+pymysql://jsa_dev_admin:RM#AXR02NhAp@itx-acm-jsa-mdm-dev.czijpxum5el7.us-east-1.rds.amazonaws.com/jsamdm_dev" app = FastAPI() # Create the SQLAlchemy engine engine = create_engine(DATABASE_URL) # Create a configured "Session" class SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) class MDMContent(Base): __tablename__ = 'mdm_contents' id = Column('CONTENT_ID', Integer, primary_key=True) type = Column('CONTENT_TYPE', String) text = Column('CONTENT_TEXT', String) link = Column('CONTENT_LINK', String) order = Column('CONTENT_ORDER', Integer) created_date = Column('CREATED_DATE', DateTime) updated_date = Column('UPDATED_DATE', DateTime) @strawberry.type class MDMContentType: id: int type: str text: str | None link: str order: int created_date: datetime updated_date: datetime @contextmanager def get_db(): db = SessionLocal() try: yield db finally: db.close() @app.middleware("http") async def db_session_middleware(request, call_next): response = None try: request.state.db = SessionLocal() response = await call_next(request) finally: request.state.db.close() return response #@app.get("/") #def read_root(): #return {"Hello": "World"} @strawberry.type class Query: @strawberry.field def get_quick_links(self, info: Info) -> List[MDMContentType]: session: Session = info.context["request"].state.db # Ensure this matches the field name in the SQLAlchemy model quick_links = session.query(MDMContent).filter_by(type="Quick Links").all() return [MDMContentType( id=item.id, type=item.type, text=item.text, link=item.link, order=item.order, created_date=item.created_date, updated_date=item.updated_date ) for item in quick_links] # Define your schema as before schema = strawberry.Schema(query=Query) graphql_app = GraphQLRouter(schema) app.include_router(graphql_app, prefix="/graphql")
Leave a Comment