Login

set_paths

Author:
amitu
Posted:
October 14, 2008
Language:
Python
Version:
1.0
Score:
0 (after 2 ratings)

To make all scripts relocatable.

The layout of my project is:

/some/path/myproject/
/some/path/myproject/some_script
/some/path/myproject/some_other_script
/some/path/myproject/set_paths.py
/some/path/myproject/setttings.py
/some/path/myproject/lib/ # some external libraries/apps checked in with my project.
/some/path/myproject/myapp/ # my apps etc.

This way myproject folder can be moved anywhere on the file system, and calling right path, settings.py is used.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# content of set_paths.py:
import sys, os
import path # http://www.jorendorff.com/articles/python/path/
def set_paths(f):
    p = path.path(f)
    sys.path.append(str(p.parent.joinpath("..").abspath()))
    sys.path.append(str(p.parent.parent.joinpath("lib/").abspath()))
    os.environ["DJANGO_SETTINGS_MODULE"] = "myproject.settings" 

# usage: 
# contents of file "some_script":
#!/usr/bin/python

import set_paths
set_paths.set_paths(__file__) # this must be the first thing in the script.

from myproject.myapp.models import MyModel
print MyModel.objects.count() # whatever.

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 9 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
  5. Help text hyperlinks by sa2812 1 year, 5 months ago

Comments

Please login first before commenting.