Saturday, May 24, 2008

Using Django in command-line scripts

Over at this page is a reference to "Using Django in command-line scripts". Those tricks, which seem to load in enough of the django environment, weren't working for me in more complext db operations. I made a little change to the setup described there, to force a loading of more of the django environment, and so far all of the operations that work rom within a django web-server can now be called from the command line, at least for me.

In these cases, I'm running the standalone pythong scripts (e.g. foo.py) from 2 directories below where the "manage.py" and "settings.py" scripts exist.

Here's the code that starts all of the stand-alone python scripts running in that directory:


##################################### BEGIN DJANGO PREAMBLE ####################################################################
import os, sys
# Preamble so we can use Django's DB API
django_manager_dir = os.path.normpath(os.path.dirname(os.path.abspath(__file__)) + "/../.." ) + "/";
sys.path.append(django_manager_dir)
from django.core.management import execute_manager
import settings
execute_manager(settings, argv=["blah","validate"])
###################################### END DJANGO PREAMBLE #####################################################################


After that preamble I seem to be able to use any of the django db calls without a problem. Calling execute_manager(.."validate") seems a little silly, since it should be like a no-op, but obviously it does something important for setting up the environment.


FOLLOWUP: By using the suggestions at http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/ there's a better approach. Replace the last three lines with these:
from django.core.management import setup_environ
import settings
setup_environ(settings)

Friday, May 16, 2008

iTunes won't recognize iPhone after Leopard upgrade

I had this problem too. Reinstalling iTunes solved it, and no data was lost.