from schoolsyst_api.accounts.models import User from schoolsyst_api.accounts.users import get_current_confirmed_user from schoolsyst_api.models import DatetimeRange, ObjectBareKey, WeekType from schoolsyst_api.resource_base import ResourceRoutesGenerator from schoolsyst_api.schedule import current_week_type from schoolsyst_api.schedule.models import ( Course, Event, EventMutation, EventMutationInterpretation, InEvent, ) from schoolsyst_api.settings.models import Settings from schoolsyst_api.utils import daterange router = InferringRouter() helper = ResourceRoutesGenerator( name_sg="event", name_pl="events", model_in=InEvent, model_out=Event, ) @router.get("/weektype_of/{date}") def get_week_type( date: date, settings: Settings = Depends(settings.get)) -> WeekType: return current_week_type( starting_week_type=settings.starting_week_type, year_start=settings.year_layout[0].start, current_date=date,
from fastapi import Depends, Header, HTTPException, Body, Query, Path, Form, APIRouter #from fastapi.responses import PlainTextResponse from fastapi.security import HTTPAuthorizationCredentials from starlette.responses import HTMLResponse, RedirectResponse, PlainTextResponse from starlette.requests import Request from ..configs import configs from .authorization import FRONTEND_APP, oauth, _get_id_token_user, authenticated, authorized_frontend from .authorization import _jwt_pub_key, create_jwt_token, parse_jwt_token from .models import TokensResponse, TokenResponse from ..dummy_frontend import loggedin_frontend from ..exceptions import DoesNotExistError, NotAuthorizedError from ..models import get_doc, get_docs, User, AppToken from ..services.models import jwt_security_scheme, IsSuccess auth_router = InferringRouter('auth') auth_base_url = configs['hostname'] + '/auth' frontend_url = configs['frontend']['hostname'] @auth_router.get( '/jwt_pubkey', status_code=200, description='Get the current JWT Public Key', tags=['Auth'], ) def get_jwt_pubkey(): return PlainTextResponse(_jwt_pub_key, media_type='text/plain') @auth_router.get(
from werkzeug import exceptions from starlette.requests import Request from fastapi import Depends, Header, HTTPException, Body, Query, Path, APIRouter from fastapi.security import HTTPAuthorizationCredentials from fastapi_utils.cbv import cbv from fastapi_utils.inferring_router import InferringRouter from .models import IsSuccess, ActuationRequest, jwt_security_scheme from ..dependencies import get_ts_db, get_lock_manager, get_actuation_iface, dependency_supplier from brick_server.extensions.lockmanager import LockManager from ..auth.authorization import auth_scheme, authorized from ..interfaces import BaseActuation, BaseTimeseries from ..configs import configs actuation_router = InferringRouter('actuation') @cbv(actuation_router) class ActuationEntity(): lock_manager: LockManager = Depends(get_lock_manager) actuation_iface: BaseActuation = Depends(get_actuation_iface) ts_db: BaseTimeseries = Depends(get_ts_db) auth_logic: Callable = Depends(dependency_supplier.get_auth_logic) @actuation_router.post( '/{entity_id}', description='Actuate an entity to a value', response_model=IsSuccess, status_code=200, tags=['Actuation'],
from fastapi_utils.api_model import APIMessage from fastapi_utils.cbv import cbv from fastapi_utils.inferring_router import InferringRouter from sqlalchemy import update, delete from models import TaskList from routers import session from schemas.task_list_schemas import TListCreate, TListRead, TListUpdate from utils import get_item_by_id LIST_ROUTER = InferringRouter() @cbv(LIST_ROUTER) class TaskListView: @LIST_ROUTER.post("/task_list") async def create_item(self, task_list: TListCreate) -> TListRead: task_list_orm = TaskList(desc=task_list.desc, tasks=[]) session.add(task_list_orm) await session.commit() return TListRead.from_orm(task_list_orm) @LIST_ROUTER.get("/task_list/{list_id}") async def read_item(self, list_id: int) -> TListRead: task_list_orm = await get_item_by_id(session, TaskList, list_id) return TListRead.from_orm(task_list_orm) @LIST_ROUTER.put("/task_list/{list_id}") async def update_item(self, list_id: int, task_list: TListUpdate) -> TListRead: task_list_orm = await get_item_by_id(session, TaskList, list_id)
from starlette.requests import Request from .models import TimeseriesData, ValueTypes, ValueType, IsSuccess, jwt_security_scheme from .models import entity_id_desc, graph_desc, relationships_desc, start_time_desc, end_time_desc from .models import value_type_desc, timeseries_data_desc from ..helpers import striding_windows from ..auth.authorization import authorized, authorized_arg, O, R, W from ..models import get_all_relationships from ..configs import configs from ..dependencies import get_brick_db, get_ts_db, dependency_supplier from ..interfaces import BaseTimeseries data_router = InferringRouter('data') @cbv(data_router) class TimeseriesById: ts_db: BaseTimeseries = Depends(get_ts_db) auth_logic: Callable = Depends(dependency_supplier.get_auth_logic) @data_router.get('/timeseries/{entity_id}', status_code=200, #description='Get data of an entity with in a time range.', response_model=TimeseriesData, tags=['Data'], ) @authorized_arg(R) async def get(self,
""" Pretend this function returns a SQLAlchemy ORM session""" def get_owned_item(session: Session, owner: UserID, item_id: ItemID) -> ItemORM: item: Optional[ItemORM] = session.query(ItemORM).get(item_id) if item is not None and item.owner != owner: raise HTTPException(status_code=HTTP_403_FORBIDDEN) if item is None: raise HTTPException(status_code=HTTP_404_NOT_FOUND) return item # End Setup app = FastAPI() router = InferringRouter() # Step 1: Create a router @cbv(router) # Step 2: Create and decorate a class to hold the endpoints class ItemCBV: # Step 3: Add dependencies as class attributes session: Session = Depends(get_db) user_id: UserID = Depends(get_jwt_user) @router.post("/item") def create_item(self, item: ItemCreate) -> ItemInDB: # Step 4: Use `self.<dependency_name>` to access shared dependencies item_orm = ItemORM(name=item.name, owner=self.user_id) self.session.add(item_orm) self.session.commit() return ItemInDB.from_orm(item_orm)
from typing import List from fastapi_utils.inferring_router import InferringRouter from src import facade from .schemas import AddEvolutionParams, CreatePokemonParams, HelloWorldNode, \ PokemonNode, UpdatePokemonParams router = InferringRouter(prefix="/api") @router.get("/") def hello() -> HelloWorldNode: return {"message": "Hello World"} @router.post("/pokemon/create") def create_pokemon(body: CreatePokemonParams) -> PokemonNode: return facade.add_pokemon( no=body.no, name=body.name, types=body.types, ) @router.get("/pokemon/{no}") def get_pokemon(no: str) -> PokemonNode: return facade.get_pokemon(no) @router.get("/pokemons")
from fastapi_utils.cbv import cbv from starlette.requests import Request from .models import Entity, Relationships, EntityIds, Entities, IsSuccess from .models import EntitiesCreateResponse, CreateEntitiesRequest from .models import entity_id_desc, graph_desc, jwt_security_scheme, relationships_desc, entity_desc, relation_query_desc from .namespaces import URN, UUID from ..dbs import BrickSparqlAsync from ..helpers import striding_windows from ..auth.authorization import auth_scheme, parse_jwt_token, authorized, authorized_arg, R, O from ..models import get_all_relationships from ..configs import configs from ..dependencies import get_brick_db, dependency_supplier entity_router = InferringRouter('entities') async def get_entity_type(db, entity_id): qstr = """ select ?o where {{ <{0}> a ?o. }} """.format(entity_id) res = await db.query(qstr) entity_types = [row['o']['value'] for row in res['results']['bindings']] if entity_types: #assert len(entity_types) == 1 # TODO: This should be changed return entity_types[0] else: # Type not found for the entity_id
from fastapi_utils.api_model import APIMessage from fastapi_utils.cbv import cbv from fastapi_utils.inferring_router import InferringRouter from sqlalchemy import update, delete from models import Task from routers import session from schemas.task_schemas import TODOCreate, TODOUpdate, TODORead from utils import get_item_by_id TASK_ROUTER = InferringRouter() @cbv(TASK_ROUTER) class TaskView: @TASK_ROUTER.post("/task_list/{list_id}/task") async def create_item(self, task: TODOCreate) -> TODORead: task_orm = Task(desc=task.desc, list_id=task.list_id) session.add(task_orm) await session.commit() return TODORead.from_orm(task_orm) @TASK_ROUTER.get("/task_list/{list_id}/task/{task_id}") async def read_item(self, task_id: int) -> TODORead: task_orm = await get_item_by_id(session, Task, task_id) return TODORead.from_orm(task_orm) @TASK_ROUTER.put("/task_list/{list_id}/task/{task_id}") async def update_item(self, task_id: int, task: TODOUpdate) -> TODORead: task_orm = await get_item_by_id(session, Task, task_id) q = update(Task).where(Task.id == task_id)
from fastapi import APIRouter, HTTPException, status from fastapi_utils.cbv import cbv from fastapi_utils.inferring_router import InferringRouter from fastapi_sqlalchemy import db from typing import List from app.api.property.models import Property as ModelProperty from app.api.property.schemas import PropertyCreate as SchemaPropertyCreate from app.api.property.schemas import Property as SchemaProperties from app.api.property.models import RealEstate as ModelRealEstate from app.api.property.schemas import RealEstateCreate as SchemaRealEstateCreate from app.api.property.schemas import RealEstate as SchemaRealEstate router_property = InferringRouter() router_real_estate = InferringRouter() @cbv(router_property) class Property: @router_property.get("/", response_model=List[SchemaProperties], status_code=status.HTTP_200_OK) def get_properties(self): properties = db.session.query(ModelProperty).all() return properties @router_property.get("/{id_property}", response_model=SchemaProperties, status_code=status.HTTP_200_OK)
from fastapi_utils.cbv import cbv from fastapi_utils.inferring_router import InferringRouter from fastapi import Depends, FastAPI, Header, HTTPException from sqlalchemy.orm import Session from utils.db import db_session from user.User import User from user.UserInput import UserInput userRouter = InferringRouter() @cbv(userRouter) class UserController: db: Session = Depends(db_session) def __init__(self): pass @userRouter.get("/users/search") def search(self): try: data = self.db.query(User).limit(100).all() return {"data": data} except Exception as error: print(error) return { "error": error } @userRouter.post("/users/save") def save(self, user: UserInput): try: db_item = User(**user.dict()) self.db.add(db_item)
from starlette.requests import Request from fastapi.security import HTTPAuthorizationCredentials from .models import TimeseriesData, SparqlResult from .models import sql_desc, sparql_desc from ..dbs import BrickSparqlAsync from ..helpers import striding_windows from ..auth.authorization import authorized, auth_scheme from ..models import get_all_relationships from ..configs import configs from ..dependencies import get_brick_db, get_ts_db, dependency_supplier from ..interfaces import BaseTimeseries query_router = InferringRouter('raw_queries') @cbv(query_router) class TimeseriesQuery(): ts_db: BaseTimeseries = Depends(get_ts_db) auth_logic: Callable = Depends(dependency_supplier.get_auth_logic) @query_router.post('/timeseries', description='Raw PostgreSQL query for timeseries. (May not be exposed in the production deployment.)', #response_model = TimeseriesData, tags=['Raw Queries'], ) @authorized async def post(self, request: Request,