From single to multi-package
When last we left our application, the directory structure looked something like this:
templates/ # Holds Jinja templates
init.py # General application setup
forms.py # User data to domain data mappers and validators
models.py # Domain models
views.py # well … controllers, really.
config.py # Configuration, just like it says on the cover
python run.py to bring the application up locally.
To keep things clear, let’s move the existing forms, models, and views into a tracking sub-package and create another sub-package for our User-specific functionality which we will call users:
tracking/ # This is the code from Part 1
init.py # Create this file - it should be empty.
users/ # Where we are working today
init.py # This is also code from Part 1
This means that we will need to change our import in flask_tracking/init.py from from .views import tracking to from .tracking.views import tracking.
Then there is the database setup in tracking.models. This we will move out into the parent package (flask_tracking) since the database manager will be shared between packages. Let’s call that module data:
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def query_to_list(query, include_field_names=True):
“”“Turns a SQLAlchemy query into a list of data values.”""
for i, obj in enumerate(query.all()):
if i == 0:
column_names = [c.name for c in obj.table.columns]
yield obj_to_list(obj, column_names)
def obj_to_list(sa_obj, field_order):
“”“Takes a SQLAlchemy object - returns a list of all its data”""
return [getattr(sa_obj, field_name, None) for field_name in field_order]
Then we can update tracking.models to use from flask_tracking.data import db and tracking.views to use from flask_tracking.data import db, query_to_list and we should now have a working multi-package application.