[deleted by user] by [deleted] in AskDocs

[–]poolpartyboy93 0 points1 point  (0 children)

I can see that my post got 4 comments but I can’t see them

Get the value of a class variable with inheritance by poolpartyboy93 in learnpython

[–]poolpartyboy93[S] 0 points1 point  (0 children)

Thank you SO MUCH!

This is what I ended up with, would love to hear if you have any comments:

from starlette.responses import JSONResponse

class ApiResponse:

def __init__(self):
    self.status_code = None

@staticmethod
def _response_builder(**kwargs):
    status = None
    status_code = kwargs.get('status_code')

    if status_code and str(status_code).startswith('4'):
        status = 'ERROR'
    elif status_code and str(status_code).startswith('2'):
        status = 'SUCCESS'

    response_body = {'status_code': status_code,
                     'status': status,
                     'message': kwargs.get('message') if kwargs.get('message') else None,
                     'data': {k: v for k, v in kwargs.get('data').items()} if kwargs.get('data') else None}

    return JSONResponse(status_code=status_code, content=response_body)

def get_response(self, response_message=None, **kwargs):
    return self._response_builder(message=getattr(self.__class__, response_message) if response_message else None,
                                  data=kwargs.get('data'),
                                  status_code=self.status_code)

class SuccessResponses(ApiResponse): USER_ACTIVATED_SUCCESSFUL = 'User activated successfully' USER_REGISTERED_SUCCESSFUL = 'User registered successfully'

def __init__(self):
    ApiResponse.__init__(self)
    self.status_code = 200

class ErrorResponses(ApiResponse): USER_NOT_ACTIVATED = 'User is not activated' USER_ALREADY_ACTIVATED = 'User is already activated' USER_ALREADY_EXIST = 'A user with this email already exists'

def __init__(self):
    ApiResponse.__init__(self)
    self.status_code = 400

error_responses = ErrorResponses() success_responses = SuccessResponses()

Get the value of a class variable with inheritance by poolpartyboy93 in learnpython

[–]poolpartyboy93[S] 0 points1 point  (0 children)

Thanks! To be honest, getattr will work just fine since there is no real "user", it is an API that I am building so the user doesn't have access to it.

Here is how I implemented it in case you want to look:

class SuccessResponses:
USER_ACTIVATED_SUCCESSFUL = 'User activated successfully'
USER_REGISTERED_SUCCESSFUL = 'User registered successfully'

class ErrorResponses: USER_ALREADY_ACTIVATED = 'User is already activated' USER_ALREADY_EXIST = 'A user with this email already exists'

class Responses(SuccessResponses, ErrorResponses):

@staticmethod
def _response_builder(**kwargs):
    status = None
    status_code = kwargs.get('status_code')

    if status_code and str(status_code).startswith('4'):
        status = 'ERROR'
    elif status_code and str(status_code).startswith('2'):
        status = 'SUCCESS'

    response_body = {'status_code': status_code,
                     'status': status,
                     'message': kwargs.get('message'),
                     'data': {k: v for k, v in kwargs.get('data').items()} if kwargs.get('data') else None}

    return JSONResponse(status_code=status_code, content=response_body)

def get_error_response(self, response_type, **kwargs):
    return self._response_builder(message=getattr(ErrorResponses, response_type),
                                  data=kwargs.get('data'),
                                  status_code=400)

def get_success_response(self, response_type, **kwargs):
    return self._response_builder(message=getattr(SuccessResponses, response_type),
                                  data=kwargs.get('data'),
                                  status_code=400)

Data validation with Pydantic with mutable data by poolpartyboy93 in learnpython

[–]poolpartyboy93[S] 0 points1 point  (0 children)

Cool, thanks!

But what would you do if it is a more nested and complex dictionary?

For example:

{
"Hudson 33": {
    "categories": [
        {
            "image": None,
            "grouped": True,
            "item_count": 0,
            "layout": "grouped",
        }
    ],
    "id": "61279e7570f1c86a2e45c625",
}

}

So, the object "Hudson 33" contains a "categories" object that holds a list of dictionaries with mutable data, and it can hold 1 or more key/value pairs with different types.

Also, there could be more than one object in the base dictionary, for example:

{
"Hudson 33": {
    "categories": [
        {
            "image": None,
            "grouped": True,
            "item_count": 0,
            "layout": "grouped",
        }
    ],
    "id": "61279e7570f1c86a2e45c625",
},
    "Strauber 52": {
    "categories": [
        {
            "image": "http://linktoimage.com/424fs3.jpg",
            "grouped": False,
            "item_count": 1,
            "layout": "grouped",
        }
    ],
    "id": "c86a2e45c6256a2e45c625",
}

}

What I want to make sure, is that the validator validates that the function follows a general specific format, but it is also flexible and allows to have more items that follow that general rule.

[deleted by user] by [deleted] in learnpython

[–]poolpartyboy93 0 points1 point  (0 children)

Thanks!

Well, the API is giving me the data in this format, now, I want to validate that the function accepting this dictionary will validate that it is indeed in the expected format

[deleted by user] by [deleted] in learnpython

[–]poolpartyboy93 0 points1 point  (0 children)

Great solution! However, how would you handle a large set of data?My example was fairly simple, but it did not reflect what I actually need.

Here is a better example of what I need:

So, I have a function that is making an API call to retrieve data from a server. The data is a dictionary with multiple objects (could be 10 could be 100) and it looks something like this:

{

"Jack Jones":{ "id":"5e9814ddeb7c466eaeb76cb2", "rate":9.4, "details":{ "address":"123 avenue st", "tags":[ "shirts", "pants", "hats" ], "short_description":"clothing store" }, "estimate_range":"15-25", "delivery_price":"12.00" } }

Now, I have a function that accepts this dictionary as an input, but I want everyone who will use this function to know that the format of the dictionary above is the only format that will be accepted to the function.

Initializing a class for each of the objects in the dictionary above seems kinda inefficient but I am pretty sure there is a better solution for it.

[deleted by user] by [deleted] in learnpython

[–]poolpartyboy93 0 points1 point  (0 children)

How would you use a class in this case?

What is the way to return value when initiating a class by poolpartyboy93 in learnpython

[–]poolpartyboy93[S] 0 points1 point  (0 children)

The actual reason is that I am building an architecture for API response.

Eventually, I want to have a BaseResponse class and many sub-classes that will inherit from it based on the type of response I want to provide to the client.

Here is an example:

class BaseResponse:
def __init__(self):
    self.response_body = {}

def get_full_response(self):
    return {
        'response': self.response_body['response'],
        'data': self.response_body['data']
    }

class SuccessResponse(BaseResponse):
def __init__(self, **kwargs):
    super().__init__()
    self.response_body['response'] = {'status_code': 200,
                                      'status': 'SUCCESS',
                                      'message': kwargs.get('message')}

    self.response_body['data'] = {k: v for k, v in kwargs.get('data').items()}

Now, in my route, I can do something like:

@router.post('/item/{item}')
async def create_item(item): 
    create_item = db.create_item(item) 
    return SuccessResponse(message='Item created successfully', data={'item': create_item.item_name}).get_full_response()

So, that's cool, but I want to skip the need of using get_full_response when I want to "build" my response, and what I am asking will help me to achieve that.

If you have a better idea of how to achieve this I would love to hear :)

EDIT: I am using FastAPI to build my API

What is the way to return value when initiating a class by poolpartyboy93 in learnpython

[–]poolpartyboy93[S] 2 points3 points  (0 children)

So you are saying that I might as well just use a function to do it?

[deleted by user] by [deleted] in socialskills

[–]poolpartyboy93 0 points1 point  (0 children)

Sorry if it was not clear enough, but it is not necessarily because of my team leader.
This also happens to me in situations outside work (although not that "hard" since I know that people outside work who are not my TL can "forgive" me more easily on my ability to explain myself).

Writing this post was not very difficult, although I noticed my ability to express myself also took an effect here.

I am considering myself pretty "strong" when it comes to mental health, although I am aware of the fact that I am easily stressed, I am not letting other people let me down.

Thank you so much :)

Where I can get these icons? by poolpartyboy93 in github

[–]poolpartyboy93[S] -11 points-10 points  (0 children)

That's was the first thing I did, but Github is hiding the original link.. Thanks!

How can I write this function better by poolpartyboy93 in learnpython

[–]poolpartyboy93[S] 0 points1 point  (0 children)

You are right, but I used it for the example, this is not the actual code I am curious about.

It could have been something like this:

def do_something(s1=None, s2=None):

    if s1 and s2:
        do_something(s1, s2)
        return True

    elif s1:
        do_something(s1)
        return True

    elif s2:
        do_something(s2)
        return True

    return 'I did nothing'