Replace main.app with factory function

Using factory function to create flask.Flask or it's descendants is
very common and useful pattern. It leads to cleaner code at many
places, and much easier testing.

Change-Id: I2262d687a1946a4258ab226b604ac5e6679c44f9