7 Ways To Interact With Internet Protocols You Should Know
What is the Internet Protocol?
The Internet Protocol is designed to implement a uniform system of addresses on all of the Internet-connected computers everywhere and to make it possible for packets to travel from one end of the Internet to the other. You may know it better as the “IP” in TCP/IP.
There are various categories of internet protocols. These protocols are created to serve the needs of different types of data communication between different computers on the internet.
Why use Python to interact with internet protocols?
Python has extensive built-in modules to handle each of these communication scenarios. The methods and functions in these modules can do the simplest job of just validating a URL or also the complex job of handling the cookies and sessions.
Because these models are built-in modules, no further installations are required.
Read these articles, to see “How Python is Powerful for Dealing with Various Scenarios”:
Delphi adds powerful GUI features and functionalities to Python
In this tutorial, we’ll build Windows Apps with extensive Internet Protocols and Supports capabilities by integrating Python’s Internet Protocols and Supports libraries with Embarcadero’s Delphi, using Python4Delphi (P4D).
P4D empowers Python users with Delphi’s award-winning VCL functionalities for Windows which enables us to build native Windows apps 5x faster. This integration enables us to create a modern GUI with the Windows 10 look or style and responsive controls for our Python applications. Python4Delphi also comes with an extensive range of demos, use cases, and tutorials.
We’re going to cover the following…
How to use http, ipaddress, smtplib, urllib, uuid, webbrowser, and wsgiref Python libraries to interact with Internet Protocols and Supports
All of them would be integrated with Python4Delphi to create Windows Apps with Internet Protocols and Support capabilities.
Prerequisites
Before we begin to work, download and install the latest Python for your platform. Follow the Python4Delphi installation instructions mentioned here. Alternatively, you can check out the easy instructions found in the Getting Started With Python4Delphi video by Jim McKeeth.
Most of the modules above require the presence of the system-dependent module socket, which is currently built-in support on most popular platforms.
Getting started with Python4Delphi
First, open and run our Python GUI using project Demo1 from Python4Delphi with RAD Studio. Then insert the script into the lower Memo, click the Execute button, and get the result in the upper Memo. You can find the Demo1 source on GitHub. The behind the scene details of how Delphi manages to run your Python code in this amazing Python GUI can be found at this link.
1. How to use the Python http package?
We can use the http package for working with the HyperText Transfer Protocol. http is a collection of these modules:
- http.client is a low-level HTTP protocol client; for high-level URL opening use urllib.request
- http.server contains basic HTTP server classes based on socket server
- http.cookies has utilities for implementing state management with cookies
- http.cookiejar provides persistence of cookies
http is also a module that defines a number of HTTP status codes and associated messages through the http.HTTPStatus.
The following is a code example of http package to learn about HTTP Statuses (run this inside the lower Memo of Python4Delphi Demo01 GUI):
print(HTTPStatus.OK)
print(HTTPStatus.OK == 200)
print(HTTPStatus.OK.value)
print(HTTPStatus.OK.phrase)
print(HTTPStatus.OK.description)
print(list(HTTPStatus))
from http import HTTPStatus
print(HTTPStatus.OK) print(HTTPStatus.OK == 200) print(HTTPStatus.OK.value) print(HTTPStatus.OK.phrase) print(HTTPStatus.OK.description) print(list(HTTPStatus)) |
Here is the result in the Python GUI
2. How do I use the Python ipaddress package?
The ipaddress library provides the capabilities to create, manipulate and operate on IPv4 and IPv6 addresses and networks.
Here is some convenient use of ipaddress functions:
- ipaddress.ip_address(address): Return an IPv4Address or IPv6Address object depending on the IP address passed as an argument. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. A ValueError is raised if the address does not represent a valid IPv4 or IPv6 address.
- ipaddress.ip_network(address, strict=True): Return an IPv4Network or IPv6Network object depending on the IP address passed as argument. The address is a string or integer representing the IP network. Either IPv4 or IPv6 networks may be supplied; integers less than 2**32 will be considered to be IPv4 by default. strict is passed to IPv4Network or IPv6Network constructor. A ValueError is raised if the address does not represent a valid IPv4 or IPv6 address, or if the network has host bits set.
- ipaddress.IPv4Interface(address): Construct an IPv4 interface. The meaning of address is as in the constructor of IPv4Network, except that arbitrary host addresses are always accepted.
- ipaddress.IPv6Interface(address): Construct an IPv6 interface. The meaning of address is as in the constructor of IPv6Network, except that arbitrary host addresses are always accepted.
The following code is the implementation of the concepts above:
print(ipaddress.ip_address(‘192.168.0.1’))
print(ipaddress.ip_address(‘2001:db8::’))
print(ipaddress.ip_network(‘192.168.0.0/28’))
print(ipaddress.IPv4Address(‘192.168.0.1′))
print(ipaddress.IPv4Address(3232235521))
print(ipaddress.IPv4Address(b’xC0xA8x00x01’))
print(ipaddress.IPv6Address(‘2001:db8::1000’))
print(ipaddress.IPv6Address(‘ff02::5678’))
import ipaddress
print(ipaddress.ip_address(‘192.168.0.1’)) print(ipaddress.ip_address(‘2001:db8::’)) print(ipaddress.ip_network(‘192.168.0.0/28’))
print(ipaddress.IPv4Address(‘192.168.0.1’)) print(ipaddress.IPv4Address(3232235521)) print(ipaddress.IPv4Address(b‘xC0xA8x00x01’))
print(ipaddress.IPv6Address(‘2001:db8::1000’)) print(ipaddress.IPv6Address(‘ff02::5678’)) |
Here is the ipaddress introductory examples in the Python GUI:
3. How do we use the Python smtplib package?
The smtplib module defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon.
The following example prompts the user for addresses needed in the message envelope (‘To’ and ‘From’ addresses), and the message to be delivered. Note that the headers to be included with the message must be included in the message as entered; this example doesn’t do any processing of the RFC 822 headers. In particular, the ‘To’ and ‘From’ addresses must be included in the message headers explicitly.
def prompt(prompt):
return input(prompt).strip()
fromaddr = prompt(“From: “)
toaddrs = prompt(“To: “).split()
print(“Enter message, end with ^D (Unix) or ^Z (Windows):”)
# Add the From: and To: headers at the start!
msg = (“From: %srnTo: %srnrn”
% (fromaddr, “, “.join(toaddrs)))
while True:
try:
line = input()
except EOFError:
break
if not line:
break
msg = msg + line
print(“Message length is”, len(msg))
server = smtplib.SMTP(‘localhost’)
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import smtplib
def prompt(prompt): return input(prompt).strip()
fromaddr = prompt(“From: “) toaddrs = prompt(“To: “).split() print(“Enter message, end with ^D (Unix) or ^Z (Windows):”)
# Add the From: and To: headers at the start! msg = (“From: %srnTo: %srnrn” % (fromaddr, “, “.join(toaddrs))) while True: try: line = input() except EOFError: break if not line: break msg = msg + line
print(“Message length is”, len(msg))
server = smtplib.SMTP(‘localhost’) server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, msg) server.quit() |
Here are the smtplib Python4Delphi and PyScripter example’s results
4. How do I use the Python urllib package?
urllib is a package that collects these modules for working with URLs:
- urllib.request for opening and reading URLs
- urllib.error containing the exceptions raised by urllib.request
- urllib.parse for parsing URLs
- urllib.robotparser for parsing robots.txt files
In this section, we will learn more about urllib.request. The urllib.request module defines functions and classes which help in opening URLs (mostly HTTP) basic and digest authentication, redirections, cookies, and more.
This example gets the embarcadero.com main page and displays the first 300 bytes of it:
with urllib.request.urlopen(‘http://embarcadero.com/’) as f:
print(f.read(300))
import urllib.request
with urllib.request.urlopen(‘http://embarcadero.com/’) as f: print(f.read(300)) |
urllib Simple Examples:
5. How to use the Python uuid package?
The uuid module provides immutable UUID objects (the UUID class) and the functions uuid1(), uuid3(), uuid4(), uuid5() for generating version 1, 3, 4, and 5 UUIDs as specified in RFC 4122.
Here are some examples of typical usage of the uuid module:
# Make a UUID based on the host ID and current time
print(uuid.uuid1())
# Make a UUID using an MD5 hash of a namespace UUID and a name
print(uuid.uuid3(uuid.NAMESPACE_DNS, ‘pythongui.org’))
# Make a random UUID
print(uuid.uuid4())
# Make a UUID using a SHA-1 hash of a namespace UUID and a name
print(uuid.uuid5(uuid.NAMESPACE_DNS, ‘pythongui.org’))
import uuid
# Make a UUID based on the host ID and current time print(uuid.uuid1())
# Make a UUID using an MD5 hash of a namespace UUID and a name print(uuid.uuid3(uuid.NAMESPACE_DNS, ‘pythongui.org’))
# Make a random UUID print(uuid.uuid4())
# Make a UUID using a SHA-1 hash of a namespace UUID and a name print(uuid.uuid5(uuid.NAMESPACE_DNS, ‘pythongui.org’)) |
Here is the uuid Python demo results in the Python GUI:
6. How to use the Python webbrowser package?
The webbrowser module provides a high-level interface to allow displaying Web-based documents to users. Under most circumstances, simply calling the open() function from this module will do the whole thing you need.
Here is a simple example to open blogs.embarcadero.com:
url = ‘https://blogs.embarcadero.com/’
# Open URL in a new tab, if a browser window is already open.
webbrowser.open_new_tab(url)
# Open URL in new window, raising the window if possible.
webbrowser.open_new(url)
import webbrowser
url = ‘https://blogs.embarcadero.com/’
# Open URL in a new tab, if a browser window is already open. webbrowser.open_new_tab(url)
# Open URL in new window, raising the window if possible. webbrowser.open_new(url) |
Here is the result in Python GUI
7. How can we use the Python wsgiref Package?
wsgiref is WSGI Utilities and Reference Implementation in Python.
The Web Server Gateway Interface (WSGI) is a standard interface between web server software and web applications written in Python. Having a standard interface makes it easy to use an application that supports WSGI with a number of different web servers.
Example usage of wsgiref:
# A relatively simple WSGI application. It’s going to print out the
# environment dictionary after being updated by setup_testing_defaults
def simple_app(environ, start_response):
setup_testing_defaults(environ)
status = ‘200 OK’
headers = [(‘Content-type’, ‘text/plain; charset=utf-8’)]
start_response(status, headers)
ret = [(“%s: %sn” % (key, value)).encode(“utf-8″)
for key, value in environ.items()]
return ret
with make_server(”, 8000, simple_app) as httpd:
print(“Serving on port 8000…”)
httpd.serve_forever()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
from wsgiref.util import setup_testing_defaults from wsgiref.simple_server import make_server
# A relatively simple WSGI application. It’s going to print out the # environment dictionary after being updated by setup_testing_defaults def simple_app(environ, start_response): setup_testing_defaults(environ)
status = ‘200 OK’ headers = [(‘Content-type’, ‘text/plain; charset=utf-8’)]
start_response(status, headers)
ret = [(“%s: %sn” % (key, value)).encode(“utf-8”) for key, value in environ.items()] return ret
with make_server(”, 8000, simple_app) as httpd: print(“Serving on port 8000…”) httpd.serve_forever() |
Here is the wsgiref introductory example in the Python GUI:
Are you ready to enable your apps to interact with Internet protocols?
The Internet Protocols we’ve shown you are responsible for the end-to-end delivery of data over the internet. We demonstrated 7 powerful built-in Python libraries for interacting with various common Internet Protocols – http, ipaddress, smtplib, urllib, uuid, webbrowser, and wsgiref. All of them wrapped well inside a powerful GUI provided by Python4Delphi. We can’t wait to see what you build with Python4Delphi!
Want to know some more? Then check out Python4Delphi which easily allows you to build Python GUIs for Windows using Delphi.