The concept of cleanup after application run time is nothing new, but often ignored or forgotten by developers. What happens during cleanup all depends on the application. This might mean closing and deleting temporary files, removing session data, or deleting a PID (Process ID) file for example.
To allow for application cleanup not only within your program, but also external plugins and extensions, there is the
app.close() method that must be called after
app.run() regardless of any exceptions or runtime errors.
You can optionally configure your application to automatically call
sys.exit() as well as set the status code that your application exists with via the meta option App.Meta.exit_on_close as well as setting
from cement import Appclass MyApp(App):class Meta:label = 'myapp'exit_on_close = Truewith MyApp() as app:try:app.run()except SomeException as e:# do something with eapp.log.fatal('Caught Exception: %s' % e)app.exit_code = 100
Note the use of the
App.exit_on_close meta option. Cement will not call
sys.exit() unless this is set to
True. You will find that calling
sys.exit() in testing is very problematic, therefore you will likely want to enable
exit_on_close in production, but not for testing as in this example:
# create a separate class for unit testsclass MyTestApp(MyApp):class Meta:exit_on_close = False
Any extension, or plugin, or even the application itself that has cleanup code should do so within the
post_close framework hooks to ensure that it gets run.
def my_cleanup_code(app):# do something to cleanupif os.path.exists('/path/to/some/dir'):os.remove('/path/to/some/dir')def load(app):app.hook.register('pre_close', my_cleanup_code)