Jun 15, 2012

Resource Paths

After installing Python 2.7 (I hear that 3.x is not yet widely adopted, like the holdouts still running Windows XP) and Django, I loaded up what looks like the "official" tutorial and followed closely. Right away you get started creating a directory structure for a main project with room for applications (modular sub-components). Within the program files (aka modules or namespaces) there would be what looked like references to some kinds of resources "out there" in the system. For example:

<within settings.py>

<within views.py>
from django.db import models

I see this stuff with all the "dots" but it was up to my imagination what it meant, whether it was a metaphorical path to some object structure loaded in the back end or a literal path to a real file I could also open and investigate. This mattered because when I started trying to build out the project, Django would complain that didn't recognize some of the objects I was trying to implement. It turns out those "dot" elements generally do indicate a literal path to a recourse. Within the settings.py module, the line "django.contrib.auth" really does point to a file: "~/dev/Django-1.4/django/contrib/auth" (as I have it set on my system). Likewise, within the views.py module, the line "from django.db import models" instructs to look in the folder "~/dev/Django-1.4/django/" and import the package 'models'.

The main thing to understand is that Python relies on getting a "heads up" as to where it should find the modules and packages you mention. Python has set of directories in its "PYTHONPATH" environment variable, and when you pass some resource path, Python will traverse its PATH directories to look for an appropriate match. You can add your own directory names in a file you create a file with a ".pth" extension in the directory "/usr/lib/python2.7/dist-packages". Now you will need to be careful with your resource path naming conventions. For example, in the settings.py file under "INSTALLED_APPS", if my project name were "survey" with the app "polls" and I included the path to that project directoy in my ".pth" file, then I'd be in trouble if I included "survey.polls" as an installed app. Python would be confused because it's looking for an app named "survey.polls" instead of just "polls" within the "survey" project directory on the Python PATH.

No comments:

Post a Comment