I have been programming for a while, but never really got deep into it. Now I'm working in a reasearch center and I need to make my stuff coherent and compatible. My coworkers proposed to me a "Standard" method of organizing my project:
Project
|_ LICENCE.txt
|_ README.txt
|_ code
|_ main.py
|_ __init__.py
|_ tests
|_ context.py
|_ test_main.py
That way they say it will be easier to do unit testing and all.
I have visited tens of websites that do exactly the same thing, so I figured it wouldn,t be that bad: wrong. I have been trying for the whole weekend now to make this work and I feel like I'm just getting colder.
Here is what I have:
IDE image with project structure with context.py open in the window
From what I have read in the past few days, This is the correct method, my problem is, no matter how I write it, the code won't recognize bidon.py, nor the funcitons defined in it.
bidon.py is just a file containing
def add(x, y):
return x+y
def sub(x, y):
return x-y
in context it is not possible to use the function add, but when the test file and the .py are in the same folder, it seems to work...
But why doesn't it work even though I have added the path? I tried (in the context.py):
import code
import code
import bidon
from code import bidion
from code import *
from code import bidon
from bidon import *
from code import bidon
from bidon import add
none of these worked.
It gets worse when I try to use the context.py in a test file.
For example in test_bidon.py, I have
import unittest
from .context import code
class TestBidon(unittest.TestCase):
def test_add(self):
result = add(10, 5)
self.assertEqual(result, 15)
if __name__ == "__main___":
unittest.main()
This creates an error telling me that test_bidon.py is not a package?
Again, I tried multiple combinaisons, none worked. Please help me figure this out! I'm out of options and I don't want to spend another day looking for nothing.
I have found a way to do what I wanted. I made a github of my Basic project architecture as I wanted it. There is still work to do in the setup file, but the master now works.
url: https://github.com/PyMarc2/BasicProjectArchitecture
Basically, I don't know why, but it didn't work well when the setup file was in the test folder. Instead, put the setup file right in the project folder.
(os.path.abspath(os.path.join(os.path.dirname(__file__), testFolderNameSetup)))
That command is what saved me.
Thank you!
Related
I'm trying to load a signal every time the app gets loaded. (I'm watching a tutorial and I have to do it like that don't ask me why)
In the tutorial the guy edits the init.py file of the app like follows:
default_app_config = 'payment.apps.PaymentConfig'
Now my Problem:
I put all my apps in a subfolder "apps" for more overview in my project.
So thought I have to write that line like follows:
default_app_config = 'apps.Pages.apps.PagesConfig'
(My app is called Pages)
If I try it I get the error in the title.
I also tried to just write: Pages.apps.Pagesconfig but this didn't work either.
I'm open for any ideas. Tanks
everybody! I want to access to constants value that I declare in my setting.py file to use in my template, but not in a template inside the app, I just want to use in my home template the template that I declare in my setting file.
CMS_TEMPLATES = (
## Customize this
('page.html', 'Page'),
('feature.html', 'Page with Feature'),
('homeTemplate.html', 'Home Template') // I want to use here
)
I found this example about the same problem in StackOverflow, but all case uses the variable inside apps not in top level.
How is the best way to use this value inside this template!!
I'd start by asking - why do you want to do that? It seems like an odd way of... adjusting the templates directories that you're using, i guess??
I wonder if you may have an XY problem. If you post what you're trying to achieve, that might be better than a specific solution to this specific problem.
Broadly though, you can only serve django variables (including from settings.py) inside a project or script that's using Django, or at least its environments. Doing from django.conf import settings imports the settings that are available at the highest level in the project, across all of the apps. Projects are laid out in this rough fashion.
myproject -
- myapp1
- myapp2
- myproject
- settings.py
- wsgi.py
- manage.py
As in this answer, For external scripts, you can still import the django settings thus:
import os
import django
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
django.setup()
# now you can use settings.VARIABLE_NAME
But: this still won't get it into a template, because getting the variable from here into a template needs you to use the django engine to render a response.
If it's not being served by the django system, it's not a template, it's just a regular html file.
If it's a template in another app in your overall project, you would pass it as part of your context dictionary, as laid out in the docs on templates.
first post to SO, so if I'm missing some details, please forgive me.
Is there a way to use relative paths from another subfolder without resorting to modifying sys.path via os? Eventually this will be run from a cgi webserver so I'd rather stay away from any -m arguments to python.exe.
I'm using Python 2.7.3 and have a file/directory structure of the following :
| myprog.py
|
+---functions
| myfunctions.py
| __init__.py
|
\---subfolder
mysub.py
In the root, I have a single .py file, called myprog.py :
#file .\myprog.py
from functions import *
hello("Hi from Main")
In the functions folder I have two files, init.py, myfunctions.py :
#The File: functions\__init__.py :
from myfunctions import *
#The File: functions\myfunctions.py :
def hello(sometext):
print sometext
And finally, in the subfolder, I have :
#The File: subfolder\mysub.py :
from ..functions import *
hello("Hi From mysubprogram")
The myprog.py executes fine (when running python.exe myprog.py from the parent folder), printing "Hi From Main", however, the mysub.py (when executed from the subfolder) keeps putting the error: ValueError: Attempted relative import in non-package
I have tried varying combinations in mysub.py such as from ..functions.myfunctions import * yet none yields the desired result.
I have read a few relevant articles :
using __init__.py
How to import classes defined in __init__.py
http://docs.python.org/2/tutorial/modules.html#packages-in-multiple-directories
But just can't figure this out. Oh, and once I get this working, I would like to remove the import *'s wherever possible, however, I'd rather not have to put the full paths to the hello function each time it's called, so any advise there or on cleaning up the init.py (using all or in another manner) would be a bonus.
Thanks Blckknght EDIT, I also found the below :
Relative imports for the billionth time
Which, if what I'm requesting isn't possible, perhaps I'm asking the wrong thing. If this is just outright bad practice, is the right way to accomplish my goal using sys.path or is there something else someone can recommend (like not calling functions from ../folders) ?
I think the issue has to do with how you are running the mysub.py script. Python doesn't tend to do well with scripts in packages, since the main script module is always named __main__ rather than its usual name.
I think you can fix this by running mysub with python -m subfolder.mysub, or by manipulating the __package__ variable in mysub.py (as described by PEP 366). It's not neat, unfortunately.
I want to run a python recipe I found, but I don't know how as it imports from another one!
For example, I would like to test the code here.
I have downloaded it and also downloaded this one as it uses it.
So how can I test the this code by passing the needed parameter as below?!
>>> G = {'s':{'u':10, 'x':5}, 'u':{'v':1, 'x':2}, 'v':{'y':4}, 'x':{'u':3, 'v':9, 'y':2}, 'y':{'s':7, 'v':6}}
>>> Dijkstra.Dijkstra(G,'s','v')
I have added the two files in one of the python paths, and imported both but still get error
Could you please give me some advice on simple way to test this code?
You really should put the files in your current directory if you are just testing, instead of putting them in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ as that path is reserved for the Python standard library.
It seems that the second recipe, the Priority Dictionary, needs to be put in a file called priodict.py since the Dijkstra code imports from priodict. So, you should have the following files in your current directory: Dijkstra.py, priodict.py. Then you can just start Python and do import Dijkstra, and it should work.
Also, don't modify the Dijkstra code to remove the import as you apparently did...
I've inherited a Django application that I need to modify using a custom template filter. I'm absolutely new to Django and am quite mystified by it. I thought I had followed the instructions exactly, and also followed all the advice from other posts on the subject, but I still get an error when I include the following line in my template:
{% load mlgb_custom_filters %}
My directory structure is as follows:
mysite (i.e. the project)
__init__.py
mlgb/ (i.e. the app)
__init__.py
templatetags/
__init__.py
mlgb_custom_filters.py
The code of mlgb_custom_filters.py is as follows:
from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
#register.filter(name='fix_dashes')
#stringfilter
def fix_dashes( value ):
return value.replace( '--', 'DASH' )
if __name__ == "__main__":
testvar = fix_dashes( "ouch -- ow -- I hate django" )
print testvar
As you can see, I've added a 'name = main' section to let me run it in standalone mode, just to check that there are no errors in that particular file, and it's fine when run in standalone mode.
Based on someone else's advice, I've also tried importing it into another file, just to see whether there was an import error, and once again, it was fine if I added this to the end of settings.py (while using the dev server):
try:
import mlgb.templatetags.mlgb_custom_filters
except Exception, exc:
print 'error importing mlgb_custom_filters'
print exc
Also, INSTALLED_APPS in settings.py includes the line 'mysite.mlgb', and I have also tried putting just 'mlgb' instead of 'mysite.mlgb' there, as yet another person suggested. And I restarted the dev server every time I made a change.
I think I have tried every single suggestion that I have found on the web until now. Does anyone have any new ideas? Could it be anything to do with the fact that I have inherited a directory structure where the template directory is not within the same structure as the application, i.e. it is not under mysite? Scraping the barrel for ideas here! I hope someone can help.
OK, in the situation that I was in when first posting this question, it seems all I actually needed to do was touch a wsgi file under my appname/apache directory to force the application to be refreshed. Yesterday's initial answer was a red herring. Basically I should have touched the file myproject/myapp/apache/myapp.wsgi. Then maybe restart Apache for good measure? But the confusion was caused by the fact that apparently it wasn't enough either simply to restart Apache or to manually recompile the Python. In order to pick up my changes, seems like I needed to touch that wsgi file. Then all is well.
I can now post an answer to my own question thanks to the help of my colleague Masud Khokhar, whose brilliant detective work has saved the day. To recap, my application worked fine until I added a 'load' statement to one of my template files, to load a 'custom filters' module. Masud identified that now I needed to use a full/absolute path to the template file in urls.py instead of a relative one as I had before (and which worked before, until it needed to load the custom filters module). So, in urls.py, I had a section of code as follows:
url(r'^book/(?P<object_id>\d+)/$', 'list_detail.object_detail',
kwargs={
'queryset':Book.objects.all(),
'template_name' : 'mlgb/mlgb_detail.html'
},
name='mlgb_detail'
),
Instead of this:
'template_name' : 'mlgb/mlgb_detail.html'
I needed something like this:
'template_name' : '/THE_FULL_PATH/mlgb/templates/mlgb/mlgb_detail.html'
Made that change - sorted! Thank you once again, Masud.