Exemplo n.º 1
0
from fastapi import APIRouter
from api.v1.endpoints import ekyc
from fastapi.staticfiles import StaticFiles

api_router = APIRouter()

api_router.include_router(ekyc.router, prefix='/ekyc', tags=['ekyc'])
api_router.mount("/ui", StaticFiles(directory="./api/build"), name="ui_build")
api_router.mount("/static",
                 StaticFiles(directory="./api/build/static"),
                 name="ui_static")
from typing import List
from fastapi import APIRouter, HTTPException
from app.models.Persona import Persona
import logging

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/personas",
                   tags=["personas"], )


@router.get("/", response_model=List[Persona])
def personas_get_all():
    # personas = Persona.get_all()
    personas = []
    logger.info('personas %s', personas)

    return personas


@router.get('/{persona_id}', response_model=Persona)
def get_detail(persona_id: int):
    persona = Persona.get_by_id(persona_id)
    if persona is None:
        raise HTTPException(status_code=404, detail=f"Persona con id:{persona_id} not found")

    return persona


@router.put('/{persona_id}', response_model=Persona)
def update_detail(persona_id: int, persona: Persona):
    persona_original = Persona.get_by_id(persona_id)
Exemplo n.º 3
0
from typing import Callable, List, Optional

from fastapi import APIRouter, Depends
from starlette.requests import Request
from starlette.responses import Response

from extensions.rendering import get_render
from extensions.signals import get_message_flashes
from models import User, Node, Group, Content
from extensions.mongo import mongo_engine
from pprint import pprint
from models import ObjectIdStr
import tempfile

router = APIRouter()


@router.get("/{content_id}")
async def read_content(content_id: ObjectIdStr,
                       request: Request,
                       flashes: list = Depends(get_message_flashes)):
    with tempfile.TemporaryFile() as file:
        content = Content.parse_obj(
            (await
             mongo_engine.db["fs.files"].find_one({"_id":
                                                   content_id}))["metadata"])
        await mongo_engine.fs.download_to_stream(content_id, file)
        pprint(content)
        file.seek(0)
        data = file.read()
    return Response(content=data, media_type=f"application/{content.filetype}")
Exemplo n.º 4
0
from api.dependencies.database import get_repository
from api.dependencies.shared_services import get_shared_service_by_id_from_path, get_operation_by_id_from_path
from db.repositories.resource_templates import ResourceTemplateRepository
from db.repositories.shared_services import SharedServiceRepository
from models.domain.resource import ResourceType
from models.schemas.operation import OperationInList, OperationInResponse
from models.schemas.shared_service import SharedServiceInCreate, SharedServicesInList, SharedServiceInResponse
from models.schemas.resource import ResourcePatch
from resources import strings
from .workspaces import save_and_deploy_resource, construct_location_header
from azure.cosmos.exceptions import CosmosAccessConditionFailedError
from .resource_helpers import send_custom_action_message, send_uninstall_message, send_resource_request_message
from services.authentication import get_current_admin_user, get_current_tre_user_or_tre_admin
from models.domain.request_action import RequestAction

shared_services_router = APIRouter(
    dependencies=[Depends(get_current_tre_user_or_tre_admin)])


@shared_services_router.get(
    "/shared-services",
    response_model=SharedServicesInList,
    name=strings.API_GET_ALL_SHARED_SERVICES,
    dependencies=[Depends(get_current_tre_user_or_tre_admin)])
async def retrieve_shared_services(shared_services_repo=Depends(
    get_repository(SharedServiceRepository))) -> SharedServicesInList:
    shared_services = shared_services_repo.get_active_shared_services()
    return SharedServicesInList(sharedServices=shared_services)


@shared_services_router.get("/shared-services/{shared_service_id}",
                            response_model=SharedServiceInResponse,
Exemplo n.º 5
0
from fastapi import APIRouter, Depends
from mealie.db.database import db
from mealie.db.db_setup import generate_session
from mealie.routes.deps import get_current_user, is_logged_in
from mealie.schema.recipe import RecipeSummary
from slugify import slugify
from sqlalchemy.orm.session import Session

router = APIRouter(tags=["Query All Recipes"])


@router.get("/api/recipes/summary", response_model=list[RecipeSummary])
async def get_recipe_summary(start=0,
                             limit=9999,
                             session: Session = Depends(generate_session),
                             user: bool = Depends(is_logged_in)):
    """
    Returns key the recipe summary data for recipes in the database. You can perform
    slice operations to set the skip/end amounts for recipes. All recipes are sorted by the added date.

    **Query Parameters**
    - skip: The database entry to start at. (0 Indexed)
    - end: The number of entries to return.

    skip=2, end=10 will return entries

    """

    if user:
        return db.recipes.get_all(session,
                                  limit=limit,
Exemplo n.º 6
0
# @Email:   [email protected]
# @Blog:   https://blog.ztongyang.cn
# @Last Modified time: 2021-03-23 18:47:59

import random
import time
from fastapi import APIRouter
from spiders import Soul
from spiders import Joke
from spiders import Shici
from spiders import YiyanSpider
from spiders import TodaySpider
from pydantic import BaseModel
from typing import Optional

soul = APIRouter()
joke = APIRouter()
shici = APIRouter()
yiyan = APIRouter()
today = APIRouter()

categories = [
    "dongwu", "jieri", "renwu", "shanshui", "shenghuo", "shiwu", "shuqing",
    "siji", "tianqi", "zhiwu"
]


class PostData(BaseModel):
    category: Optional[str] = None

Exemplo n.º 7
0
from fastapi import APIRouter, Depends, FastAPI, Header, HTTPException

from app.api.api_v1.endpoints import group, scan, ng_word
from app.core.config import settings

api_router = APIRouter()

api_router.include_router(ng_word.router,
                          prefix="/ng_words",
                          tags=["ng_words"])

api_router.include_router(scan.router, prefix="/scan", tags=["scan"])

api_router.include_router(group.router, prefix="/groups", tags=["groups"])
Exemplo n.º 8
0
from fastapi import APIRouter

# from app.text.endpoint.texts import text_router
# from app.cluster.endpoint.clusters import cluster_router
# from app.ai_model.endpoint.ai_models import ai_model_router

api_router = APIRouter()

# api_router.include_router(text_router, prefix="/texts", tags=["Text"])
# api_router.include_router(cluster_router, prefix="/clusters", tags=["Cluster"])
# api_router.include_router(ai_model_router, prefix="/ai_models", tags=["AI Models"])
Exemplo n.º 9
0
from typing import List
from fastapi import Depends, APIRouter, HTTPException, UploadFile, File
from sqlalchemy.orm import Session
from app.blogs import schemas, crud
from app.db.session import get_db
from app.auth.authentications import get_current_active_user
from app.images.process import save_image

app = APIRouter()


@app.get("/category/",
         response_model=List[schemas.Category],
         tags=["post_property"])
def read_categories(
        skip: int = 0,
        limit: int = 100,
        db: Session = Depends(get_db),
        current_user=Depends(get_current_active_user),
):
    query = crud.get_category_query(db, skip=skip, limit=limit)
    if len(query) == 0:
        raise HTTPException(status_code=400, detail="Category does not exist")
    return query


@app.post("/category/",
          response_model=schemas.Category,
          tags=["post_property"])
def create_category(
        category: schemas.CreateCategory,
Exemplo n.º 10
0
from fastapi import APIRouter

from jina.helper import get_public_ip, get_internal_ip, get_full_version
from jina.logging.profile import used_memory_readable
from ...models.status import DaemonStatus
from ...stores import pea_store, pod_store, flow_store, workspace_store

router = APIRouter(tags=['daemon'])


@router.on_event('startup')
async def startup():
    """Start the process"""
    from ... import daemon_logger, jinad_args

    daemon_logger.info(
        f'''
Welcome to Jina daemon - the manager of distributed Jina
💬 Swagger UI     :\thttp://localhost:{jinad_args.port_expose}/docs
📚 Redoc          :\thttp://localhost:{jinad_args.port_expose}/redoc
🔒 Private address:\thttp://{get_internal_ip()}:{jinad_args.port_expose}
🌐 Public address :\thttp://{get_public_ip()}:{jinad_args.port_expose}'''
    )
    from jina import __ready_msg__

    daemon_logger.success(__ready_msg__)


@router.get(
    path='/',
)
Exemplo n.º 11
0
from fastapi import APIRouter
from typing import Optional

from api.models.core import CoreDTO
from api.utils import (extract_config, handle_response, update_config,
                       map_section_from_config, map_to_config_file_format)

core_router = APIRouter()


@core_router.get("", response_model=CoreDTO)
def get_core_config():
    """
    Returns the core configuration of the processor
    """
    return map_section_from_config("CORE", extract_config())


@core_router.put("", response_model=CoreDTO)
def update_core_config(core: CoreDTO, reboot_processor: Optional[bool] = True):
    """
    Updates the core configuration of the processor
    """
    config_dict = extract_config()
    core_dict = map_to_config_file_format(core)
    config_dict["CORE"] = core_dict
    success = update_config(config_dict, reboot_processor)
    return handle_response(core_dict, success)
Exemplo n.º 12
0
from dispatch.incident_priority.views import router as incident_priority_router
from dispatch.incident_type.views import router as incident_type_router
from dispatch.individual.views import router as individual_contact_router

from dispatch.policy.views import router as policy_router
from dispatch.route.views import router as route_router
from dispatch.search.views import router as search_router
from dispatch.service.views import router as service_router
from dispatch.team.views import router as team_contact_router
from dispatch.term.views import router as team_router
from dispatch.document.views import router as document_router
from dispatch.task.views import router as task_router

from .common.utils.cli import install_plugins, install_plugin_events

api_router = APIRouter(
)  # WARNING: Don't use this unless you want unauthenticated routes
authenticated_api_router = APIRouter()

# NOTE: All api routes should be authenticated by default
authenticated_api_router.include_router(document_router,
                                        prefix="/documents",
                                        tags=["documents"])
authenticated_api_router.include_router(tag_router,
                                        prefix="/tags",
                                        tags=["Tags"])
authenticated_api_router.include_router(service_router,
                                        prefix="/services",
                                        tags=["services"])
authenticated_api_router.include_router(team_contact_router,
                                        prefix="/teams",
                                        tags=["teams"])
Exemplo n.º 13
0
from dispatch.database.core import get_db
from dispatch.database.service import search_filter_sort_paginate

from .models import (
    UserLogin,
    UserRegister,
    UserRead,
    UserUpdate,
    UserPagination,
    UserLoginResponse,
    UserRegisterResponse,
)
from .service import get, get_by_email, update, create, get_current_user

auth_router = APIRouter()
user_router = APIRouter()


@user_router.get("/", response_model=UserPagination)
def get_users(
        db_session: Session = Depends(get_db),
        page: int = 1,
        items_per_page: int = Query(5, alias="itemsPerPage"),
        query_str: str = Query(None, alias="q"),
        sort_by: List[str] = Query([], alias="sortBy[]"),
        descending: List[bool] = Query([], alias="descending[]"),
        fields: List[str] = Query([], alias="fields[]"),
        ops: List[str] = Query([], alias="ops[]"),
        values: List[str] = Query([], alias="values[]"),
):
Exemplo n.º 14
0
from fastapi import APIRouter
from models.schemas.iris import Iris, IrisPredictionResponse
import models.ml.classifier as clf

app_iris_predict_v1 = APIRouter()


@app_iris_predict_v1.post('/iris/predict',
                          tags=["Predictions"],
                          response_model=IrisPredictionResponse,
                          description="Get a classification from Iris")
async def get_prediction(iris: Iris):
    data = dict(iris)['data']
    prediction = clf.model.predict(data).tolist()
    probability = clf.model.predict_proba(data).tolist()
    log_probability = clf.model.predict_log_proba(data).tolist()
    return {
        "prediction": prediction,
        "probability": probability,
        "log_probability": log_probability
    }
Exemplo n.º 15
0
from fastapi import APIRouter

from routers import (
    users, tasks, questions
)


api_router = APIRouter()


api_router.include_router(users.router, prefix='/user', tags=['User'])
api_router.include_router(tasks.router, prefix='/task', tags=['Task'])
api_router.include_router(questions.router, prefix='/question', tags=['Question'])
Exemplo n.º 16
0
from fastapi import Depends, APIRouter, HTTPException

from ... import Runtime400Exception
from ..dependencies import PeaDepends
from ...models import DaemonID, ContainerItem, ContainerStoreStatus, PeaModel
from ...stores import pea_store as store

router = APIRouter(prefix='/peas', tags=['peas'])


@router.get(path='',
            summary='Get all alive Pea\' status',
            response_model=ContainerStoreStatus)
async def _get_items():
    return store.status


@router.get(
    path='/arguments',
    summary='Get all accepted arguments of a Pea',
)
async def _fetch_pea_params():
    return PeaModel.schema()['properties']


@router.post(
    path='',
    summary='Create a Pea',
    description='Create a Pea and add it to the store',
    status_code=201,
    response_model=DaemonID,
Exemplo n.º 17
0
from fastapi import APIRouter

from app.views import pic
# from app.views import users, user_info, account

bprouter = APIRouter()

# bprouter.include_router(users.router, tags=['users'])
# bprouter.include_router(user_info.router, tags=['user_info'])
# bprouter.include_router(account.router, tags=['account'], prefix='/account')
bprouter.include_router(pic.router, tags=['pic'])
Exemplo n.º 18
0
from typing import List

from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session

from ..domain import schemas, database
from ..repository import user_repository, blog_repository
from ..security import oauth2

router = APIRouter(prefix='/api/users', tags=['Users'])


@router.post('/',
             status_code=status.HTTP_201_CREATED,
             response_model=schemas.ShowUser)
async def add_user(request: schemas.CreateUser,
                   db: Session = Depends(database.get_db)):
    return user_repository.create(db, request)


@router.get('/', response_model=List[schemas.ShowAuthor])
async def get_users(db: Session = Depends(database.get_db)):
    return user_repository.get_all(db)


# @router.get('/me', status_code=status.HTTP_200_OK, response_model=schemas.ShowUser)
# async def get_me(db: Session = Depends(database.get_db),
#                  current_user: models.User = Depends(oauth2.get_current_user)):
#     user = blog_repository.get_by_username(db, current_user.username)
#     return user
Exemplo n.º 19
0
# import native Python packages
from enum import Enum

# import third party packages
from fastapi import APIRouter, Request
from fastapi.templating import Jinja2Templates

# router and templates
tc_views = APIRouter(prefix="/timecapsule")
tcd_views = APIRouter(prefix="/timecapsuledeep")
templates = Jinja2Templates(directory='templates')


class TemplateID(str, Enum):
    APARGUMENT = "apargument"
    APARGUMENTSCAN = "apargumentscan"
    APENGLISH12 = "apenglish12"
    APPS = "apps"
    APSCHOLARD = "apscholard"
    BLUEBIRD = "Bluebird"
    BOWLINGPIC = "bowlingpic"
    CALCULUS = "calculus"
    CARPAYMENT = "CarPayment"
    DIPLOMA = "diploma"
    DOYOUKNOWME = "DoYouKnowMe"
    ECSP = "ecsp"
    ENGLISH10 = "english10"
    ENTER = "enter"
    FIRSTAPPLET = "FirstApplet"
    GPA = "gpa"
    INDEX = "index"
Exemplo n.º 20
0
import asyncio

from fastapi import APIRouter, Depends
from fastapi.responses import RedirectResponse
from fastapi.exceptions import HTTPException
from starlette.requests import Request

from app.config import templates
from app.routers import deps
from app.security import superuser_required
from app.models import UserPayload
from app.api import userfunc, apifunc
from app.func import read_exams
from app.models import Subjects

router = APIRouter(prefix='/user-activity')


@router.get('/')
@superuser_required
async def manage_list_userinfo(
    request: Request,
    current_user: UserPayload = Depends(deps.get_current_user)
) -> Any:
    users = await userfunc.get_all_user()
    return templates.TemplateResponse('manager/user-statusboard.jinja2', {
        'request': request,
        'current_user': current_user,
        'users': users
    })
Exemplo n.º 21
0
from fastapi import APIRouter, Depends, HTTPException, Response, Request
from fastapi.responses import JSONResponse

from fastapi_sqlalchemy import db
from app.app_app import app
from app.app_jwt import jwt_user
from app.mail import send_mail
from app.google_analytics import ga
import common.models as M
from sqlalchemy import text
from common.utils import vars

import logging
logger = logging.getLogger(__name__)

stripe_router = APIRouter()

stripe.api_key = vars.STRIPE_SECRET_KEY
stripe.api_version = vars.STRIPE_API_VERSION


def product_details():
    return {
        'currency': 'USD',
        'amount': 500
    }


@stripe_router.get('/public-key')
def PUBLISHABLE_KEY(viewer: M.User = Depends(jwt_user)):
    return {
Exemplo n.º 22
0
from app.api.dependencies.authentication import get_current_user_authorizer
from app.api.dependencies.database import get_repository
from app.db.repositories.articles import ArticlesRepository
from app.models.domain.articles import Article
from app.models.domain.users import User
from app.models.schemas.articles import (
    DEFAULT_ARTICLES_LIMIT,
    DEFAULT_ARTICLES_OFFSET,
    ArticleForResponse,
    ArticleInResponse,
    ListOfArticlesInResponse,
)
from app.resources import strings
from app.api.base import BaseRoute

router = APIRouter(route_class=BaseRoute)


@router.get(
    "/feed",
    response_model=ListOfArticlesInResponse,
    name="articles:get-user-feed-articles",
)
async def get_articles_for_user_feed(
    limit: int = Query(DEFAULT_ARTICLES_LIMIT, ge=1),
    offset: int = Query(DEFAULT_ARTICLES_OFFSET, ge=0),
    user: User = Depends(get_current_user_authorizer()),
    articles_repo: ArticlesRepository = Depends(
        get_repository(ArticlesRepository)),
) -> ListOfArticlesInResponse:
    articles = await articles_repo.get_articles_for_user_feed(
Exemplo n.º 23
0
from fastapi import APIRouter, Depends, HTTPException, status
from dependencies import get_token_header
from nodeFunctions import get_node_ip, get_url, get_header
import requests

router = APIRouter(
    prefix="/account",
    tags=["account"],
    dependencies=[Depends(get_token_header)],
    responses={404: {
        "description": "Not found"
    }},
)


@router.get('/quota/{viteAddress}',
            description='Returns quota and vite amount for address')
async def get_quota(viteAddress: str):
    nodeIP = get_node_ip()
    if nodeIP == False:
        print('Connection ERROR...')
        raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
                            detail='Could not find a node')

    url = get_url(nodeIP)
    header = get_header()
    body = {
        "jsonrpc": "2.0",
        "id": 1,
        "method": "contract_getQuotaByAccount",
        "params": [viteAddress]
Exemplo n.º 24
0
from dispatch.database import get_db, search_filter_sort_paginate
from dispatch.plugins.kandbox_planner.util.kandbox_date_util import get_current_day_string
from dispatch.service.planner_service import (
    get_default_active_planner,
    get_appt_dict_from_redis,
)
from dispatch.team.models import Team
from dispatch.service.planner_models import (
    GenericJobPredictActionInput, GenericJobPredictActionOutput,
    GenericJobAction, GenericJobCommitActionInput, LockedSlot,
    LockedSlotOutput, GenericJobCommitActionInput, GenericJobCommitOutput,
    SingleJobDropCheckInput, SingleJobDropCheckOutput, PLANNER_ERROR_MESSAGES)

import dataclasses

planner_router = APIRouter()

import dataclasses
import json

from dispatch.plugins.kandbox_planner.env.env_models import ActionDict, ActionEvaluationScore
from dispatch.plugins.kandbox_planner.env.env_enums import (
    ActionType,
    ActionScoringResultType,
    AppointmentStatus,
)

from dispatch.config import DATA_START_DAY

import logging
Exemplo n.º 25
0
from fastapi import APIRouter

from . import auth, challenges, roles, users

router = APIRouter(prefix="/v1")

router.include_router(auth.router)
router.include_router(challenges.router)
router.include_router(roles.router)
router.include_router(users.router)
Exemplo n.º 26
0
def get_user_router():
    user_router = APIRouter(tags=["User"])

    class CurrentUserResponse(BaseModel):
        email: str
        username: str
        fav_enterprise_id: Optional[int] = None

    @user_router.get(
        "/user/me",
        response_model=CurrentUserResponse,
        responses={status.HTTP_401_UNAUTHORIZED: {
            "model": Message
        }},
    )
    async def get_user_data(user: models.User = Depends(CurrentUser())):

        user_data = CurrentUserResponse(
            email=user.email,
            username=user.username,
            fav_enterprise_id=user.fav_enterprise_id.id
            if user.fav_enterprise_id else None,
        )
        return user_data

    class UserUpdateEnterpriseResponse(CurrentUserResponse):
        email: Optional[str] = None
        username: Optional[str] = None
        fav_enterprise_id: int

    @user_router.patch(
        "/user/me/preferred_enterprise",
        response_model=UserUpdateEnterpriseResponse,
        responses={status.HTTP_401_UNAUTHORIZED: {
            "model": Message
        }},
    )
    async def update_enterprise(
        enterprise_id: int,
        user: models.User = Depends(
            CurrentUser(required_permissions=[
                models.UserEnterpriseRoles.editor,
                models.UserEnterpriseRoles.admin,
                models.UserEnterpriseRoles.viewer,
            ], )),
    ):
        await user.update(fav_enterprise_id=enterprise_id)
        return UserUpdateEnterpriseResponse(
            email=user.email,
            username=user.username,
            fav_enterprise_id=user.fav_enterprise_id.id,
        )

    class FavEnterpriseResponse(BaseModel):
        fav_enterprise: int

    @user_router.get(
        "/user/me/preferred_enterprise",
        response_model=FavEnterpriseResponse,
        responses={
            status.HTTP_409_CONFLICT: {
                "model": Message
            },
            HTTP_404_NOT_FOUND: {
                "model": Message
            },
        },
    )
    async def get_fav_enterprise(user: models.User = Depends(CurrentUser())):
        if user.fav_enterprise_id is not None:
            fav_enterprise = FavEnterpriseResponse(
                fav_enterprise=user.fav_enterprise_id.id)
            return fav_enterprise
        else:
            raise HTTPException(HTTP_404_NOT_FOUND,
                                "Not found favorite enterprise.")

    return user_router
Exemplo n.º 27
0
def kp_router(
    database_file: Union[str, aiosqlite.Connection] = ":memory:",
    **kwargs,
):
    """Add KP to server."""
    router = APIRouter()

    @router.post("/query", response_model=Response)
    async def answer_question(query: Query, ) -> Response:
        """Get results for query graph."""
        query = query.dict(exclude_unset=True)
        workflow = query.get("workflow", [{"id": "lookup"}])
        if len(workflow) > 1:
            raise HTTPException(
                400, "Binder does not support workflows of length >1")
        operation = workflow[0]
        qgraph = query["message"]["query_graph"]
        if operation["id"] == "lookup":
            async with KnowledgeProvider(database_file, **kwargs) as kp:
                kgraph, results = await kp.get_results(qgraph)
        elif operation["id"] == "bind":
            kgraph = query["message"]["knowledge_graph"]
            knodes = [{
                "id":
                knode_id,
                "category":
                knode.get("categories", ["biolink:NamedThing"])[0],
            } for knode_id, knode in kgraph["nodes"].items()]
            kedges = [{
                "id": kedge_id,
                "subject": kedge["subject"],
                "predicate": kedge["predicate"],
                "object": kedge["object"],
            } for kedge_id, kedge in kgraph["edges"].items()]

            async with KnowledgeProvider(":memory:", **kwargs) as kp:
                await add_data(kp.db, knodes, kedges)
                kgraph, results = await kp.get_results(qgraph)
        else:
            raise HTTPException(400, f"Unsupported operation {operation}")

        response = {
            "message": {
                "knowledge_graph": kgraph,
                "results": results,
                "query_graph": qgraph,
            }
        }
        return Response.parse_obj(response)

    @router.get("/meta_knowledge_graph")
    async def get_metakg(
            kp: KnowledgeProvider = Depends(get_kp(database_file)), ):
        """Get meta knowledge graph."""
        meta_kg = {
            "edges": [{
                "subject": op["subject_category"],
                "predicate": op["predicate"],
                "object": op["object_category"],
            } for op in await kp.get_operations()],
            "nodes": {
                category: {
                    "id_prefixes": data
                }
                for category, data in (await kp.get_curie_prefixes()).items()
            },
        }
        return meta_kg

    return router
Exemplo n.º 28
0
from fastapi import APIRouter, Depends, status, HTTPException
from .. import schemas, database, models, oauth2
from sqlalchemy.orm import Session
from typing import List
from ..repository import stock

router = APIRouter(prefix="/Stock", tags=['Stocks'])

get_db = database.get_db


# input each route
@router.get('/', response_model=List[schemas.ShowStock])
def all(db: Session = Depends(get_db),
        current_user: schemas.User = Depends(oauth2.get_current_user)):
    return stock.get_all(db)


# use status to auto create the status codes
@router.post('/', status_code=status.HTTP_201_CREATED)
# converts session into pydantic
def create(request: schemas.Stock,
           db: Session = Depends(get_db),
           current_user: schemas.User = Depends(oauth2.get_current_user)):
    return stock.create(request, db)


@router.delete('/{id}', status_code=status.HTTP_204_NO_CONTENT)
def destroy(id: int,
            db: Session = Depends(get_db),
            current_user: schemas.User = Depends(oauth2.get_current_user)):
Exemplo n.º 29
0
from fastapi import APIRouter, Depends
from SmartHome.depends.auth import token_dep
from SmartHome.schemas.group import GroupSchema
from SmartHome.logic.groups.GroupFile import Groups
from fastapi.responses import JSONResponse
from SmartHome.schemas.device import DeviceValueSchema
from SmartHome.logic.groups.setValueGroup import setValueGroup
from SmartHome.schemas.base import FunctionRespons, TypeRespons
from typing import List

router_groups = APIRouter(
    prefix="/api/group",
    tags=["group"],
    responses={404: {
        "description": "Not found"
    }},
)


@router_groups.get("/all", response_model=List[GroupSchema])
async def get_group(auth_data: dict = Depends(token_dep)):
    groups = []
    for item in Groups.all():
        groups.append(item)
    return groups


@router_groups.get("/get/{name}", response_model=GroupSchema)
async def get_group(name: str, auth_data: dict = Depends(token_dep)):
    return Groups.get(name)
Exemplo n.º 30
0
from fastapi import APIRouter

from app.api.endpoints import (
    employee,
    owner,
    owner_token,
    reparation_detail,
    root,
    vehicle,
    vehicle_x_owner,
)

api_router = APIRouter()
api_router.include_router(root.router)
api_router.include_router(employee.router, prefix="/employees", tags=["employees"])
api_router.include_router(owner.router, prefix="/owners", tags=["owners"])
api_router.include_router(vehicle.router, prefix="/vehicles", tags=["vehicles"])
api_router.include_router(
    vehicle_x_owner.router, prefix="/vehicles-x-owners", tags=["vehicles-x-owners"]
)
api_router.include_router(reparation_detail.router, prefix="/details", tags=["details"])
api_router.include_router(
    owner_token.router, prefix="/owner-tokens", tags=["owner-tokens"]
)