hyperlink.parse
? Mostly you get hyperlink.URLParseError
, but you can occasionally get a ValueError
as well.
current_user == None
, not current_user is None
current_user
is a proxy object that happens to be wrapping None
, but isn’t actually None
.
Connect to the domain using the socket
module, then use the getpeercert()
method on the connection to get information about the HTTPS certificate.
Open the file with mode r+
to be able to seek around the file and write to it.
Adding a couple of options to the console
lexer (console?lang=python&prompt=>>>
) gets you syntax highlighting for a Python console session.
I made a library that knows how to read lots of different forms of Flickr.com URL, and I used hyperlink
to do it.
[Errno 54] Connection reset by peer
when using pytest You can run a TCP server in the background using a fixture, and using the SO_LINGER
socket option can reset the connection.
To see exactly what HTTP requests were being made, I modified the library so that betamax would record requests.
When you make an HTTP request, you can use the If-Modified-Since
header to get a 304 Not Modified if nothing has changed since your last request.
Images can have orientation specified in their EXIF metadata, which isn’t preserved when you open and save an image with Pillow.
Why I use Sessions in boto3, and the Python function I use to create them.
Some experimenting with the YouTube API to merge two accounts into one.
resp.close()
to close the file opened by send_file()
You can use app.error_handler
to add custom responses for HTTP status codes, so the errors match the look and feel of the rest of the site.
MaxMind offer databases you can do to look up IP addresses without sending the address off to a remote service.
By reading the code for the pytest-random-order
plugin, I was able to write a new plugin that runs a random subset of tests.
You can use sqlite-utils on the command line to create a SQLite database from a CSV file.
The sqlite3.connect(…)
context manager will hold connections open, so you need to remember to close it manually or write your own context manager.
I wrote some shell config to smooth out the experience of using virtual environments in Python.
Calling browser.set_ca_data(cafile=certifi.where())
will tell where mechanize can find some local SSL certificates.
Looking for search queries that came from robots, not real people.
My Apple Watch knows where I am, which is handy when I have a camera that doesn’t.
A couple of functions I use to get access to CloudFront logs as easy-to-use iterators.
A function to find all the files in a directory is one of my most-used snippets.
Using collections.UserDict, we can create a dictionary where dict[key1] and dict[key2] always point to the same value.
How do you make sure everyone gets to work with everyone else?
Getting something that looks more like the output of the ListObjectsV2 API.
When I’m writing templates with Jinja, strict behaviour is what I want, even if it’s not the default.
Some Python code for turning MRI scans of fruit and veg into animated GIFs.
Digging into a throwaway comment in the Python documentation.
How do you pick the right combination of planks to lay a wooden floor? Python and itertools to the rescue!
A script that allows me to ignore folders like “target” and “node_modules”, so they don’t appear in search results.
A Python script that finds CloudWatch Alarms which are based on a now non-existent source.
Diving into the internals of the AWS SDK to find deleted secrets.
A Python script that shows me how often I’ve been journalling, so I can track my progress.
Making it easier to see how long a file transfer will take, in the terminal.
If your Python script creates a file that you don’t want to track in Git, here’s how you can ignore it.
A Python function that generates every item in a DynamoDB table.
A script that downloads the nicely formatted AO3 downloads for everything I’ve saved in Pinboard.
I want to assign a bunch of variables to True, but I don’t know how many there are. Reflection to the rescue!
Experimenting with a way to store words and phrases that highlights the connections between them.
Adjusting the hue to get different colour variants of the same image.
A web app to generate mashups of Norse valknuts and Pride flags.
YAML allows you to execute arbitrary code in a parser, even if you really really shouldn’t.
The filecmp module has a confusing API, and it just caught me out.
Using unique prime factorisations and itertools to find all the divisors of a number.
Python functions for getting a list of keys and objects in an S3 bucket.
Explaining some code for moving files around in a way that’s atomic and works across filesystem boundaries.
Code for processing large objects in S3 without downloading the whole thing first, using file-like objects in Python.
Some notes on trying to do this in a way that supports both Python 2 and 3, and the frustration of doing so.
A snippet for iterating over an arbitrary iterable in chunks, and returning a smaller chunk if the boundaries don’t line up.
A script that creates temporary credentials for an assumed IAM role, and stores them in ~/.aws/credentials.
Calling json.dumps(…, separators=(',', ':'))
will reduce the amount of whitespace in the final string.
A snippet to make it a bit easier to debug errors in AWS Lambda functions written in Python.
A Python snippets for drawing bar charts in command-line applications.
If you use Python’s subprocess module, be careful you don’t leak sensitive information in your error logs.
Code for saving every message from an SQS queue, and then saving the messages to a file, or resending them to another queue.
Python functions for getting a list of keys and objects in an S3 bucket.
A detailed breakdown of how I wrote a Python script to download logs from CloudWatch.
I often have code I want to run against every HTTP response (logging, error checking) — event hooks give me a nice way to do that without repetition.
How I use pip-tools to ensure my Python dependencies are pinned, precise, and as minimal as possible.
Why I love docopt as a tool for writing clean, simple command-line interfaces.
I wrote a small Python module for lazy file reading, ideal for efficient batch processing.
A short Python function for getting a list of keys in an S3 bucket.
AO3 doesn’t have an official API for scraping data - but with a bit of Python, it might not be necessary.
AO3 doesn’t have an official API for scraping data - but with a bit of Python, it might not be necessary.
Pop quiz: if I lowercase a string, does it still have the same length as the original string?
If you need to store passwords in a Python application, use the keyring module to keep them safe.
Take a regular tiling of the plane, apply a random colouring, and voila: a unique wallpaper, courtesy of the Python Imaging Library.
Using the Python Imaging Library to draw regular tilings of squares, triangles and hexagons.
Why py.test is my unit test framework of choice in Python.
A pair of Python scripts I’ve been using to clean up my mess of directories.
A quick Python function to follow a redirect to its eventual conclusion.
A Python script I wrote that let me sends web pages from my Mac and my iPhone to my Kindle.
Testing with randomly generated examples can be a good way to uncover bugs in your code.
A Python script for finding 404 errors in my Apache web logs - and by extension, broken pages.
A quick python-smtplib wrapper for sending emails through Fastmail.
Using Alfred and a Python script to retrieve artwork from the iTunes, App and Mac App Stores.
If you want to create a file, but only if it doesn’t already exist, Python 3 has a helpful new file mode x
.
Playing with a tiny computer that runs Python.
A review of Effective Python, by Brett Slatkin.
Configuring an IPython notebook server that is always running and easily accessible in Windows.
A Python script for non-destructive file copying/moving.
A web app for applying syntax highlighting to code using the Pygments library.
A script for automatically backing up bookmarks from Pinboard