Extension¶
A Extension page describes features that are outside the scope of ahttp_client’s native functionality but may be helpful for development.
Mulitple Hooking¶
A decorator method that hook mulitple methods in a HTTP request. In normal condition, an HTTP request can only have one hooking: before the request, and after the request.
- @multiple_hook(hook, index)¶
Use this method, if more than one pre-invoke hooks or post-invoke hooks need.
- Parameters:
hook – Contains the decorator function used for hooking. This can be RequestCore.before_hook() or RequestCore.after_hook().
index (Optional[int]) – Order of invocation in invoke-hook
Example
1class MetroAPI(Session): 2 def __init__(self, loop: asyncio.AbstractEventLoop): 3 super().__init__("https://api.yhs.kr", loop=loop) 4 5 @request("GET", "/metro/station") 6 async def station_search_with_query( 7 self, 8 response: aiohttp.ClientResponse, 9 name: Query | str 10 ) -> dict[str, Any]: 11 return await response.json() 12 13 @multiple_hook(station_search_with_query.before_hook) 14 async def before_hook_1(self, obj, path): 15 # Set-up before request 16 return obj, path 17 18 @multiple_hook(station_search_with_query.before_hook) 19 async def before_hook_2(self, obj, path): 20 # Set-up before request 21 return obj, path
Pydantic Response Model¶
Note
pydantic pacakage is required.
pip install pydantic
Returns ths json formatted data from HTTP request, serialized and returned as a class extended with pydantic.BaseModel.
- @pydantic_response_model(model)¶
Create a request method to return a model extended by pydantic.BaseModel
- Parameters:
model (Optional[pydantic.BaseModel]) – A model extended by pydantic.BaseModel to parse JSON. If directly_response enabled and model parameter is empty, model will followed return annotation. However, model parameter is empty, TypeError(“Invalid model type.”) will be raised.
index (Optional[int]) – Order of invocation in invoke-hook. The order is recommended to be last after the status check.
strict (Optional[bool]) – Same feature as parameter of pydantic.BaseModel.model_validate method named strict.
from_attributes (Optional[bool]) – Same feature as parameter of pydantic.BaseModel.model_validate method named from_attributes.
context (Optional[dict[str, Any]]) – Same feature as parameter of pydantic.BaseModel.model_validate method named context.
Warning
This feature is experimental. It might not work as expected. And pydatnic pacakge required.
Examples
>>> class ResponseModel(pydantic.BaseModel): ... name: str ... id: str ... >>> class MetroAPI(Session): ... def __init__(self, loop: asyncio.AbstractEventLoop): ... super().__init__("https://api.yhs.kr", loop=loop) ... ... @pydantic_response_model(ResponseModel) ... @request("GET", "/metro/station") ... async def station_search_with_query( ... self, ... response: aiohttp.ClientResponse, ... name: Query | str ... ) -> ResponseModel: ... pass