So far we have setup our empty class and have initialized our folders
modules as a python package, so far so good. This challenge is going to cover:
Let’s jump right into it.
- Import the package requests. Beware: It is more beneficial to load only the packages that you need, in this case you will need the method
- Modify your IPInfo class inside
ipinfo.pyand define your initialization module. This initialization will require only one parameter of type string and will be called
- Create a Class Attribute named
ip_data. This class attribute will requests a json response from the public API https://ipinfo.io/IP_NUMBER/json where
IP_NUMBERis equal to the initialization parameter
ip. To challenge yourself, try to make this JSON request in a single line.
To make this work we will first import the
requests package and modify our class
IPInfo, we will add an initialization method that makes a GET request to a desired IP.
from requests import get as rget
- As you can see, we first imported the method
getfrom the package
requestsand give it the alias of
rgetbecause “get” is too generic.
- Then we write an initialization method in our class IPInfo and store the contents of the given requests into our variable
This is enough to make the challenge #3 pass.
- Change the object representation of your class to return
Geolocation information of IP_ADDRwhere
IP_ADDRis equal to the IP address of the requested JSON data stored in
- Create a iterable method that allows iteration in your class. For every key and value stored in the dictionary
self.ip_datayou should yield a
(key, value)tuple, e.g:
('ip', '188.8.131.52'). This way you should be able to yield a generator.
Let’s add the special module
__repr__ to change the representation of our class, and an
__iter__ module to enable iteration in our class.
With this we have completed challenge 4.
We can check how this works in the python interpreter.
from modules import IPInfo
See how easy it was? Let’s move on to challenge 5.
This is one of the easiest one, it’s all about documentation, we should document our code, modules, and packages with docstrings.
- You should always document your modules, classes and method definition with triple quoted strings, following the PEP8 recommendations on Docstrings. To see the modules, packages, and classes that you should document try running
If we run pydocstyle we will encounter the following errors:
modules/__init__.py:1 at module level:
That means that we need to document these packages and modules, this is a very good practice that you have to maintain.
Also we should document our ipinfo.py module, class and methods.
"""Module that handles IPInfo classes and methods."""
After we document our code, the test should pass now.
That’s it for this entry, we have learn how to initialize our class into a object, return a representation of our object, and we also enabled iteration in our class. See you next time.