Skip to content

myip

myip is a simple utility built with python and using requests to print out the public IP address of your computer. I chose this project to both learn and to teach how to package python projects. It was important to me that the project required another package and that we developed it using Test-Driven Development.

Usage and file structure of the finished project.

MyIP

.
├── dist
│   ├── myip_tjc-0.0.1-py3-none-any.whl
│   └── myip-tjc-0.0.1.tar.gz
├── LICENSE
├── pyproject.toml
├── README.md
├── setup.cfg
├── src
│   ├── myip
│   │   ├── api.py
│   │   ├── __init__.py
│   │   ├── __main__.py
│   └── myip_tjc.egg-info
│       ├── dependency_links.txt
│       ├── entry_points.txt
│       ├── PKG-INFO
│       ├── requires.txt
│       ├── SOURCES.txt
│       └── top_level.txt
└── tests
    └── test_myip.py

PyPI Test Account

We are going to push our package to the PyPI test server. This server is made specifically for testing packages. The packages deployed or not persistent. Visit https://test.pypi.org/ and register a user.

Creating the Project Folder and Files

Barebones Structure

First thing we are going to do is create some folders for our project.

mkdir myip
cd myip
mkdir {src,tests}
mkdir src/myip

Now we create the package folder and the two files needed in the package. __init__.py is required so that Python knows the folder is a package. myip.py is the file where we are going to store the logic of our application.

touch src/myip/__init__.py
touch src/myip/__main__.py
touch src/myip/api.py

Now our file structure should look like this.

file structure

pyproject.toml

The pyproject.toml is used to tell build tools what is required to build your project. In this example we are going to use setuptools as our builder. Other options include flit or poetry.

pyproject.toml
[build-system]
requires = ["setuptools>=42"]
build-backend = "setuptools.build_meta"

setup.cfg

This is the configuration file for setuptools. It will describe the package and the code structure. Here you will use your username created at the PyPI test server.

setup.cfg
[metadata]
name = myip-{YOUR-USER}
version = 0.0.1
author = {YOUR NAME}
author_email = {YOUR EMAIL}
description = A small utility to get the public IP of host
long_description = file: README.md
long_description_content_type = text/markdown
url = https://github.com/{YOUR GITHUB}
classifiers =
    Programming Language :: Python :: 3
    License :: OSI Approved :: MIT License
    Operating System :: OS Independent

[options]
package_dir =
    = src
packages = find:
python_requires = >=3.6
install_requires =
  requests

[options.packages.find]
where = src

[options.entry_points]
console_scripts =
  myip=myip:print_public_ip

README.md

README.md
# MyIP

This is a simple package that retrieves the external public IP. It uses a
third-party API to retrieve the response using the `requests` library.

LICENSE

You can use https://choosealicense.com/ to find the appropriate license for you project. For this one I am going to use the MIT License.

LICENSE
MIT License

Copyright (c) 2022 {YOUR NAME}

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.

Your file structure should now look like this.

Tree Structure

Set Up our Dev Environment

Virtual Environment

From the myip folder create a python virtual environment.

python -m venv .venv

Activate the virtual environment

source .venv/bin/activate

Upgrade pip

python -m pip install --upgrade pip

Installing our Package as Editable

Now we are going to install our barebones package locally and make it editable. This will also install any requirements (such as requests) listed in the setup.cfg file.

pip install --editable .

Installing Development Dependencies

During development we will use pytest to ensure our application is working as expected. Along with pytest we are going to use requests-mock to mock the responses from our external source. Lets install these two dev dependencies.

pip install pytest requests-mock

Write the Code

Writing our First Test

Before writing any of the application code, we are going to start off by writing a test, making sure it fails, and then writing enough code to make it pass. This is Test-Driven Development (TDD).

tests/test_myip.py
import myip


def test_get_public_ip(requests_mock):
    requests_mock.get(myip.API, json={"ip": "10.0.0.1"})
    resp = myip.get_public_ip()
    assert resp == "10.0.0.1"

Now run pytest from the project folder and you should get an error stating: AttributeError: module 'myip' has no attribute 'API'

Pytest Error

Now we are going to solve this error by adding in the API url. First we edit the src/myip/api.py file.

src/myip/api.py
API = "https://api.ipify.org?format=json"

Then we edit the src/myip/__init__.py file.

src/myip/__init__.py
from .api import API  # noqa

Now we run pytest again, but get a different error.

Pytest Error

Lets fix that by first editing the src/myip/api.py file again.

src/myip/api.py
API = "https://api.ipify.org?format=json"


def get_public_ip():
    pass

Then we edit the src/myip/__init__.py file.

src/myip/__init__.py
from .api import API, get_public_ip  # noqa

And run pytest again. It looks like we fixed the last error, but got a different error.

Pytest Error

This is the iteration process for TDD. Now lets finish up the code and make sure it passes.

src/myip/api.py
import requests


API = "https://api.ipify.org?format=json"


def get_public_ip():
    try:
        resp = requests.get(API, timeout=5)
    except requests.exceptions.Timeout:
        return "Request Timed Out"
    except requests.exceptions.RequestException:
        return "An error occurred during the request."
    return resp.json()["ip"]


def print_public_ip():
    ip = get_public_ip()
    print(ip)

Running pytest now and we get a success!

Pytest Success

We should add a couple more tests to ensure we have good coverage.

tests/test_myip.py
import requests

import myip


def test_get_public_ip(requests_mock):
    requests_mock.get(myip.API, json={"ip": "10.0.0.1"})
    resp = myip.get_public_ip()
    assert resp == "10.0.0.1"


def test_get_public_ip_timeout(requests_mock):
    requests_mock.get(myip.API, exc=requests.exceptions.Timeout)
    resp = myip.get_public_ip()
    assert resp == "Request Timed Out"


def test_get_public_ip_error(requests_mock):
    requests_mock.get(myip.API, exc=requests.exceptions.ConnectionError)
    resp = myip.get_public_ip()
    assert resp == "An error occurred during the request."

Setup main

First lets add one more import to src/myip/__init__.py.

src/myip/__init__.py
from .api import API, get_public_ip, print_public_ip  # noqa

Now we edit src/myip/__main__.py

src/myip/__main__.py
import myip


if __name__ == "__main__":
    myip.print_public_ip()

With that done, we should be able to run both python -m myip and just plain old myip.

MyIP

Publish to PyPI

Building the Distribution Archives

Last step is publishing it to PyPI. We start by installing the build package.

python -m pip install --upgrade build

Then we run build.

python -m build

Built

Uploading

First we install a package for uploading.

python -m pip install --upgrade twine

Then we upload to the test PyPI instance.

python -m twine upload --repository testpypi dist/*

Upload

Now we can install our new package! First deactivate the virtual environment by running deactivate. Then run the following - Remember to change this to your username.

python -m pip install --index-url https://test.pypi.org/simple/ --no-deps myip-tjc

Test it out by running either python -m myip or simply myip on the command line.

Back to top