Coder Social home page Coder Social logo

gunyu1019 / ahttp-client Goto Github PK

View Code? Open in Web Editor NEW
5.0 1.0 0.0 165 KB

A framework for easy asynchronous HTTP request calling with decorations

Home Page: https://pypi.org/p/ahttp-client

License: MIT License

Python 100.00%
aiohttp aiohttp-client http-client python

ahttp-client's Introduction

ahttp-client

PyPI - Version PyPI - Downloads PyPI - License

Using @decorator to easily request an HTTP Client
This framework based on aiohttp's http client framework.

Use Annotated Type to describe the elements required in an HTTP request.

Installation

Python 3.10 or higher is required.

pip install ahttp-client

Quick Example

An example is the API provided by the BUS API.

import asyncio
import aiohttp
from ahttp_client import request, Session, Query
from typing import Annotated, Any

loop = asyncio.get_event_loop()


class MetroAPI(Session):
    def __init__(self, loop: asyncio.AbstractEventLoop):
        super().__init__("https://api.yhs.kr", loop=loop)

    @request("GET", "/metro/station")
    async def station_search_with_query(
            self,
            response: aiohttp.ClientResponse,
            name: Annotated[str, Query]
    ) -> dict[str, Any]:
        return await response.json()


async def main():
    async with MetroAPI(loop) as client:
        data = await client.station_search_with_query(name="metro-station-name")
        print(len(data))


loop.run_until_complete(main())

ahttp-client's People

Contributors

gunyu1019 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

ahttp-client's Issues

[Feat] Support Pydantic Model

Describe the new feature

Support Pydantic data model at wrapper

TODO

  • Add detect function to validate model

Addition Context

# Example
# ----------
@app.get("/station/<name>")
@Session.single_session("https://api.yhs.kr")
@request("GET", "/bus/station")
async def station_search_with_query(
    session: Session
) -> PydanticModel:
    pass # return validated PydanticModel
``

[Feat] Support Annotated Type

Describe the new feature

Support typing.Annotated for add request component

from async_client_decorator import get, Session, Query
from typing import Annotated

@Session.single_session("https://base_url")
@get("/")
async def request(response: aiohttp.ClientResponse, parameter: Annotated[str, Query]):
    ...

For convenience, support Union Type(Multiple Type) at request component.

from async_client_decorator import get, Session, Query
from typing import Annotated

@Session.single_session("https://base_url")
@get("/")
async def request(response: aiohttp.ClientResponse, parameter: str | Query):
    ...

TODO

  • Support annotated type at _request method

Addition Context

[Bug] Can't accept multiple types of return annotation

Describe the bug

The return type of a method decorated with _request method cannot support union type

To Reproduce

Set return annotation of the request method to Union Type.

import aiohttp
from async_client_decorator import *

class TSession(Session):

    def __init__(self, api_key: str):
        self.api_key = api_key
        super().__init__(
            base_url="https://based_url/",
            headers={
                "Authorization": "Bearer {0}".format(self.api_key),
            }
        )

    @get("/{block_id}/")
    async def retrieve_block_children(
            self,
            response: aiohttp.ClientResponse,
            block_id: Path | str
    ) -> list[block.BLOCKS] | None: # Casued Issue
        pass

Expected behavior

Nothing, only success compile.

Actual Results

Cuased compile error

Traceback (most recent call last):
  File "%CONSOLE_PATH%", line 367, in runcode
    loop.run_until_complete(coro)
  File "C:\Program Files\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "<input>", line 3, in <module>
  File "%PROJECT_PATH%\venv_p\Lib\site-packages\async_client_decorator\request.py", line 161, in wrapper
    issubclass(signature.return_annotation, aiohttp.ClientResponse)
TypeError: issubclass() arg 1 must be a class

Device Info

Software:

  • OS: Windows 11 23H2 (22631.2861)
  • IDE: PyCharm 2023.2.1 (Professional Edition)
  • Python: 3.11

Hardware:

  • CPU: AMD Ryzen 3800X 3.90GHz
  • RAM: 32GB
  • GPU: Nvdia RTX 2060 Super

Additional context

[Fix] Incorrect body type, when used Generic Type

Describe the bug

Except TypeError, when generic type used in method

...
@Session.single_session("BASE_URL")
@request("GET", "/")
async def test_method(
    session: Session, response: aiohttp.ClientResponse, name: list[str] | Body
                                                                  ^^^^^
) -> list[...]:
    ...

TODO

  • Fix set_body method in component.py

[Feat] Managing wrapper with object

Describe the new feature

Instead of decorating wrapper, use the Request object
To possible to manage pre-call wrapper and post-call wrapper with decorating.

For example

@app.get("/station/<name>")
@Session.single_session("https://api.yhs.kr")
@request("GET", "/bus/station")
async def station_search_with_query(
    session: Session, response: aiohttp.ClientResponse, name: Query | str
):
    return await response.json()

# If need to manage requests before request HTTP Client
@station_search_with_query.before_call
async def before_call( ... ):
    pass

TODO

  • Objectify requests.py
  • Add before_call, after_http_call and after_call method
    • before_call decorating function (For dynamic request component)
    • after_http_call decorating function (To edit parameter, for wrapper)
    • after_call decorating function (Success API Called)
  • Add method for session (object) - request (object)

Addition Context

This release may be a major update. (v1.0.0)

[Fix] Support Union Type at return annotation

Describe the bug

The return type of a method decorated with _request method cannot support union type

Original Issue

  • closed #3

TODO

  • Support Union Type at return annotation

Addition Context

This issue occurred in File reqeusts.py, line 161, in wrapper ( # )

[Feat] Support Custom Name at Header, Parameter or Path

Describe the new feature

Support Custom Name at Header, Parameter or Path.
According to PEP rules, function parameter name must be snake_case.
If API parameter name is camel case, it violates the PEP rules

TODO

Not Started

Addition Context

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.