Have you ever tried to add a helpful output for showing the progress of a slow management command but all the output frustratingly appears in one go after the script has finished? You’ve tripped into something called output buffering and luckily it’s very easy to fix.
self.stdout instead of
print in management commands
You should never use
print inside Django management commands as they have a special
self.stdout method that makes testing easier. This method frustratingly takes slightly different arguments than print, but it also has more features like styling. Here’s how you would do a simple row of dots that grows iteratively:
self.stdout(".", ending="", flush=True) self.stdout.flush()
flush(). This is wat forces the output to be shown to the user before the script finishes. And the same with print:
print(".", end="", flush=True)
print will add newline to the output by default but you can disable that by explicitly setting the ending as an empty string. And when you flush your output manually, you’ll get nice and interactive console output for your management commands — voilà!
(Btw. If you have ever wondered about
ENV PYTHONUNBUFFERED 1 in some of the Docker images for Python, this is why; disabling output buffering makes reading Docker logs way easier.)
The publishing frequency of this blog has been somewhat .. irregular to say the least. The previous attempt to bring it to life didn’t quite catch on in the end as a positive problem called life got in the way. But now there’s been just too long break from blogging in English for me so I had to revitalize this project once more. Cue Gridsome.
Gridsome is an interesting static site generator built for Vue. It can read all kinds of data sources from REST APIs to Markdown files and then build the end result as a fully static site that can be deployed very easily pretty much anywhere. I opted for Netlify as I’ve found it super easy and reliable way to host static sites straight from GitLab.
The migration from a fully dynamic Django site to a fully static Vue site was a somewhat interesting experience, I’m planning to write about it in near future. But for now, here’s to yet another awakening of the Hoyci Blog!