BrazilCEP

repository·develop·Indexed 42 days ago

https://github.com/mstuttgart/brazilcep

A minimalist Python library for querying Brazilian CEP (Postal Address Code) data. It supports both synchronous and asynchronous workflows via functions like get_address_from_cep and async_get_address_from_cep, providing a unified interface to multiple web services including OpenCEP, ViaCEP, and ApiCEP.

Tokens
7K
Snippets
33
Records
42
Agent score
51%

What's inside BrazilCEP

  1. Install BrazilCEP from source code

    develop

    If you want to install BrazilCEP from the source code (for example, to use the latest development version or for contributing), follow these steps:

    1. Clone the repository or download the tarball.
    2. Navigate into the project directory.
    3. Install the package in editable mode using pip install -e ..
    git clone https://github.com/mstuttgart/brazilcep.git
    cd brazilcep
    pip install -e .
  2. Make asynchronous CEP requests

    develop

    For version >= 7.0.0, you can use async_get_address_from_cep to perform non-blocking requests. This is ideal for high-responsiveness applications like web services. This function must be awaited.

    import asyncio
    import brazilcep
    
    async def main():
        address = await brazilcep.async_get_address_from_cep('37503-130')
        print(address)
    
    asyncio.run(main())
  3. Quick Start with BrazilCEP

    develop

    BrazilCEP is a minimalist Python library used to query CEP (Postal Address Code) data. It provides a unified interface to search multiple services like ViaCEP, ApiCEP (WideNet), and OpenCEP.

    Starting from version 7.0.0, the library supports both synchronous and asynchronous operations.

    import brazilcep
    
    # Query an address using a CEP string
    address = brazilcep.get_address_from_cep('37503-130')
    print(address)
  4. Migrate from PyCEPCorreios to BrazilCEP

    develop

    BrazilCEP is the successor to PyCEPCorreios. To migrate, follow these three steps:

    1. Update Imports: Change import pycepcorreios to import brazilcep.
    2. Update Result Keys: The keys in the returned dictionary have been translated from Portuguese to English.
      • bairro $\rightarrow$ district
      • cidade $\rightarrow$ city
      • logradouro $\rightarrow$ street
      • complemento $\rightarrow$ complement
      • cep and uf remain the same.
    3. Remove BaseException usage: The BaseException that was present in the old library has been removed.
    ### Step 1: Update Imports
    # Old
    import pycepcorreios
    # New
    import brazilcep
    
    ### Step 2: Adjust Keys
    # Old format
    {
       'bairro': 'rua abc',
       'cep': '37503130',
       'cidade': 'city ABC',
       'logradouro': 'str',
       'uf': 'str',
       'complemento': 'str',
    }
    
    # New format
    {
       'district': 'rua abc',
       'cep': '37503130',
       'city': 'city ABC',
       'street': 'str',
       'uf': 'str',
       'complement': 'str',
    }
  5. Switch between different WebService providers

    develop

    By default, BrazilCEP uses the OpenCEP service. You can switch to other providers by importing the WebService class and passing the desired provider to the webservice parameter in get_address_from_cep.

    from brazilcep import get_address_from_cep, WebService
    
    # Example using APICEP
    address = get_address_from_cep('37503-130', webservice=WebService.APICEP)
  6. Query a CEP synchronously

    develop

    Use brazilcep.get_address_from_cep(cep) to perform a synchronous lookup. It returns a dictionary containing address details.

    import brazilcep
    
    # Query a CEP
    address = brazilcep.get_address_from_cep('37503-130')
    
    print(address)
    # Output:
    # {
    #     'cep': '37503-130',
    #     'street': 'Rua Geraldino Campista',
    #     'district': 'Santo Antônio',
    #     'city': 'Itajubá',
    #     'uf': 'MG',
    #     'complement': 'até 214/215'
    # }
  7. Query a CEP asynchronously

    develop

    Use brazilcep.async_get_address_from_cep(cep) within an async function to perform asynchronous lookups. This is useful for concurrent operations.

    import asyncio
    import brazilcep
    
    async def main():
        address = await brazilcep.async_get_address_from_cep('37503-130')
        print(address)
    
    asyncio.run(main())
  8. Make a synchronous CEP request

    develop

    Use the get_address_from_cep function to retrieve address information for a specific CEP. The CEP must be provided as a string. The function returns a dict containing the address details.

    import brazilcep
    
    address = brazilcep.get_address_from_cep('37503-130')
    print(address)
    # Output example:
    # {
    #     'district': 'rua abc',
    #     'cep': '37503130',
    #     'city': 'city ABC',
    #     'street': 'str',
    #     'uf': 'str',
    #     'complement': 'str',
    # }
  9. Configure timeouts and proxies

    develop

    To prevent your application from hanging, you can specify a timeout parameter in your requests. You can also configure proxies using a dictionary following the requests library pattern.

    from brazilcep import get_address_from_cep
    
    proxies = {
        'https': '00.00.00.000',
        'http': '00.00.00.000',
    }
    
    # Using proxies and (optionally) a timeout
    address = get_address_from_cep('37503-130', proxies=proxies, timeout=5)
  10. Fetch multiple CEPs concurrently

    develop

    To optimize performance when querying multiple addresses, use the asynchronous API with asyncio.gather to run requests in parallel.

    import asyncio
    from brazilcep import async_get_address_from_cep, WebService, exceptions
    
    async def fetch_multiple_ceps():
        """Fetch multiple CEPs concurrently."""
        ceps = ['37503-130', '01310-100', '20040-020']
    
        tasks = [
            async_get_address_from_cep(cep, webservice=WebService.OPENCEP)
            for cep in ceps
        ]
    
        try:
            addresses = await asyncio.gather(*tasks)
            for cep, address in zip(ceps, addresses):
                print(f"\nCEP {cep}:")
                print(f"  Street: {address['street']}")
                print(f"  City: {address['city']}/{address['uf']}")
        except exceptions.BrazilCEPException as e:
            print(f"Error fetching addresses: {e}")
    
    asyncio.run(fetch_multiple_ceps())