### Development Environment Setup and Testing Source: https://github.com/mstuttgart/brazilcep/blob/develop/README.md Standard commands for cloning the repository, installing dependencies, and running quality assurance checks including tests and linting. ```bash # Clone the repository git clone https://github.com/mstuttgart/brazilcep.git cd brazilcep # Install dependencies make setup # Run tests make test # Run linting make lint # Run all checks make check ``` -------------------------------- ### Setup Development Environment Source: https://github.com/mstuttgart/brazilcep/blob/develop/docs/source/contributing.md Commands to initialize a Python virtual environment and install project dependencies using the provided Makefile. ```shell $ virtualenv -p python3 .venv $ source .venv/bin/activate $ make setup ``` -------------------------------- ### Select Alternative Web Services for CEP Queries Source: https://github.com/mstuttgart/brazilcep/blob/develop/docs/source/user/quickstart.md Demonstrates how to specify a different provider API (such as APICEP, VIACEP, or OPENCEP) when performing a lookup by passing the WebService enum to the query function. ```python from brazilcep import get_address_from_cep, WebService get_address_from_cep('37503-130', webservice=WebService.APICEP) ``` -------------------------------- ### Configure Proxies for BrazilCEP Requests Source: https://github.com/mstuttgart/brazilcep/blob/develop/docs/source/user/quickstart.md Explains how to route requests through a proxy server by passing a dictionary of proxy URLs to the get_address_from_cep function, following the standard requests library pattern. ```python from brazilcep import get_address_from_cep proxies = { 'https': "00.00.000.000", 'http': '00.00.000.000', } get_address_from_cep('37503-130', proxies=proxies) ``` -------------------------------- ### Perform Asynchronous CEP Requests Source: https://github.com/mstuttgart/brazilcep/blob/develop/docs/source/user/quickstart.md Shows how to use the async_get_address_from_cep function to fetch address data without blocking the main execution thread. This is ideal for high-performance web applications. ```python import asyncio import brazilcep async def main(): address = await brazilcep.async_get_address_from_cep('37503-130') print(address) asyncio.run(main()) ``` -------------------------------- ### Query Address by CEP using BrazilCEP Source: https://github.com/mstuttgart/brazilcep/blob/develop/docs/source/user/quickstart.md Demonstrates how to perform a basic synchronous lookup of address information using a CEP string. The function returns a dictionary containing address details such as street, city, and district. ```python import brazilcep address = brazilcep.get_address_from_cep('37503-130') ``` -------------------------------- ### Install BrazilCEP via Package Managers Source: https://github.com/mstuttgart/brazilcep/blob/develop/README.md Instructions for installing the BrazilCEP library using common Python package managers. ```bash pip install brazilcep ``` ```bash poetry add brazilcep ``` -------------------------------- ### Configure Web Services and Request Options Source: https://github.com/mstuttgart/brazilcep/blob/develop/README.md Advanced usage examples including selecting specific web services, setting request timeouts, and configuring proxies. ```python from brazilcep import get_address_from_cep, WebService # Select specific provider address = get_address_from_cep('37503-130', webservice=WebService.VIACEP) # Set custom timeout address = get_address_from_cep('37503-130', timeout=10) # Configure proxies proxies = {'http': 'http://10.10.1.10:3128', 'https': 'http://10.10.1.10:1080'} address = get_address_from_cep('37503-130', proxies=proxies) ``` -------------------------------- ### Install BrazilCEP Python Library Source: https://context7.com/mstuttgart/brazilcep/llms.txt Installs the BrazilCEP library using pip. This is the first step to using the library in your Python projects. ```bash pip install brazilcep ``` -------------------------------- ### Query Address from CEP Source: https://github.com/mstuttgart/brazilcep/blob/develop/README.md Examples of performing synchronous and asynchronous address lookups using the BrazilCEP library. ```python import brazilcep # Synchronous query address = brazilcep.get_address_from_cep('37503-130') print(address) ``` ```python import asyncio import brazilcep async def main(): address = await brazilcep.async_get_address_from_cep('37503-130') print(address) asyncio.run(main()) ``` -------------------------------- ### Standardized Address Response Format (Python) Source: https://context7.com/mstuttgart/brazilcep/llms.txt Illustrates the standardized dictionary format returned by all BrazilCEP web service adapters. The example shows how to fetch an address and access its individual fields, including CEP, street, district, city, state (UF), and complement. It also demonstrates formatting the address into a full string. ```python import brazilcep from brazilcep import WebService # All services return the same standardized format address = brazilcep.get_address_from_cep('01001-000') # Response structure response_format = { 'cep': str, # Postal code (e.g., '01001-000') 'street': str, # Street name (e.g., 'Praça da Sé') 'district': str, # Neighborhood/district (e.g., 'Sé') 'city': str, # City name (e.g., 'São Paulo') 'uf': str, # State abbreviation (e.g., 'SP') 'complement': str, # Additional info (e.g., 'lado ímpar') } # Access individual fields print(f"Street: {address['street']}") print(f"District: {address['district']}") print(f"City: {address['city']}") print(f"State: {address['uf']}") print(f"CEP: {address['cep']}") print(f"Complement: {address['complement']}") # Format full address string full_address = f"{address['street']}, {address['district']}, {address['city']}-{address['uf']}, CEP: {address['cep']}" print(full_address) # Output: Praça da Sé, Sé, São Paulo-SP, CEP: 01001-000 ``` -------------------------------- ### FastAPI Integration for CEP Lookup (Python) Source: https://context7.com/mstuttgart/brazilcep/llms.txt Shows how to integrate BrazilCEP's asynchronous functionality into a FastAPI web application. This example defines an API endpoint that accepts a CEP, performs an asynchronous lookup using `async_get_address_from_cep`, and returns the address data. It includes error handling for common issues like CEP not found, invalid format, and timeouts, returning appropriate HTTP status codes. ```python # FastAPI integration example from fastapi import FastAPI, HTTPException import brazilcep from brazilcep import WebService from brazilcep.exceptions import CEPNotFound, InvalidCEP, Timeout app = FastAPI() @app.get("/address/{cep}") async def get_address(cep: str): """Endpoint to lookup Brazilian address by CEP.""" try: address = await brazilcep.async_get_address_from_cep( cep, webservice=WebService.OPENCEP, timeout=10 ) return {"success": True, "data": address} except CEPNotFound: raise HTTPException(status_code=404, detail="CEP not found") except InvalidCEP: raise HTTPException(status_code=400, detail="Invalid CEP format") except Timeout: raise HTTPException(status_code=504, detail="Service timeout") ``` -------------------------------- ### GET /address/ Source: https://context7.com/mstuttgart/brazilcep/llms.txt Retrieves detailed address information for a given Brazilian postal code (CEP). ```APIDOC ## GET /address/ ### Description Fetches address details such as street, neighborhood, city, and state associated with the provided CEP. ### Method GET ### Endpoint /address/ ### Parameters #### Path Parameters - **cep** (string) - Required - The 8-digit Brazilian postal code (e.g., '01001000'). ### Request Example GET /address/01001000 ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **data** (object) - Contains address fields: street, neighborhood, city, state, and cep. #### Response Example { "success": true, "data": { "cep": "01001-000", "street": "Praça da Sé", "neighborhood": "Sé", "city": "São Paulo", "state": "SP" } } #### Error Handling - **404 Not Found**: Returned when the provided CEP does not exist. - **500 Internal Server Error**: Returned when an unexpected error occurs during the lookup. ``` -------------------------------- ### GET brazilcep.async_get_address_from_cep Source: https://github.com/mstuttgart/brazilcep/blob/develop/docs/source/api.md Asynchronously fetches the address associated with a given CEP using specified web services. ```APIDOC ## GET brazilcep.async_get_address_from_cep ### Description Asynchronously queries a specified web service to retrieve address information based on the provided CEP. ### Method GET (Async Function Call) ### Parameters #### Arguments - **cep** (str) - Required - The 8-digit Brazilian postal code. - **webservice** (WebService) - Optional - The service to use (OPENCEP, VIACEP, APICEP). Defaults to WebService.OPENCEP. - **timeout** (int) - Optional - Timeout in seconds. Defaults to 5. - **proxies** (dict) - Optional - Proxy configuration dictionary. ### Response #### Success Response - **dict** - A dictionary containing address fields. ### Response Example { "cep": "01001000", "street": "Praça da Sé", "complement": "lado ímpar", "disctric": "Sé", "city": "São Paulo", "uf": "SP" } ``` -------------------------------- ### GET brazilcep.get_address_from_cep Source: https://github.com/mstuttgart/brazilcep/blob/develop/docs/source/api.md Synchronously queries a specified web service to retrieve address information based on the provided CEP. ```APIDOC ## GET brazilcep.get_address_from_cep ### Description Queries a specified web service to retrieve address information based on the provided CEP. Supports customization of timeout and proxy settings. ### Method GET (Function Call) ### Parameters #### Arguments - **cep** (str) - Required - The 8-digit Brazilian postal code. - **webservice** (WebService) - Optional - The service to use (OPENCEP, VIACEP, APICEP). Defaults to WebService.OPENCEP. - **timeout** (int) - Optional - Timeout in seconds. Defaults to 5. - **proxies** (dict) - Optional - Proxy configuration dictionary. ### Response #### Success Response - **dict** - A dictionary containing address fields like cep, street, city, and uf. ### Response Example { "cep": "01001000", "street": "Praça da Sé", "complement": "lado ímpar", "disctric": "Sé", "city": "São Paulo", "uf": "SP" } ``` -------------------------------- ### Query CEP with Fallback Services (Python) Source: https://context7.com/mstuttgart/brazilcep/llms.txt Demonstrates how to use multiple CEP lookup services sequentially, falling back to the next service if one fails. This ensures higher availability by trying different providers like OPENCEP, VIACEP, and APICEP. It includes basic error handling and prints the result or raises an exception if all services fail. ```python from brazilcep import get_address_from_cep, WebService def get_address_with_fallback(cep: str) -> dict: """Try multiple services until one succeeds.""" services = [WebService.OPENCEP, WebService.VIACEP, WebService.APICEP] for service in services: try: return get_address_from_cep(cep, webservice=service, timeout=5) except Exception as e: print(f"{service.name} failed: {e}") continue raise Exception("All services failed") address = get_address_with_fallback('01001-000') print(address) ``` -------------------------------- ### Configure Real API Testing Source: https://github.com/mstuttgart/brazilcep/blob/develop/docs/source/contributing.md Configuration snippet for the .env file to enable tests that interact with the live API. ```ini SKIP_REAL_TEST=False ``` -------------------------------- ### Run Project Tests and Quality Checks Source: https://github.com/mstuttgart/brazilcep/blob/develop/docs/source/contributing.md Commands to execute automated style checks, comprehensive test suites, and coverage reports. ```shell $ make check $ make pre-commit $ make test $ make coverage ``` -------------------------------- ### Handle BrazilCEP Exceptions Source: https://github.com/mstuttgart/brazilcep/blob/develop/README.md Demonstrates how to catch and handle specific exceptions raised during the address lookup process. ```python from brazilcep import get_address_from_cep, exceptions try: address = get_address_from_cep('00000-000') except exceptions.CEPNotFound: print('CEP not found!') except exceptions.InvalidCEP: print('Invalid CEP format!') except exceptions.BrazilCEPException as e: print(f'An error occurred: {e}') ``` -------------------------------- ### Perform Asynchronous Concurrent CEP Lookups Source: https://github.com/mstuttgart/brazilcep/blob/develop/README.md Demonstrates how to use the async_get_address_from_cep function with asyncio.gather to fetch multiple address details concurrently from a web service. ```python 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()) ``` -------------------------------- ### Migrate from PyCEPCorreios to BrazilCEP Source: https://github.com/mstuttgart/brazilcep/blob/develop/docs/source/api.md Demonstrates the import changes and the updated dictionary key structure required when migrating from the legacy PyCEPCorreios library to BrazilCEP. ```python # Old import # import pycepcorreios # New import import brazilcep # New format example address = brazilcep.get_address_from_cep('37503-130') # Returns: {'district': '...', 'cep': '...', 'city': '...', 'street': '...', 'uf': '...', 'complement': '...'} ``` -------------------------------- ### Asynchronous CEP Lookup with BrazilCEP Source: https://context7.com/mstuttgart/brazilcep/llms.txt Illustrates the asynchronous capabilities of BrazilCEP using `async_get_address_from_cep` with `aiohttp`. It covers single CEP lookups, concurrent lookups of multiple CEPs using `asyncio.gather` for performance, and robust error handling for asynchronous operations, including `CEPNotFound` and `ConnectionError`. ```python import asyncio import brazilcep from brazilcep import WebService from brazilcep.exceptions import CEPNotFound, ConnectionError async def lookup_single_cep(): """Basic async CEP lookup.""" address = await brazilcep.async_get_address_from_cep('01001-000') print(f"Address: {address['street']}, {address['city']}-{address['uf']}") return address async def lookup_multiple_ceps(): """Concurrent lookup of multiple CEPs for better performance.""" ceps = ['01001-000', '37503-130', '01310-100', '80010-000'] tasks = [ brazilcep.async_get_address_from_cep(cep, webservice=WebService.VIACEP) for cep in ceps ] results = await asyncio.gather(*tasks, return_exceptions=True) for cep, result in zip(ceps, results): if isinstance(result, Exception): print(f"CEP {cep}: Error - {type(result).__name__}") else: print(f"CEP {cep}: {result['city']}-{result['uf']}") return results async def lookup_with_error_handling(): """Async lookup with comprehensive error handling.""" try: address = await brazilcep.async_get_address_from_cep( '01001-000', webservice=WebService.OPENCEP, timeout=10 ) return address except CEPNotFound: print("CEP not found") except ConnectionError: print("Connection failed") except Exception as e: print(f"Unexpected error: {e}") return None # Run async functions asyncio.run(lookup_single_cep()) asyncio.run(lookup_multiple_ceps()) ``` -------------------------------- ### Migrate from PyCEPCorreios to BrazilCEP Source: https://github.com/mstuttgart/brazilcep/blob/develop/README.md Shows the import statement change required to migrate existing projects from the deprecated PyCEPCorreios library to BrazilCEP. ```python # Old (PyCEPCorreios): from pycepcorreios import get_address_from_cep # New (BrazilCEP): from brazilcep import get_address_from_cep ``` -------------------------------- ### BrazilCEP WebService Enum Usage Source: https://context7.com/mstuttgart/brazilcep/llms.txt Demonstrates how to use the `WebService` enumeration to specify which CEP lookup service to use with the `get_address_from_cep` function. It lists the available services: `OPENCEP` (default), `VIACEP`, and `APICEP`, along with their respective URLs. ```python from brazilcep import get_address_from_cep, WebService # Available web services print(WebService.OPENCEP) # Default service - https://opencep.com print(WebService.VIACEP) # ViaCEP - https://viacep.com.br print(WebService.APICEP) # ApiCEP - https://apicep.com ``` -------------------------------- ### Expose Address Lookup via Flask Endpoint Source: https://context7.com/mstuttgart/brazilcep/llms.txt This snippet demonstrates how to create a synchronous Flask route that accepts a CEP parameter. It utilizes the brazilcep library to fetch address data and returns a standardized JSON response, handling both successful lookups and common error scenarios like CEPNotFound. ```python from flask import Flask, jsonify import brazilcep from brazilcep import CEPNotFound flask_app = Flask(__name__) @flask_app.route('/address/') def flask_get_address(cep): """Flask endpoint for CEP lookup.""" try: address = brazilcep.get_address_from_cep(cep, timeout=5) return jsonify(success=True, data=address) except CEPNotFound: return jsonify(success=False, error="CEP not found"), 404 except Exception as e: return jsonify(success=False, error=str(e)), 500 ``` -------------------------------- ### Execute Specific Tests with Pytest Source: https://github.com/mstuttgart/brazilcep/blob/develop/docs/source/contributing.md Commands to run individual test files or specific test functions within the project. ```shell $ pytest tests/test_apicep.py $ pytest tests/test_apicep.py::test_fetch_address_success ``` -------------------------------- ### Synchronous CEP Lookup with BrazilCEP Source: https://context7.com/mstuttgart/brazilcep/llms.txt Demonstrates how to use the `get_address_from_cep` function to retrieve address details from a Brazilian postal code. It shows basic usage with the default OpenCEP service, specifying alternative services like ViaCEP and ApiCEP, configuring timeouts and proxies, and handling potential exceptions like `CEPNotFound`, `InvalidCEP`, and `Timeout`. ```python import brazilcep from brazilcep import WebService from brazilcep.exceptions import CEPNotFound, InvalidCEP, Timeout # Basic usage with default OpenCEP service address = brazilcep.get_address_from_cep('01001-000') print(address) # Output: # { # 'district': 'Sé', # 'cep': '01001-000', # 'city': 'São Paulo', # 'street': 'Praça da Sé', # 'uf': 'SP', # 'complement': 'lado ímpar' # } # Using ViaCEP service with timeout address = brazilcep.get_address_from_cep( '37503130', # CEP without formatting also works webservice=WebService.VIACEP, timeout=10 ) # Using ApiCEP service with proxy configuration proxies = { 'https': 'http://10.10.1.10:3128', 'http': 'http://10.10.1.10:3128', } address = brazilcep.get_address_from_cep( '01310-100', webservice=WebService.APICEP, timeout=5, proxies=proxies ) # Error handling try: address = brazilcep.get_address_from_cep('99999-999') except CEPNotFound: print("CEP not found in the database") except InvalidCEP: print("Invalid CEP format provided") except Timeout: print("Request timed out") ``` -------------------------------- ### Fetch address by CEP in Python Source: https://github.com/mstuttgart/brazilcep/blob/develop/docs/source/api.md Functions to retrieve address information from a CEP string. Supports synchronous and asynchronous execution with configurable web services, timeouts, and proxy settings. ```python from brazilcep import get_address_from_cep, WebService # Synchronous call address = get_address_from_cep("01001000", webservice=WebService.VIACEP) print(address) ``` ```python from brazilcep import async_get_address_from_cep, WebService # Asynchronous call address = await async_get_address_from_cep("01001000", webservice=WebService.VIACEP) print(address) ``` -------------------------------- ### Query Address by CEP using BrazilCEP Source: https://github.com/mstuttgart/brazilcep/blob/develop/docs/source/index.md Demonstrates how to retrieve address information from a given CEP string. The function returns a dictionary containing details like district, city, street, and state. ```python import brazilcep address = brazilcep.get_address_from_cep('37503-130') print(address) ``` -------------------------------- ### Handle BrazilCEP Exceptions Gracefully (Python) Source: https://context7.com/mstuttgart/brazilcep/llms.txt Provides a robust function for looking up CEPs while handling various specific exceptions raised by the BrazilCEP library. It catches common errors like invalid CEP format, CEP not found, rate limiting, timeouts, and network issues, printing informative messages for each. It also includes a general catch for any other BrazilCEP-specific errors. ```python from brazilcep import get_address_from_cep from brazilcep.exceptions import ( BrazilCEPException, # Base exception class InvalidCEP, # Invalid CEP format CEPNotFound, # CEP not in database BlockedByFlood, # Rate limited by API ConnectionError, # Network connection issues HTTPError, # HTTP protocol errors URLRequired, # Invalid URL configuration TooManyRedirects, # Too many HTTP redirects Timeout, # Request timeout ) def safe_cep_lookup(cep: str) -> dict | None: """Lookup CEP with comprehensive error handling.""" try: return get_address_from_cep(cep, timeout=5) except InvalidCEP: print(f"Invalid CEP format: {cep}") except CEPNotFound: print(f"CEP {cep} not found in database") except BlockedByFlood: print("Too many requests - rate limited by API") except Timeout: print("Request timed out - try increasing timeout") except ConnectionError: print("Network connection failed") except BrazilCEPException as e: # Catch any other BrazilCEP-specific errors print(f"BrazilCEP error: {e}") return None # Test various scenarios safe_cep_lookup('01001-000') # Valid CEP safe_cep_lookup('') # Empty string - raises InvalidCEP (via ValueError) safe_cep_lookup('99999-999') # Non-existent CEP - raises CEPNotFound ``` -------------------------------- ### Fetch address data from CEP providers Source: https://github.com/mstuttgart/brazilcep/blob/develop/docs/source/api.md Functions to retrieve address information using specific providers. These functions accept a CEP string and optional timeout/proxy configurations, returning a dictionary of address details. ```python from brazilcep import apicep, opencep, viacep # Fetch using different providers address_api = apicep.fetch_address('37503-130') address_open = opencep.fetch_address('37503-130') address_via = viacep.fetch_address('37503-130') ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.