In mine, models.py
I am opening some files and database connections. Where can I put the code to ensure that these files / connections are closed when the server shuts down?
You can use python with instruction. This allows you to clean up after yourself. That is, the files are closed.
Here's a good tutorial: http://effbot.org/zone/python-with-statement.htm