开发者

How to properly share code between applications in a django project

开发者 https://www.devze.com 2023-04-06 13:56 出处:网络
I have several applications in my django project. I wou开发者_Python百科ld like to re-use some of the functions across all of my apps. I created a new app, and added a custom functions.py to it. Tryin

I have several applications in my django project. I wou开发者_Python百科ld like to re-use some of the functions across all of my apps. I created a new app, and added a custom functions.py to it. Trying the following:

from myNewApp import *
from myNewApp import functions

I get NameError: global name xxx is undefined

Am I omitting something important?

How would you recommend I solve the problem of re-using code across multiple apps?

Thanks,


Make sure that the directory above the app is on your PYTHONPATH


Imagine that you have a project called commons where you store all the code you want to share. And then you want to use the code of commons in a project called foo. Imagine that you have the follow directories:

/home/shared/commons.py
/home/tim/projects/foo.py

The commons.py have this content:

def say_hello():
    return "Hello World!"

If you want to be able to import the module commons in your file test.py put in this file:

import sys
sys.path.append("/home/shared/")

import commons
print commons.say_hello()

And it will print "Hello world!".


You can use either a folder in the route of your project (in which you can create the functions you want and then import them to the desired app/file) or, you can either use a app/utils.py file, the problem that I have with this one is the fact that, maybe another app that wanted to use your functions/objects from the app/utils.py will have a direct reference linked to it e.g:

from app.utils import my_desired_function

Hope it helps :)

0

精彩评论

暂无评论...
验证码 换一张
取 消