Python
- Understanding HTTP from Scratch with Python Sockets
Most Python developers reach for
requestswhen working with HTTP — and for good reason. It’s convenient, safe, and hides all the messy details of networking. But hiding those details also hides how the web actually works.Under the surface, every HTTP transaction is just plain text sent over a TCP socket. Understanding what happens at that level gives you insight into how browsers, APIs, and servers communicate. It also helps you debug connection issues, craft custom clients, or even build HTTP servers yourself.
- How to Generate a 32-byte Key for AES Encryption
Generating a 32-byte key for AES encryption from a password using only built-in Python modules. To do this we’ll use the
hashliblibrary. For this approach we’ll use the PBKDF2 (Password-Based Key Derivation Function 2) viahashlib.pbkdf2_hmac. This ensures that the key is securely derived from the password.Here’s some example code:
import os import hashlib def generate_aes_key(password: str, salt: bytes = None, iterations: int = 100_000) -> bytes: """ Generate a 32-byte AES key from a password using PBKDF2-HMAC-SHA256. :param password: The password to derive the key from. :param salt: A unique salt (16 bytes recommended). If None, a random salt will be generated. :param iterations: The number of iterations for the key derivation function. :return: A tuple containing the derived key and the salt used. """ if salt is None: salt = os.urandom(16) # Generate a random 16-byte salt if not provided # Use PBKDF2 with HMAC-SHA256 to derive the key key = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, iterations, dklen=32) return key, salt # Example usage password = "securepassword" key, salt = generate_aes_key(password) print("Derived Key (hex):", key.hex()) print("Salt (hex):", salt.hex())I preferred to use this approach to avoid any external dependencies.
- Example of adding CORS headers Flask
An example of adding CORS headers to a Flask app without using Flask-CORS.
from flask import Flask, request, jsonify, make_response from werkzeug.datastructures import Headers app = Flask(__name__) @app.route('/', methods=['OPTIONS', 'GET', 'POST']) def index(): # output all request headers to terminal print(request.headers) if request.method == 'POST': # handle json post data here... print(request.get_json()) headers = Headers() headers.add('Access-Control-Allow-Origin', '*') headers.add('Access-Control-Allow-Methods', 'OPTIONS', 'GET', 'POST') headers.add('Access-Control-Allow-Headers', 'Content-Type') headers.add('Access-Control-Max-Age', '300') resp = make_response( jsonify( {'msg':'nailed it!'} ) ) resp.headers = headers return resp if __name__ == '__main__': app.run(debug=True) - Python date string to date object
If you have a date string and need to convert it into a date object, how can it be converted to a date object using Python?
Python includes within the datetime package a strptime function, here’s an example usage:
>>> import datetime >>> datetime.datetime.strptime('2022-10-30T14:32:41Z', "%Y-%m-%dT%H:%M:%S%z") datetime.datetime(2022, 10, 30, 14, 32, 41, tzinfo=datetime.timezone.utc)Updated code for Windows
Recently I ran into an issue where a report was generated on Linux but I wanted to process it further on windows. The timezones don’t match up though and will cause issues. Let’s look at how to handle that.
- ModuleNotFoundError: No module named 'distutils.util' on Ubuntu
If you’re using Ubuntu 16.04 or newer and want to use Python 3.7 and newer with pip you have probably seen this error message
ModuleNotFoundError: No module named 'distutils.util'.On later versions of Ubuntu the error message will be:
ModuleNotFoundError: No module named 'distutils.cmd'. This fix will still work.bmcculley@hakk:~$ pip3 Traceback (most recent call last): File "/usr/local/bin/pip3", line 5, in <module> from pip._internal.cli.main import main File "/usr/local/lib/python3.7/dist-packages/pip/_internal/cli/main.py", line 10, in <module> from pip._internal.cli.autocompletion import autocomplete File "/usr/local/lib/python3.7/dist-packages/pip/_internal/cli/autocompletion.py", line 9, in <module> from pip._internal.cli.main_parser import create_main_parser File "/usr/local/lib/python3.7/dist-packages/pip/_internal/cli/main_parser.py", line 7, in <module> from pip._internal.cli import cmdoptions File "/usr/local/lib/python3.7/dist-packages/pip/_internal/cli/cmdoptions.py", line 19, in <module> from distutils.util import strtobool ModuleNotFoundError: No module named 'distutils.util' Error in sys.excepthook: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook from apport.fileutils import likely_packaged, get_recent_crashes File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module> from apport.report import Report File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in <module> import apport.fileutils File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in <module> from apport.packaging_impl import impl as packaging File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 23, in <module> import apt File "/usr/lib/python3/dist-packages/apt/__init__.py", line 23, in <module> import apt_pkg ModuleNotFoundError: No module named 'apt_pkg' Original exception was: Traceback (most recent call last): File "/usr/local/bin/pip3", line 5, in <module> from pip._internal.cli.main import main File "/usr/local/lib/python3.7/dist-packages/pip/_internal/cli/main.py", line 10, in <module> from pip._internal.cli.autocompletion import autocomplete File "/usr/local/lib/python3.7/dist-packages/pip/_internal/cli/autocompletion.py", line 9, in <module> from pip._internal.cli.main_parser import create_main_parser File "/usr/local/lib/python3.7/dist-packages/pip/_internal/cli/main_parser.py", line 7, in <module> from pip._internal.cli import cmdoptions File "/usr/local/lib/python3.7/dist-packages/pip/_internal/cli/cmdoptions.py", line 19, in <module> from distutils.util import strtobool ModuleNotFoundError: No module named 'distutils.util'Solution
Don’t worry, it’s a pretty easy fix. The module not found error just means that the nessacary packages aren’t installed. To fix this, just run the following in the terminal:
- How to Install Python 3.8 on Ubuntu 16.04 and 18.04

The Zen of Python Python is one of the most popular and most widely used programming languages in the world at this time. The philosophy behind the Python programming language is most likely the reason. It’s very easy to learn with its simple syntax, that same syntax makes the language very readable, therefore easy to understand what someone else wrote. From this the Python ecosystem has grown into a massive juggernaut, encompassing everything from basic scripts to web applications, to machine learning algorithms, process automation and everything in between.