negadive

negadive

Member Since 2 years ago

PT Talenta Informasi Teknologi, Semarang, Jawa Tengah

Experience Points
1
follower
Lessons Completed
4
follow
Lessons Completed
26
stars
Best Reply Awards
22
repos

789 contributions in the last year

Pinned
⚡ Mengirim data row terakhir pada google spreadsheet melalui telegram bot
Activity
Oct
22
2 days ago
Activity icon
fork

negadive forked freeCodeCamp/boilerplate-npm

⚡ A boilerplate for the freeCodeCamp curriculum.
negadive Updated
fork time in 2 days ago
Oct
20
4 days ago
Activity icon
created branch

negadive in negadive/neonime-cli create branch add-requirement-list

createdAt 3 days ago
Activity icon
fork

negadive forked sayahafidz/neonime-cli

⚡ script buat donwload anime dari neonime
negadive Updated
fork time in 3 days ago
Oct
14
1 week ago
Activity icon
issue

negadive issue comment tiangolo/fastapi

negadive
negadive

FastAPI DB Context for service layer

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from fastapi import FastAPI

Description

My current set up is FastAPI, SqlAlchhemy & Alembic, although i am writing the raw SQL myself, pydantic etc, pretty straight forward.

I am trying to implement a DDD type pattern where i have a repository layer which handles all DB actions, and a Service Layer which handles all business logic.

I have basic CRUD routes which communicate directly to my repository layer and all is working. In these methods I am able to successfully use the DB dependency injection. See example code below:

Dependencies

def get_database(request: Request) -> Database:
    return request.app.state._db
def get_repository(Repo_type: Type[BaseRepository]) -> Callable:
    def get_repo(db: Database = Depends(get_database)) -> Type[BaseRepository]:
        return Repo_type(db)
    return get_repo

Example GET by ID Route

@router.get("/{id}/", response_model=TablePub, name="Get Table by id")
async def get_table_by_id(
    id: UUID, table_repo: TableRepository = Depends(get_repository(TableRepository))
) -> TableInDB:
    table = await table_repo.get_table_by_id(id=id)
    if not table:
        raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail="No Table found with that id.")
    return table

Corresponding Repository

from databases import Database

class BaseRepository:
    def __init__(self, db: Database) -> None:
        self.db = db

class TableRepository(BaseRepository):

    async def get_table_by_id(self, *, id: UUID) -> TableInDB:
        table = await self.db.fetch_one(
            query=GET_TABLE_BY_ID_QUERY, 
            values={"id": id},
        )
        if not table:
            return None
        return TableInDB(**table)

Now I want to start doing some more complex operations and want to add a service layer to house all of the business logic.

What is the correct way to structure this so that i can reuse the repositories that i have already written? For example, i want to return all Sales for a Table, but i need to get the table number from the DB first before i can query the Sales Table. The route requires table_id to be passed in as a param -> service layer, where i fetch the table by ID (Using existing repo) -> from that object, get the table number, then do a request to an external API that requires the table number as a param.

What I have so far:

Route

@router.get("/{table_id}", response_model=SalesPub, name="Get Sale Entries by table id")
async def get_sales_by_table_id(
    table_id: UUID = Path(..., title="ID of the Table to get Sales Entries for")):
    response = await SalesService.get_sales_from_external_API(table_id=table_id)
    return response

Service Layer 'SalesService'

async def get_sales_from_external_API(
        table_id: UUID, 
        table_repo: TableRepository = Depends(get_repository(TableRepository))
        ) -> TableInDB:
        table_data = await table_repo.get_table_by_id(id=table_id)
        if table_data is None:
            logger.info(f"No table with id:{table_id} could not be found")
        table_number = table_data.number
        client_id = table_data.client_id
        
        sales = await salesGateway.call_external_API(table_number, client_id)
        return sales

The code brakes here table_data = await table_repo.get_table_by_id(id=table_id)

With an error AttributeError: 'Depends' object has no attribute 'get_table_by_id'

What i don't understand is that the code is almost identical to the route method that can get the table by ID? The depends object TableRepository does have a get_table_by_id method. What is it that i'm doing incorrectly, and is this the best way to split up business logic from database actions?

Thanks in advance

Operating System

macOS

Operating System Details

No response

FastAPI Version

0.55.1

Python Version

3.8

Additional Context

No response

negadive
negadive

you didnt put Depends(get_repository(TableRepository)) inside route function params, so its returning instance of Depends instead of processing the get_repository(TableRepository)

Activity icon
issue

negadive issue comment bellshade/Python

negadive
negadive

try except

dalam koding try except diharap tidak menggunakan

  • operator input
  • tidak langsung except menggunakan seperti contoh dibawah ini
except Exception as e:
 print("catch semua error ", e)
negadive
negadive

@slowy07 #56 udah cukup menjelaskan tentang try...except

Activity icon
issue

negadive issue comment yuval9313/FastApi-RESTful

negadive
negadive

[QUESTION]How to operate Swagger?

image How do I write comments in Swegger?

Activity icon
issue

negadive issue comment tiangolo/fastapi

negadive
negadive

OpenAPI model not compliant with anyOf

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from typing import Union, Tuple

from fastapi import FastAPI
from pydantic import BaseModel, StrictFloat, StrictInt

app = FastAPI()


class Foo(BaseModel):
    operand: Union[Tuple[StrictFloat, StrictFloat], Tuple[StrictInt, StrictInt]]


@app.get("/")
def foo(request: Foo):
    return "hello"


app.openapi()

Description

When running app.openapi() I get the following error:

Traceback (most recent call last):
  File "foo.py", line 19, in <module>
    app.openapi()
  File "/Users/nrushton/Library/Caches/pypoetry/virtualenvs/egress-Y6TME6Xy-py3.8/lib/python3.8/site-packages/fastapi/applications.py", line 136, in openapi
    self.openapi_schema = get_openapi(
  File "/Users/nrushton/Library/Caches/pypoetry/virtualenvs/egress-Y6TME6Xy-py3.8/lib/python3.8/site-packages/fastapi/openapi/utils.py", line 410, in get_openapi
    return jsonable_encoder(OpenAPI(**output), by_alias=True, exclude_none=True)  # type: ignore
  File "pydantic/main.py", line 406, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 3 validation errors for OpenAPI
components -> schemas -> Foo -> properties -> operand -> anyOf -> 0 -> items
  value is not a valid dict (type=type_error.dict)
components -> schemas -> Foo -> properties -> operand -> anyOf -> 1 -> items
  value is not a valid dict (type=type_error.dict)
components -> schemas -> Foo -> $ref
  field required (type=value_error.missing)

This became an issue for us when upgrading from 0.65.3 to 0.69

Operating System

macOS

Operating System Details

No response

FastAPI Version

0.69

Python Version

3.8.2

Additional Context

I delved into the code a little bit and it seems the change from anyOf: Optional[List[Any]] to anyOf: Optional[List["Schema"]] in fastapi.openapi.models.Schema seems to be the cause.

No response

negadive
negadive

this is the same issue with #3254

the one caused the ValidationError is multiple types inside Tuple

Tuple[StrictFloat, StrictFloat]

which causing openapi.components.schemas.<Schema>.properties.tuple.items become list(expecting dict)

the other way is

I think that you can represent your model like this class BuggyModel(BaseModel): tuple: List[int] = Field(... , max_items=4 , min_items=4)

Originally posted by @rodrigoga799 in https://github.com/tiangolo/fastapi/issues/3254#issuecomment-844569862

started
started time in 1 week ago
Oct
13
1 week ago
push

negadive push negadive/resume

negadive
negadive

exclude paths on action trigger

commit sha: 50c7bb87697195fba946637b8571fb52d4e05155

push time in 1 week ago
Oct
12
1 week ago
push

negadive push negadive/resume

negadive
negadive

fix theme name

  • change source to forked repo

commit sha: cc7dc01494022d647c34cf3e37ed0b6116d61753

push time in 1 week ago
Activity icon
delete

negadive in negadive/resume delete branch add-workflow

deleted time in 1 week ago
Activity icon
published release

negadive in negadive/resume create published release

createdAt 1 week ago
Activity icon
created tag

negadive in negadive/resume create tag v0.0.3

createdAt 1 week ago
Activity icon
published release

negadive in negadive/resume create published release

createdAt 1 week ago
Activity icon
created tag

negadive in negadive/resume create tag v0.0.2

createdAt 1 week ago
Activity icon
created tag

negadive in negadive/resume create tag v0.0.1

createdAt 1 week ago
Activity icon
created branch

negadive in negadive/resume create branch add-workflow

createdAt 1 week ago
Activity icon
fork

negadive forked houtianze/jsonresume-theme-stackoverflow-ibic

⚡ Stack Overflow theme for JSON Resume
negadive Updated
fork time in 1 week ago
Oct
11
1 week ago
push

negadive push negadive/resume

negadive
negadive

update resume

  • ganti routing untuk pages

commit sha: 6f0c2b521427a6e913e071e76cab1edbf4dfe8a0

push time in 1 week ago
Activity icon
fork

negadive forked phoinixi/jsonresume-theme-stackoverflow

⚡ Stack Overflow theme for JSON Resume
negadive Updated
fork time in 1 week ago
Previous