### Install uszipcode Source: https://uszipcode.readthedocs.io/index Instructions on how to install the uszipcode library using pip. ```bash pip install uszipcode ``` -------------------------------- ### Use Different RDBMS Backend (MySQL Example) Source: https://uszipcode.readthedocs.io/01-Usage-Example/index Shows how to use a different RDBMS backend, such as MySQL, by creating a SQLAlchemy engine and passing it to the SearchEngine. This involves downloading the db file, using DBeaver to dump CSV, and loading it into MySQL. ```python import sqlalchemy_mate as sam engine = sam.EngineCreator(username, password, host, port, database)..create_postgresql_pg8000() search = SearchEngine(engine=engine) ``` -------------------------------- ### Host Database Privately Source: https://uszipcode.readthedocs.io/01-Usage-Example/index Demonstrates how to initialize the SearchEngine with a privately hosted SQLite database file by specifying the `download_url` parameter. ```python search = SearchEngine(download_url="https://your-private-store.sqlite") ``` -------------------------------- ### Choosing Database Type Source: https://uszipcode.readthedocs.io/_sources/01-Usage-Example/index.rst Shows how to specify whether to use the 'simple' or 'comprehensive' zipcode database when initializing the SearchEngine. ```python from uszipcode import SearchEngine # use simple zipcode search = SearchEngine( simple_or_comprehensive=SearchEngine.SimpleOrComprehensiveArgEnum.simple ) # use comprehensive zipcode search = SearchEngine( simple_or_comprehensive=SearchEngine.SimpleOrComprehensiveArgEnum.comprehensive ) ``` -------------------------------- ### Install uszipcode Source: https://uszipcode.readthedocs.io/index Instructions for installing the uszipcode package using pip. Includes commands for initial installation and upgrading to the latest version. ```bash $ pip install uszipcode ``` ```bash $ pip install --upgrade uszipcode ``` -------------------------------- ### Get Zipcode Statistics and Demographic Data Source: https://uszipcode.readthedocs.io/01-Usage-Example/index Demonstrates how to initialize the SearchEngine and retrieve zipcode information using either a string or integer representation of the zipcode. The output includes statistics and demographic data for the specified zipcode. ```python from uszipcode import SearchEngine sr = SearchEngine() z = sr.by_zipcode("10001") print(z) z = sr.by_zipcode(10001) print(z) ``` -------------------------------- ### Using Different RDBMS Backends Source: https://uszipcode.readthedocs.io/_sources/01-Usage-Example/index.rst Explains how to use different RDBMS backends like MySQL by creating a SQLAlchemy engine and passing it to the SearchEngine. ```python import sqlalchemy_mate as sam engine = sam.EngineCreator(username, password, host, port, database)..create_postgresql_pg8000() search = SearchEngine(engine=engine) ``` -------------------------------- ### Search by Zipcode Prefix Source: https://uszipcode.readthedocs.io/02-Advanced-Tutorial/index Demonstrates searching for all zipcodes that start with a given prefix. ```python >>> result = search.by_prefix("900") >>> for zipcode in result: ... print(zipcode.zipcode) 90001 90002 90003 ... ``` -------------------------------- ### Range Search Examples Source: https://uszipcode.readthedocs.io/02-Advanced-Tutorial/index Demonstrates how to search for zipcodes within a specified range for attributes like population and population density. These examples show the basic usage of range queries. ```python >>> result = search.by_population(lower=5000, upper=10000) >>> for zipcode in result: ... # do whatever you want... >>> result = search.by_population_density(lower=1000, upper=2000) >>> for zipcode in result: ... # do whatever you want... ``` -------------------------------- ### Basic Zipcode Lookup Source: https://uszipcode.readthedocs.io/_sources/01-Usage-Example/index.rst Demonstrates how to initialize the SearchEngine and retrieve zipcode information using a zipcode string or integer. ```python from uszipcode import SearchEngine sr = SearchEngine() z = sr.by_zipcode("10001") print(z) z = sr.by_zipcode(10001) print(z) ``` -------------------------------- ### SearchEngine Initialization and Database Setup Source: https://uszipcode.readthedocs.io/_modules/uszipcode/search Initializes the SearchEngine with a database file path and download URL. It handles downloading the database if it doesn't exist and sets up the SQLite engine and session. It also determines whether to use simple or comprehensive zipcode data. ```python def __init__(self, db_file_path: typing.Optional[str] = None, download_url: typing.Optional[str] = None, simple_or_comprehensive: SimpleOrComprehensiveArgEnum = SimpleOrComprehensiveArgEnum.simple): self.db_file_path = db_file_path self.download_url = download_url self._download_db_file_if_not_exists() self.engine = sam.EngineCreator().create_sqlite(path=self.db_file_path) self.eng = self.engine self.session = orm.Session(self.engine) self.ses = self.session self.zip_klass: typing.Union[SimpleZipcode, ComprehensiveZipcode] if self.simple_or_comprehensive is self.SimpleOrComprehensiveArgEnum.simple: self.zip_klass = SimpleZipcode elif self.simple_or_comprehensive is self.SimpleOrComprehensiveArgEnum.comprehensive: self.zip_klass = ComprehensiveZipcode ``` -------------------------------- ### Basic Zipcode Search with SearchEngine Source: https://uszipcode.readthedocs.io/02-Advanced-Tutorial/index Demonstrates initializing the SearchEngine, performing a search by zipcode, and accessing attributes of the returned zipcode object. This example uses SearchEngine directly. ```python >>> from uszipcode import SearchEngine, SimpleZipcode, ComprehensiveZipcode >>> search = SearchEngine() >>> zipcode = search.by_zipcode(10030) >>> zipcode.zipcode # access attributes '10030' >>> zipcode.major_city 'New York' >>> zipcode.state_abbr 'NY' >>> zipcode.population 26999 ``` -------------------------------- ### Private Database Hosting Source: https://uszipcode.readthedocs.io/_sources/01-Usage-Example/index.rst Provides instructions on how to host the uszipcode database file privately by downloading the SQLite database and using the `download_url` parameter. ```python search = SearchEngine(download_url="https://your-private-store.sqlite") ``` -------------------------------- ### Basic Usage Example Source: https://uszipcode.readthedocs.io/_modules/uszipcode/model Demonstrates the fundamental usage of the uszipcode library, likely involving searching for zip codes and retrieving associated information. ```python from uszipcode import SearchEngine search = SearchEngine() # Example: Find zip codes by city zipcodes = search.by_city('New York') for zipcode in zipcodes: print(zipcode) # Example: Find zip codes by zip code zipcode_info = search.by_zipcode('10001') print(zipcode_info) # Example: Find zip codes by radius zipcodes_in_radius = search.by_radius(lat=40.7128, lng=-74.0060, radius=5, returns=5) for zipcode in zipcodes_in_radius: print(zipcode) ``` -------------------------------- ### Select Simple vs Comprehensive Zipcode Database Source: https://uszipcode.readthedocs.io/01-Usage-Example/index Shows how to choose between the 'SimpleZipcode' and 'ComprehensiveZipcode' databases when initializing the SearchEngine. The comprehensive database offers more data but is larger, while the simple database is smaller and faster. ```python from uszipcode import SearchEngine # use simple zipcode search = SearchEngine( simple_or_comprehensive=SearchEngine.SimpleOrComprehensiveArgEnum.simple ) # use comprehensive zipcode search = SearchEngine( simple_or_comprehensive=SearchEngine.SimpleOrComprehensiveArgEnum.comprehensive ) ``` -------------------------------- ### Filtering by Zipcode Type Source: https://uszipcode.readthedocs.io/01-Usage-Example/index Demonstrates how to retrieve specific types of zipcodes, such as PO Box zipcodes, or to include all zipcode types in a search. ```python from uszipcode import SearchEngine, ZipcodeTypeEnum search = SearchEngine() # return all zipcode type res = search.by_coordinates(..., zipcode_type=None) # return only PO box type res = search.by_coordinates(..., zipcode_type=ZipcodeTypeEnum.PO_Box) ``` -------------------------------- ### Search by City Source: https://uszipcode.readthedocs.io/02-Advanced-Tutorial/index Demonstrates searching for zipcodes by city name. It also includes an example of using an internal method to find correct city names with fuzzy matching. ```python >>> res = search.by_city("vienna") >>> zipcode = res[0] >>> zipcode.major_city 'Vienna' >>> search.find_city("phonix", bes_match=True) ['Phoenix'] >>> search.find_city("kersen", state="kensas", best_match=False) ['Nickerson'] ``` -------------------------------- ### Basic Zipcode Lookup and Data Access Source: https://uszipcode.readthedocs.io/01-Usage-Example/index Demonstrates how to initialize the SearchEngine, retrieve zipcode information by a specific zipcode, and access its attributes or convert it to a list or dictionary. It also shows how to convert the zipcode object to a JSON string. ```python from uszipcode import SearchEngine search = SearchEngine(simple_zipcode=True) # set simple_zipcode=False to use rich info database zipcode = search.by_zipcode("10001") print(zipcode) print(zipcode.values()) # to list print(zipcode.to_dict()) # to dict print(zipcode.to_json()) # to json ``` -------------------------------- ### Sorting Search Results Source: https://uszipcode.readthedocs.io/_sources/01-Usage-Example/index.rst Demonstrates how to sort search results by any field, including distance from coordinates when performing location-based queries. ```python # Find top 10 population zipcode res = search.by_population(lower=0, upper=999999999, sort_by=Zipcode.population, ascending=False, returns=10) for zipcode in res: # do whatever you want... ``` -------------------------------- ### Search by Coordinates Source: https://uszipcode.readthedocs.io/01-Usage-Example/index Shows how to find zipcodes within a specified radius from given coordinates. The results can be ordered by proximity and limited to a certain number of returns. ```python from uszipcode import SearchEngine search = SearchEngine() # Search zipcode within 30 miles, ordered from closest to farthest result = search.by_coordinates(39.122229, -77.133578, radius=30, returns=5) print(len(result)) # by default 5 results returned for zipcode in result: # do whatever you want... ``` -------------------------------- ### Changing Default Download URL Source: https://uszipcode.readthedocs.io/_sources/01-Usage-Example/index.rst Explains how to specify a custom URL for downloading the zipcode database file, allowing for private storage or alternative hosting. ```python from uszipcode import SearchEngine search = SearchEngine(download_url="https://your-private-storage.sqlite") ``` -------------------------------- ### SearchEngine Data Access Methods Source: https://uszipcode.readthedocs.io/_sources/01-Usage-Example/index.rst Demonstrates retrieving zipcode data and converting it into different formats: a default object representation, a list of values, a dictionary, and a JSON string. ```python from uszipcode import SearchEngine search = SearchEngine(simple_zipcode=True) # set simple_zipcode=False to use rich info database zipcode = search.by_zipcode("10001") print(zipcode) # Default object representation print(zipcode.values()) # Convert to list print(zipcode.to_dict()) # Convert to dictionary print(zipcode.to_json()) # Convert to JSON string ``` -------------------------------- ### Basic Zipcode Search with Zipcode Class Source: https://uszipcode.readthedocs.io/02-Advanced-Tutorial/index Demonstrates initializing the SearchEngine, performing a search by zipcode, and accessing attributes of the returned zipcode object. This example explicitly imports and uses the Zipcode class. ```python >>> from uszipcode import SearchEngine, SimpleZipcode, Zipcode >>> search = SearchEngine() >>> zipcode = search.by_zipcode(10030) >>> zipcode.zipcode # access attributes '10030' >>> zipcode.major_city 'New York' >>> zipcode.state_abbr 'NY' >>> zipcode.population 26999 ``` -------------------------------- ### Search Zipcode by Prefix Source: https://uszipcode.readthedocs.io/_sources/02-Advanced-Tutorial/index.rst Retrieves all zipcodes that start with a given prefix. This is useful for finding zipcodes within a specific geographic area defined by the prefix. ```python >>> result = search.by_prefix("900") >>> for zipcode in result: ... print(zipcode.zipcode) 90001 90002 90003 ... ``` -------------------------------- ### Sorting Search Results Source: https://uszipcode.readthedocs.io/01-Usage-Example/index Explains how to sort search results by any field, including distance from a specified coordinate if the search is location-based. ```python from uszipcode import SearchEngine, Zipcode search = SearchEngine() # Find top 10 population zipcode res = search.by_population(lower=0, upper=999999999, sort_by=Zipcode.population, ascending=False, returns=10) for zipcode in res: # do whatever you want... ``` -------------------------------- ### Search by Population and Land Area Source: https://uszipcode.readthedocs.io/01-Usage-Example/index Illustrates how to find zipcodes based on population or land area ranges. Results can be sorted by these fields in ascending or descending order. ```python from uszipcode import SearchEngine, Zipcode search = SearchEngine() # Find top 10 population zipcode result = search.by_population(lower=0, upper=999999999, sort_by=Zipcode.population, ascending=False, returns=10) # Find top 10 largest land area zipcode res = search.by_landarea(lower=0, upper=999999999, sort_by=Zipcode.land_area_in_sqmi, ascending=False, returns=10) ``` -------------------------------- ### Changing Default Database File Location Source: https://uszipcode.readthedocs.io/_sources/01-Usage-Example/index.rst Illustrates how to set a custom directory for downloading and storing the zipcode database file, useful for environments like AWS Lambda. ```python from uszipcode import SearchEngine search = SearchEngine(db_file_path="/tmp/simple_db.sqlite") ``` -------------------------------- ### Search by Population Source: https://uszipcode.readthedocs.io/_sources/01-Usage-Example/index.rst Finds zipcodes based on population range, allowing sorting by population in ascending or descending order. Returns a specified number of results. ```python # Find top 10 population zipcode result = search.by_population(lower=0, upper=999999999, sort_by=Zipcode.population, ascending=False, returns=10) ``` -------------------------------- ### Change Default Download URL Source: https://uszipcode.readthedocs.io/01-Usage-Example/index Explains how to set a custom URL for downloading the zipcode database file. This allows users to host the database on their own storage or a different CDN. ```python search = SearchEngine(download_url="https://your-private-storage.sqlite") ``` -------------------------------- ### Search by Coordinates Source: https://uszipcode.readthedocs.io/_sources/01-Usage-Example/index.rst Searches for zipcodes within a specified radius of given coordinates, ordered by proximity. By default, it returns the 5 closest zipcodes. ```python from uszipcode import Zipcode # Search zipcode within 30 miles, ordered from closest to farthest result = search.by_coordinates(39.122229, -77.133578, radius=30, returns=5) print(len(result)) # by default 5 results returned for zipcode in result: # do whatever you want... ``` -------------------------------- ### Custom Query with SQLAlchemy Source: https://uszipcode.readthedocs.io/02-Advanced-Tutorial/index Shows how to leverage SQLAlchemy ORM for custom zipcode queries. This example demonstrates building a SQL query to select zipcodes based on specific conditions. ```python >>> import sqlalchemy as sa >>> from uszipcode import SearchEngine, SimpleZipcode >>> search = SearchEngine(simple_zipcode=True) >>> sql = sa.select(SimpleZipcode).where(SimpleZipcode.zipcode=="10001") >>> search.ses.scalar(stmt).one() SimpleZipcode(zipcode="10001", ...) ``` -------------------------------- ### Zipcode Object Comparison and Set Usage with SimpleZipcode Source: https://uszipcode.readthedocs.io/02-Advanced-Tutorial/index Illustrates that SimpleZipcode objects are comparable and hashable, allowing them to be used in sets for uniqueness and sorted. This example focuses on the SimpleZipcode class. ```python >>> bool(SimpleZipcode(zipcode="10030")) True >>> bool(SimpleZipcode()) False >>> SimpleZipcode(zipcode="10030") <= SimpleZipcode(zipcode="10031") True >>> len(set([SimpleZipcode(zipcode="10030"), SimpleZipcode(zipcode="10031")])) 2 ``` -------------------------------- ### Search by Land Area Source: https://uszipcode.readthedocs.io/_sources/01-Usage-Example/index.rst Retrieves zipcodes based on land area, enabling sorting by land area in ascending or descending order. Allows specifying the number of results to return. ```python # Find top 10 largest land area zipcode res = search.by_landarea(lower=0, upper=999999999, sort_by=Zipcode.land_area_in_sqmi, ascending=False, returns=10) ``` -------------------------------- ### Fuzzy City and State Name Search Source: https://uszipcode.readthedocs.io/01-Usage-Example/index Highlights the library's ability to perform fuzzy searches for city and state names, which is tolerant to typos and case/space insensitivity. This is useful for user input in web applications. ```python from uszipcode import SearchEngine search = SearchEngine() # Looking for Chicago and IL, but entered wrong spelling. res = search.by_city_and_state("cicago", "il", returns=999) # only returns first 999 results print(len(res)) # 56 zipcodes in Chicago zipcode = res[0] print(zipcode.major_city) print(zipcode.state_abbr) ``` -------------------------------- ### Advanced Search: Richest Zipcodes Near Silicon Valley Source: https://uszipcode.readthedocs.io/_sources/02-Advanced-Tutorial/index.rst An example of finding the top richest zipcodes near a specific geographic location, sorted by median household income. ```python # Find top 10 richest zipcode near Silicon Valley lat, lng = 37.391184, -122.082235 radius = 100 res = search.find( lat=lat, lng=lng, radius=radius, sort_by=Zipcode.median_household_income, ascending=False, returns=10, ) ``` -------------------------------- ### Change Default Database File Location Source: https://uszipcode.readthedocs.io/01-Usage-Example/index Illustrates how to specify a custom directory for storing the uszipcode database file. This is useful in environments like AWS Lambda where writing to the default home directory might not be permitted. ```python search = SearchEngine(db_file_path="/tmp/simple_db.sqlite") ``` -------------------------------- ### Limit Number of USZipcode Search Results Source: https://uszipcode.readthedocs.io/02-Advanced-Tutorial/index Shows how to use the 'returns' keyword to limit the number of results returned by search methods. Zero means unlimited results. The default limit is 5. Example finds top 10 most populated zipcodes. ```python # Example to find the top 10 most people zipcode, sorted by population: # search.query(..., returns=10, sort_by='population', ascending=False) ``` -------------------------------- ### Using SearchEngine with Context Manager Source: https://uszipcode.readthedocs.io/_sources/02-Advanced-Tutorial/index.rst Shows the recommended way to use the SearchEngine with a context manager, which ensures the database connection is automatically managed and disconnected. ```python from uszipcode import SearchEngine with SearchEngine() as search: zipcode = search.by_zipcode(10030) ``` -------------------------------- ### SearchEngine Initialization and Usage Source: https://uszipcode.readthedocs.io/_modules/uszipcode/search Demonstrates how to initialize the SearchEngine with different configurations and use it as a context manager. The SearchEngine allows querying zipcode data, with options to specify the database type (simple or comprehensive), custom file paths, download URLs, or a SQLAlchemy engine. ```python >>> search = SearchEngine() >>> zipcode = search.by_zipcode("10001") >>> with SearchEngine() as search: ... for zipcode in search.by_coordinates(lat, lng, radius): ... # do what every you want ``` -------------------------------- ### Get City List Property Source: https://uszipcode.readthedocs.io/_modules/uszipcode/search Provides access to the cached list of all available city names. If the cache is not populated, it triggers the `_get_cache_data` method. ```python @property def city_list(self): # pragma: no cover """ Return all available city name. """ if self._city_list is None: self._get_cache_data() return self._city_list ``` -------------------------------- ### Initialize SearchEngine with Big Database Source: https://uszipcode.readthedocs.io/release-history Demonstrates how to initialize the SearchEngine to use the larger database containing richer information. The larger database will be automatically downloaded to the `$HOME/.uszipcode/` directory if it doesn't exist. ```python search = SearchEngine(simple_zipcode=False) ``` -------------------------------- ### Using SearchEngine as a Context Manager Source: https://uszipcode.readthedocs.io/02-Advanced-Tutorial/index Shows how to use the SearchEngine within a 'with' statement for automatic database resource management. This is the recommended approach for ensuring proper connection handling. ```python >>> with SearchEngine() as search: ... zipcode = search.by_zipcode(10030) ``` -------------------------------- ### SearchEngine Class API Documentation Source: https://uszipcode.readthedocs.io/uszipcode/search Provides API documentation for the SearchEngine class, including its constructor parameters, properties, and methods. It details options for database selection, file paths, download URLs, and SQLAlchemy engine integration. ```APIDOC class SearchEngine: __init__( _simple_or_comprehensive: SimpleOrComprehensiveArgEnum = SimpleOrComprehensiveArgEnum.simple, _db_file_path: Optional[str] = None, _download_url: Optional[str] = None, _engine: Optional[sqlalchemy.engine.base.Engine] = None ) Zipcode Search Engine. Parameters: simple_or_comprehensive: Use the simple zipcode db (default) or the comprehensive one with rich info. db_file_path: Path to store the sqlite database file locally. Defaults to ${HOME}/.uszipcode/. download_url: URL to download the sqlite database file from. Useful for private file hosts or fallback. engine: SQLAlchemy engine object for using different backend databases. close(): Close database connection. city_list (property): Return all available city names. state_list (property): Return all available state names. query(): Provides mass options to customize your query. by_zipcode(zipcode: str): Finds zip code information by zip code string. by_coordinates(lat: float, lng: float, radius: int = 10, sort_by: str = SORT_BY_DIST, limit: int = DEFAULT_LIMIT): Finds zip codes within a given radius of coordinates. Note: SearchEngine is not multi-thread safe. Create different instances for each thread. ``` -------------------------------- ### SearchEngine Configuration Options Source: https://uszipcode.readthedocs.io/_modules/uszipcode/search Details the various configuration options available when initializing the SearchEngine. These include specifying the database type (simple or comprehensive), custom database file paths, alternative download URLs for the database, and integrating with existing SQLAlchemy engines. ```python def __init__( self, simple_or_comprehensive: SimpleOrComprehensiveArgEnum = SimpleOrComprehensiveArgEnum.simple, db_file_path: typing.Union[str, None] = None, download_url: typing.Union[str, None] = None, engine: Engine = None, ): # ... initialization logic ... ``` -------------------------------- ### Get State List Property Source: https://uszipcode.readthedocs.io/_modules/uszipcode/search Provides access to the cached list of all available state names (in long format). If the cache is not populated, it triggers the `_get_cache_data` method. ```python @property def state_list(self): # pragma: no cover """ Return all available state name. """ if self._state_list is None: self._get_cache_data() return self._state_list ``` -------------------------------- ### SearchEngine Class Initialization and Usage Source: https://uszipcode.readthedocs.io/uszipcode/search Demonstrates how to initialize the SearchEngine for querying zip code data. It shows basic usage with by_zipcode and context manager usage with by_coordinates. The SearchEngine is not thread-safe and requires separate instances per thread. ```python from uszipcode import SearchEngine # Basic usage search = SearchEngine() zincode = search.by_zipcode("10001") # Context Manager usage # with SearchEngine() as search: # for zipcode in search.by_coordinates(lat, lng, radius): # # do what every you want ``` -------------------------------- ### Zipcode Type Filtering Source: https://uszipcode.readthedocs.io/_sources/01-Usage-Example/index.rst Allows filtering search results by zipcode type, such as 'STANDARD' or 'PO_Box'. Setting zipcode_type to None returns all types. ```python from uszipcode import ZipcodeTypeEnum # return all zipcode type res = sr.by_coordinates(..., zipcode_type=None) # return only PO box type res = sr.by_coordinates(..., zipcode_type=ZipcodeTypeEnum.PO_Box) ``` -------------------------------- ### SearchEngine Context Manager Source: https://uszipcode.readthedocs.io/_sources/02-Advanced-Tutorial/index.rst Illustrates the use of SearchEngine as a context manager, which automatically handles database connections and disconnections. This is the recommended way to use the SearchEngine. ```python >>> with SearchEngine() as search: ... zipcode = search.by_zipcode(10030) ``` ```python >>> with ZipcodeSearchEngine() as search: ... zipcode = search.by_zipcode(10030) ``` -------------------------------- ### Using ZipcodeSearchEngine as a Context Manager Source: https://uszipcode.readthedocs.io/02-Advanced-Tutorial/index Illustrates the use of the ZipcodeSearchEngine as a context manager, which automatically handles database connections and disconnections, making it the recommended approach. ```python >>> with ZipcodeSearchEngine() as search: ... zipcode = search.by_zipcode(10030) ``` -------------------------------- ### Search by City and State Source: https://uszipcode.readthedocs.io/_sources/02-Advanced-Tutorial/index.rst Explains how to search for zipcodes using city and state names, including support for fuzzy matching and different state name formats (full or abbreviated). It also shows how to filter by zipcode type. ```python >>> res = search.by_city_and_state(city="cicago", state="ilinoy") # smartly guess what you are looking for >>> len(res) # matched 56 zipcode 56 >>> zipcode = res[0] >>> zipcode.major_city 'Chicago' >>> zipcode.state_abbr 'IL' Short state name also works: >>> res = search.by_city_and_state(city="cicago", state="il") # smartly guess what you are looking for >>> len(res) # 56 zipcodes in Chicago 56 >>> zipcode = res[0] >>> zipcode.major_city 'Chicago' >>> zipcode.state_abbr 'IL' You can add ``zipcode_type=ZipcodeType.PO_Box`` parameter to only include Po Box type zipcode. Or you can add ``zipcode_type=None`` to return any type of zipcode. By default, return standard type zipcode only: >>> res = search.by_city_and_state(city="Chicago", state="IL", zipcode_type=ZipcodeType.PO_Box) ``` -------------------------------- ### Advanced Tutorial Source: https://uszipcode.readthedocs.io/_modules/uszipcode/model Covers more advanced functionalities and use cases of the uszipcode library, potentially including custom searches, data manipulation, or integration with other tools. ```python # This section would contain more complex examples, such as: # - Batch searching # - Filtering results by population, density, etc. # - Exporting data # - Using different database backends if supported # Placeholder for advanced usage demonstration print("Advanced tutorial examples would go here.") ``` -------------------------------- ### Using ZipcodeSearchEngine as a Context Manager Source: https://uszipcode.readthedocs.io/02-Advanced-Tutorial/index Shows how to use the ZipcodeSearchEngine within a 'with' statement, which automatically handles database connection and disconnection. This is the recommended approach for managing database resources. ```python >>> with ZipcodeSearchEngine() as search: ... zipcode = search.by_zipcode(10030) ``` -------------------------------- ### Basic Zipcode Search and Attribute Access Source: https://uszipcode.readthedocs.io/_sources/02-Advanced-Tutorial/index.rst Demonstrates how to initialize the SearchEngine, perform a search by zipcode, and access attributes of the returned zipcode object. This includes accessing the zipcode, major city, state abbreviation, and population. ```python from uszipcode import SearchEngine, SimpleZipcode, ComprehensiveZipcode search = SearchEngine() zipcode = search.by_zipcode(10030) print(zipcode.zipcode) print(zipcode.major_city) print(zipcode.state_abbr) print(zipcode.population) ``` -------------------------------- ### Custom Query with SQLAlchemy Source: https://uszipcode.readthedocs.io/_sources/02-Advanced-Tutorial/index.rst Illustrates how to perform custom database queries using SQLAlchemy ORM with the SimpleZipcode model provided by the library. ```python >>> import sqlalchemy as sa >>> from uszipcode import SearchEngine, SimpleZipcode >>> search = SearchEngine(simple_zipcode=True) >>> sql = sa.select(SimpleZipcode).where(SimpleZipcode.zipcode=="10001") >>> search.ses.scalar(stmt).one() SimpleZipcode(zipcode="10001", ...) ``` -------------------------------- ### Fuzzy City and State Search Source: https://uszipcode.readthedocs.io/_sources/01-Usage-Example/index.rst Performs fuzzy searches for city and state names, which are case-insensitive, space-insensitive, and tolerant to typos. This is useful for web applications where exact spelling might not be known. ```python # Looking for Chicago and IL, but entered wrong spelling. res = search.by_city_and_state("cicago", "il", returns=999) # only returns first 999 results print(len(res)) # 56 zipcodes in Chicago zipcode = res[0] print(zipcode.major_city) print(zipcode.state_abbr) ``` -------------------------------- ### Basic Zipcode Search and Attribute Access Source: https://uszipcode.readthedocs.io/02-Advanced-Tutorial/index Demonstrates how to initialize the SearchEngine, search for a zipcode, and access its attributes like major city, state abbreviation, and population. ```python >>> search = SearchEngine() >>> zipcode = search.by_zipcode(10030) >>> zipcode.zipcode '10030' >>> zipcode.major_city 'New York' >>> zipcode.state_abbr 'NY' >>> zipcode.population 26999 ``` -------------------------------- ### Filtering by Zipcode Type Source: https://uszipcode.readthedocs.io/02-Advanced-Tutorial/index Explains how to filter search results based on zipcode types (PO Box, Unique, Standard). By default, only 'Standard' zipcodes are returned. Examples show how to include other types or all types. ```python search.by_xxx(..., zipcode_type=ZipcodeTypeEnum.PO_Box) search.by_xxx(..., zipcode_type=None) ``` -------------------------------- ### uszipcode Module Documentation Source: https://uszipcode.readthedocs.io/_sources/uszipcode/__init__.rst This snippet details the main uszipcode module, including its members and sub-packages. It serves as the entry point for understanding the package's structure. ```python .. automodule:: uszipcode :members: sub packages and modules ------------------------ .. toctree:: :maxdepth: 1 db model search state_abbr ``` -------------------------------- ### Zipcode Object Comparison and Hashing Source: https://uszipcode.readthedocs.io/_sources/02-Advanced-Tutorial/index.rst Illustrates the comparison and hashing capabilities of SimpleZipcode objects. It shows how to check for truthiness, perform less than comparisons, and use zipcode objects in sets. ```python from uszipcode import SimpleZipcode print(bool(SimpleZipcode(zipcode="10030"))) print(bool(SimpleZipcode())) print(SimpleZipcode(zipcode="10030") <= SimpleZipcode(zipcode="10031")) print(len(set([SimpleZipcode(zipcode="10030"), SimpleZipcode(zipcode="10031")]))) ``` -------------------------------- ### Find Top 10 Population Zipcodes Source: https://uszipcode.readthedocs.io/02-Advanced-Tutorial/index This snippet demonstrates how to find the top 10 most populated zip codes using the uszipcode library. It utilizes the `search.by_population` method with parameters to specify the upper limit for population, sort order, and the number of results to return. The example then iterates through the results to print the population of each zip code. ```python >>> res = search.by_population(upper=999999999, sort_by="population", ascending=False, returns=10) >>> len(res) 10 >>> for zipcode in res: ... print(zipcode.Population) # should be in descending order ``` -------------------------------- ### Search by City Source: https://uszipcode.readthedocs.io/_sources/02-Advanced-Tutorial/index.rst Demonstrates how to search for zipcodes based on the city name. It also mentions an internal method to help find correct city names. ```python >>> res = search.by_city("vienna") >>> zipcode = res[0] >>> zipcode.major_city 'Vienna' **uszipcode also provide a internal method to help you find correct city name**:: ``` -------------------------------- ### Search by City and State (Fuzzy Matching) Source: https://uszipcode.readthedocs.io/02-Advanced-Tutorial/index Demonstrates searching for zipcodes by city and state, supporting fuzzy matching for city and state names. It also shows how to filter by zipcode type (e.g., PO Box). ```python >>> res = search.by_city_and_state(city="cicago", state="ilinoy") # smartly guess what you are looking for >>> len(res) # matched 56 zipcode 56 >>> zipcode = res[0] >>> zipcode.major_city 'Chicago' >>> zipcode.state_abbr 'IL' >>> res = search.by_city_and_state(city="cicago", state="il") # smartly guess what you are looking for >>> len(res) # 56 zipcodes in Chicago 56 >>> zipcode = res[0] >>> zipcode.major_city 'Chicago' >>> zipcode.state_abbr 'IL' >>> res = search.by_city_and_state(city="Chicago", state="IL", zipcode_type=ZipcodeType.PO_Box) ``` -------------------------------- ### Search by State Source: https://uszipcode.readthedocs.io/02-Advanced-Tutorial/index Demonstrates searching for zipcodes by state name, returning the state abbreviation. ```python >>> res = search.by_state("Rhode Island") >>> zipcode = res[0] >>> zipcode.state_abbr 'RI' ``` -------------------------------- ### Basic Zipcode Search and Attribute Access Source: https://uszipcode.readthedocs.io/02-Advanced-Tutorial/index Demonstrates how to initialize the SearchEngine, perform a search by zipcode, and access attributes of the returned zipcode object such as zipcode, major_city, state_abbr, and population. ```python from uszipcode import SearchEngine, SimpleZipcode, ComprehensiveZipcode >>> search = SearchEngine() >>> zipcode = search.by_zipcode(10030) >>> zipcode.zipcode # access attributes '10030' >>> zipcode.major_city 'New York' >>> zipcode.state_abbr 'NY' >>> zipcode.population 26999 ``` -------------------------------- ### Advanced Search: Zipcodes in California with Prefix Source: https://uszipcode.readthedocs.io/_sources/02-Advanced-Tutorial/index.rst Shows how to combine state and prefix searches, along with sorting by housing units, to find specific zipcodes. ```python res = search.find( state="califor", prefix="95", sort_by=Zipcode.housing_units, ascending=False, returns=100, ) ``` -------------------------------- ### SearchEngine Functionality Source: https://uszipcode.readthedocs.io/genindex Demonstrates the usage of the SearchEngine class for finding zip codes and related information. Includes sorting options. ```python from uszipcode import SearchEngine search = SearchEngine() # Example: Find zip codes by city results = search.by_city('New York') print(f"Found {len(results)} zip codes in New York.") # Example: Find zip codes by state and sort by distance results_sorted = search.by_state('CA', returns=5, sort_by=SearchEngine.SORT_BY_DIST) print("Top 5 zip codes in California sorted by distance:") for zipcode in results_sorted: print(f" - {zipcode['zipcode']}, {zipcode['city']}, {zipcode['state']}") # Accessing state list print(f"Available states: {search.state_list}") ``` -------------------------------- ### Search Zipcode by State Source: https://uszipcode.readthedocs.io/_sources/02-Advanced-Tutorial/index.rst Retrieves zipcodes associated with a given state name. The results contain detailed zipcode information, including the state abbreviation. ```python >>> res = search.by_state("Rhode Island") >>> zipcode = res[0] >>> zipcode.state_abbr 'RI' ``` -------------------------------- ### Sorting Search Results Source: https://uszipcode.readthedocs.io/_sources/02-Advanced-Tutorial/index.rst Explains how to sort search results using the `sort_by` and `ascending` keywords. This applies to various search methods within the SearchEngine class. ```python res = search.query(city="New York", state=="NY", sort_by=Zipcode.median_household_income, ascending=False) for zipcode in res: print(zipcode.median_household_income) # should be in descending order ``` -------------------------------- ### Accessing Zipcode Attributes Source: https://uszipcode.readthedocs.io/_sources/02-Advanced-Tutorial/index.rst Shows how to retrieve a zipcode object using SearchEngine and then access its various attributes like zipcode, major_city, state_abbr, and population. ```python >>> from uszipcode import SearchEngine, SimpleZipcode, ComprehensiveZipcode >>> search = SearchEngine() >>> zipcode = search.by_zipcode(10030) >>> zipcode.zipcode # access attributes '10030' >>> zipcode.major_city 'New York' >>> zipcode.state_abbr 'NY' >>> zipcode.population 26999 ``` -------------------------------- ### SearchEngine Search Methods Source: https://uszipcode.readthedocs.io/_sources/02-Advanced-Tutorial/index.rst Lists the various methods available in the SearchEngine class for querying zipcode information. This includes searching by zipcode, city, state, population, and other geographical or demographic criteria. ```APIDOC List of the Way you can Search ------------------------------------------------------------------------------ Here's the list of the ways you can search zipcode: - :meth:`~uszipcode.search.SearchEngine.query` - :meth:`~uszipcode.search.SearchEngine.by_zipcode` - :meth:`~uszipcode.search.SearchEngine.by_city_and_state` - :meth:`~uszipcode.search.SearchEngine.by_city`, - :meth:`~uszipcode.search.SearchEngine.by_state` - :meth:`~uszipcode.search.SearchEngine.by_prefix` - :meth:`~uszipcode.search.SearchEngine.by_pattern` - :meth:`~uszipcode.search.SearchEngine.by_population` - :meth:`~uszipcode.search.SearchEngine.by_population_density` - :meth:`~uszipcode.search.SearchEngine.by_land_area_in_sqmi` - :meth:`~uszipcode.search.SearchEngine.by_water_area_in_sqmi` - :meth:`~uszipcode.search.SearchEngine.by_housing_units` - :meth:`~uszipcode.search.SearchEngine.by_occupied_housing_units` - :meth:`~uszipcode.search.SearchEngine.by_median_home_value` - :meth:`~uszipcode.search.SearchEngine.by_median_household_income` For sorting and limit the result, you also should know about :ref:`sort` and :ref:`limit`. ``` -------------------------------- ### SimpleZipcode Object Usage Source: https://uszipcode.readthedocs.io/_sources/02-Advanced-Tutorial/index.rst Demonstrates the hashable nature of SimpleZipcode objects, allowing them to be used in sets and sorted. It also shows boolean evaluation and comparison between SimpleZipcode instances. ```python >>> bool(SimpleZipcode(zipcode="10030")) True >>> bool(SimpleZipcode()) False >>> SimpleZipcode(zipcode="10030") <= SimpleZipcode(zipcode="10031") True >>> len(set([SimpleZipcode(zipcode="10030"), SimpleZipcode(zipcode="10031")])) 2 ``` -------------------------------- ### uszipcode Modules Source: https://uszipcode.readthedocs.io/genindex Lists the core modules within the uszipcode library, including model definitions, search utilities, and database interactions. ```python import uszipcode import uszipcode.db import uszipcode.model import uszipcode.search import uszipcode.state_abbr print("uszipcode modules imported successfully.") ``` -------------------------------- ### Filtering Zipcodes by Type Source: https://uszipcode.readthedocs.io/_sources/02-Advanced-Tutorial/index.rst Demonstrates how to filter search results by zipcode type. You can specify a particular type like PO_Box or set it to None to include all types. ```python search.by_xxx(..., zipcode_type=ZipcodeTypeEnum.PO_Box) search.by_xxx(..., zipcode_type=None) ``` -------------------------------- ### API Documentation Index Source: https://uszipcode.readthedocs.io/_sources/index.rst Provides links to navigate the API documentation, organized by name (index) and by structure (module index). This allows users to find specific functions, classes, and modules within the uszipcode library. ```APIDOC API Document ------------------------------------------------------------------------------ * :ref:`by Name ` * :ref:`by Structure ` ``` -------------------------------- ### Limiting Number of Results Source: https://uszipcode.readthedocs.io/_sources/02-Advanced-Tutorial/index.rst Shows how to limit the number of results returned by search queries using the `returns` keyword. A value of 0 means unlimited results. The default limit is 5. ```python res = search.by_population(upper=999999999, sort_by="population", ascending=False, returns=10) print(len(res)) for zipcode in res: print(zipcode.Population) # should be in descending order ``` -------------------------------- ### Accessing SQLAlchemy Session for Custom Queries Source: https://uszipcode.readthedocs.io/uszipcode/search Illustrates how to access the underlying SQLAlchemy session (`ses`) from a SearchEngine instance to perform custom database queries using SQLAlchemy models like SimpleZipcode. ```python from uszipcode import SearchEngine, SimpleZipcode search = SearchEngine() # Accessing the SQLAlchemy session for custom queries result = search.ses.scalar(SimpleZipcode).filter(SimpleZipcode.zipcode=="10001") ``` -------------------------------- ### Find City by Name Source: https://uszipcode.readthedocs.io/_sources/02-Advanced-Tutorial/index.rst Searches for cities by name, with optional best match functionality. It can handle typos in city and state names. ```python >>> search.find_city("phonix", bes_match=True) ['Phoenix'] # Find city in kensas state, state name is also typo tolerant >>> search.find_city("kersen", state="kensas", best_match=False) ["Nickerson", ] ``` -------------------------------- ### uszipcode 0.2.1 - Minor Improvements Source: https://uszipcode.readthedocs.io/release-history Version 0.2.1 clarifies the use of two databases and provides instructions on switching between them. ```python # Minor Improvements # Emphasize that there are two database used, and add an instruction for how to switching between these two. ```