Skip to content

Commit

Permalink
feat: first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
paulovitorweb committed Oct 29, 2023
0 parents commit bc7099b
Show file tree
Hide file tree
Showing 42 changed files with 2,337 additions and 0 deletions.
34 changes: 34 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
name: test

on:
push:
branches:
- main
pull_request:
branches:
- main

jobs:
test-lint:
runs-on: ubuntu-latest

steps:
- name: Checkout
uses: actions/checkout@v2

- name: Setup Python
uses: actions/setup-python@v2
with:
python-version: 3.11

- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install poetry
make install
- name: Lint
run: make lint

- name: Test
run: make test
160 changes: 160 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Paulo Freitas

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
18 changes: 18 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Variables
PYTHON = python
POETRY = poetry

# Targets
.PHONY: install test lint check

install:
$(POETRY) install

test:
$(POETRY) run pytest
$(POETRY) run coverage-badge -f -o coverage.svg

lint:
$(POETRY) run ruff check .

check: lint test
81 changes: 81 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<h1 align="center">brasilapi-python</h1>

<div align="center">
<p>
<strong>Um cliente Python assíncrono para o <a href="https://brasilapi.com.br/" target="_blank">Brasil API</a></strong>
</p>
<p>
<img src="https://github.com/paulovitorweb/brasilapi-python/actions/workflows/test.yml/badge.svg"></img>
<img src="./coverage.svg"></img>
</p>
</div>

## Motivação

Fornecer um cliente HTTP assíncrono de alto nível para acessar e desserializar recursos do BrasilAPI.

## Instalação

Com pip:

```
pip install brasilapi
```

Ou com Poetry:

```
poetry add brasilapi
```

## Uso

Este cliente fornece chamadas à API do BrasilAPI dentro de um gerenciador de contexto assíncrono para uma melhor performance.

Por exemplo, o seguinte programa:

```python
import asyncio
from brasilapi import BrasilAPI

async def run():
async with BrasilAPI() as client:
result = await client.ceps.get("89010025")
print(repr(result))

if __name__ == "__main__":
asyncio.run(run())
```

Fornece uma saída igual ou semelhante a:

```python
CEP(cep='89010025', state='SC', city='Blumenau', neighborhood='Centro', street='Rua Doutor Luiz de Freitas Melro', service='correios', location=CEPLocation(type='Point', coordinates={'longitude': '-49.0641133', 'latitude': '-26.9239862'}))
```

Chamadas dentro do gerenciador de contexto utilizam uma mesma sessão que só é fechada ao sair do bloco. Você pode optar por compartilhar o mesmo cliente e sessão durante o tratamento de uma solicitação no seu aplicativo (por exemplo, funciona muito bem retornar uma instância do BrasilAPI como uma dependência do FastAPI) ou enquanto fizer sentido para seu cenário.

## Modelos Pydantic

Os resultados das consultas são instâncias de modelos [Pydantic v2](https://github.com/pydantic/pydantic). Você pode aproveitar a consistência e todas as dicas de tipo.

Os modelos Pydantic foram construídos com base na [documentação oficial do BrasilAPI](https://brasilapi.com.br/docs) e os nomes dos serviços e atributos são iguais aos
da documentação; portanto, alguns estão em inglês e outros em português. Excetuam-se mudanças de `camelCase` para `snake_case`. Mas você pode usar seu próprio modelo Pydantic:

```python
import asyncio
from pydantic import BaseModel, Field
from brasilapi import BrasilAPI

class CustomDDD(BaseModel):
estado: str = Field(alias="state")
cidades: list[str] = Field(alias="cities")

async def run():
async with BrasilAPI() as client:
ddd = await client.ddd.get("83").with_deserializer_class(CustomDDD)
print(repr(ddd))

if __name__ == "__main__":
asyncio.run(run())
```
3 changes: 3 additions & 0 deletions brasilapi/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from brasilapi.client import BrasilAPI

__all__: tuple[str, ...] = ("BrasilAPI",)
56 changes: 56 additions & 0 deletions brasilapi/client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
from types import TracebackType
from typing import Self, Optional

from brasilapi.http import AsyncHttpClient, DEFAULT_HTTP_CLIENT_CLASS
from brasilapi.services.bank import BankService
from brasilapi.services.cep import CEPService
from brasilapi.services.ddd import DDDService
from brasilapi.services.feriado import FeriadoNacionalService
from brasilapi.services.fipe import FipeWrapper


class BrasilAPI:
def __init__(self) -> None:
self.__http_client: AsyncHttpClient = DEFAULT_HTTP_CLIENT_CLASS()

def __enter__(self) -> None:
raise TypeError("Use async with instead")

def __exit__(
self,
exc_type: Optional[type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
pass # pragma: no cover

async def __aenter__(self) -> Self:
return self

async def __aexit__(
self,
exc_type: Optional[type[BaseException]] = None,
exc_value: Optional[BaseException] = None,
exc_traceback: Optional[TracebackType] = None,
) -> None:
await self.__http_client.close()

@property
def banks(self) -> BankService:
return BankService(self.__http_client)

@property
def ceps(self) -> CEPService:
return CEPService(self.__http_client)

@property
def ddd(self) -> DDDService:
return DDDService(self.__http_client)

@property
def feriados(self) -> FeriadoNacionalService:
return FeriadoNacionalService(self.__http_client)

@property
def fipe(self) -> FipeWrapper:
return FipeWrapper(self.__http_client)
10 changes: 10 additions & 0 deletions brasilapi/dto/bank.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from typing import Optional

from pydantic import BaseModel, Field, AliasChoices


class Bank(BaseModel):
ispb: str
name: Optional[str] = Field(default=None)
code: Optional[int]
full_name: Optional[str] = Field(default=None, alias=AliasChoices("fullName", "full_name"))
Loading

0 comments on commit bc7099b

Please sign in to comment.