django_cms ImproperlyConfigured: Error importing middleware cms.middleware.media - django

I'm moving an application that uses django_cms from one server, where everything worked, to another and have spent the last 4 hours trying to find the cause of this error. A suggestions very welcome!
mod_wsgi (pid=21972): Exception occurred within WSGI script '/var/www/vhosts/compdoctest.com/django/compdoc/django.wsgi'.
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 230, in __call__
self.load_middleware()
File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py", line 42, in load_middleware
raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e))
ImproperlyConfigured: Error importing middleware cms.middleware.media: "No module named media"
The offending line is the last one in the middleware list in settings.py
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'cms.middleware.page.CurrentPageMiddleware',
'cms.middleware.user.CurrentUserMiddleware',
'cms.middleware.multilingual.MultilingualURLMiddleware',
'cms.middleware.media.PlaceholderMediaMiddleware',
)
If I remove the final line then the code continues and falls over later saying that item is required in middleware.
I'm using slightly different version of django, 1.2.1 final on the old working server and 1.2.3 final on the new server.
All the things I've tried:
The same version of django_cms - 2.1.0 beta 3 - that was used on the old server
The latest version on github - 2.1.0.beta2-550 Putting the cms, mptt, menus, publisher folders in the
app From python importing the
googled (nobody having the same problem that I can find)
middleware file directly (no problem)
result of opening in python:
python manage.py shell
Python 2.5.2 (r252:60911, Jan 20 2010, 23:14:04)
[GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import cms.middleware.media
>>> cms.middleware.media.__file__
'/var/www/vhosts/compdoctest.com/django/compdoc/cms/middleware/media.pyc'
>>> from django.forms.widgets import Media
>>> import cms.middleware.media
>>>

Thanks to my friend Bartosz Ptaszynski for pointing me in the right direction on this one. It was a path problem. Added this to the top of the settings.py file and it all magically started working.
sys.path.insert(0, '/path_to_app/app/')
And as he pointed out:
Exception occurred within WSGI script means that the path while running under the web server was wrong it's a completely different environment than the manage.py shell

I had the same problem. But since it only occurs when using mod_wsgi, another solution is adding the path in the apache config (rather than editing the syspath inside setting.py):
# mod_wsgi settings
WSGIDaemonProcess name user=user group=group python-path=/app_path/app/:/app_path/lib/python2.6/site-packages/:/app_path/
WSGIProcessGroup polykum
Including the site packages in the path is also given in the example of Jon Black.

Related

how to call python functions defined in another .py file without interactive mode

I wrote two scripts: modbus_master.py and modbus_helpers.py.
modbus_helpers.py is just a bunch of raw functions I defined that I'm trying to call from modbus_master.py.
When I try to execute 'modbus_master.py' from the windows CLI this happens...
C:\Python27\modbus_simulator>modbus_master.py
Traceback (most recent call last):
File "C:\Python27\modbus_master.py", line 3, in <module>
import modbus_helpers
ImportError: No module named modbus_helpers
However,
If I go to python interactive mode and do this...
C:\Python27\modbus_simulator>python
Python 2.7.5 (default, May 15 2013, 22:43:36) MSC v.1500 32 bit (Intel) on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import modbus_master
The code in modbus_master.py that calls modbus_helpers.py works just fine. So how do I bridge this gap here so that I can just do this and run the script without error?
C:\Python27\modbus_simulator>modbus_master.py
Code in modbus_master.py:
import sys
import json
import modbus_helpers
import os
def printRegsets():
print 'these register sets were piped in...\r\n'
regsetIndex = 0
for regset in registersetsList:
print str(regsetIndex) , ':', regset['Name']
regsetIndex = regsetIndex + 1
path = os.path.normpath('C:\Python27\modbus_simulator\export2.txt')
registersetsList = modbus_helpers.getRegisterSetFromACMExportFile(path)
printRegsets()
Found the solution to the problem. There was nothing wrong with the code. I missed the obvious...modbus_master.py must be in the same folder/directory as modbus_helpers.py for the 'import' statement to work.

uwsgi: no app loaded. going in full dynamic mode

In my uwsgi config, I have these options:
[uwsgi]
chmod-socket = 777
socket = 127.0.0.1:9031
plugins = python
pythonpath = /adminserver/
callable = app
master = True
processes = 4
reload-mercy = 8
cpu-affinity = 1
max-requests = 2000
limit-as = 512
reload-on-as = 256
reload-on-rss = 192
no-orphans
vacuum
My app structure looks like this:
/adminserver
app.py
...
My app.py has these bits of code:
app = Flask(__name__)
...
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5003, debug=True)
The result is that when I try to curl my server, I get this error:
Wed Sep 11 23:28:56 2013 - added /adminserver/ to pythonpath.
Wed Sep 11 23:28:56 2013 - *** no app loaded. going in full dynamic mode ***
Wed Sep 11 23:28:56 2013 - *** uWSGI is running in multiple interpreter mode ***
What do the module and callable options do? The docs say:
module, wsgi Argument: string
Load a WSGI module as the application. The module (sans .py) must be
importable, ie. be in PYTHONPATH.
This option may be set with -w from the command line.
callable Argument: string Default: application
Set default WSGI callable name.
Module
A module in Python maps to a file on disk - when you have a directory like this:
/some-dir
module1.py
module2.py
If you start up a python interpreter while the current working directory is /some-dir you will be able to import each of the modules:
some-dir$ python
>>> import module1, module2
# Module1 and Module2 are now imported
Python searches sys.path (and a few other things, see the docs on import for more information) for a file that matches the name you are trying to import. uwsgi uses Python's import process under the covers to load the module that contains your WSGI application.
Callable
The WSGI PEPs (333 and 3333) specify that a WSGI application is a callable that takes two arguments and returns an iterable that yields bytestrings:
# simple_wsgi.py
# The simplest WSGI application
HELLO_WORLD = b"Hello world!\n"
def simple_app(environ, start_response):
"""Simplest possible application object"""
status = '200 OK'
response_headers = [('Content-type', 'text/plain')]
start_response(status, response_headers)
return [HELLO_WORLD]
uwsgi needs to know the name of a symbol inside of your module that maps to the WSGI application callable, so it can pass in the environment and the start_response callable - essentially, it needs to be able to do the following:
wsgi_app = getattr(simple_wsgi, 'simple_app')
TL;PC (Too Long; Prefer Code)
A simple parallel of what uwsgi is doing:
# Use `module` to know *what* to import
import simple_wsgi
# construct request environment from user input
# create a callable to pass for start_response
# and then ...
# use `callable` to know what to call
wsgi_app = getattr(simple_wsgi, 'simple_app')
# and then call it to respond to the user
response = wsgi_app(environ, start_response)
For anyone else having this problem, if you are sure your configuration is correct, you should check your uWSGI version.
Ubuntu 12.04 LTS provides 1.0.3. Removing that and using pip to install 2.0.4 resolved my issues.
First, check your configuration whether is correct.
my uwsgi.ini configuration:
[uwsgi]
chdir=/home/air/repo/Qiy
uid=nobody
gid=nobody
module=Qiy.wsgi:application
socket=/home/air/repo/Qiy/uwsgi.sock
master=true
workers=5
pidfile=/home/air/repo/Qiy/uwsgi.pid
vacuum=true
thunder-lock=true
enable-threads=true
harakiri=30
post-buffering=4096
daemonize=/home/air/repo/Qiy/uwsgi.log
then use uwsgi --ini uwsgi.ini to run uwsgi.
if not work, you rm -rf the venv directory, and re-initial the venv, and re-try my step.
I re-initial the venv solved my issue, seems the problem is when I pip3 install some packages of requirements.txt, and upgrade the pip, then install uwsgi package. so, I delete the venv, and re-initial my virtual environment.

cannot install django-filebrowser app

I did exactly as it says here: http://readthedocs.org/docs/django-filebrowser/en/latest/quickstart.html#quickstart (only used easy_install instead of pip)
it seems that I get an import error when trying to connect to admin interface:
Request Method: GET
Request URL: http://localhost:8000/admin/
Django Version: 1.3
Exception Type: ImportError
Exception Value:
No module named sites
Exception Location: c:\workspace\expedeat\..\expedeat\urls.py in <module>, line 5
Python Executable: c:\Tools\Python26\python.exe
Python Version: 2.6.4
the import the exception comes from is: from filebrowser.sites import site in urls.py
Also testing filebrowser fails with this message:
Creating test database for alias 'default'...
.......F......
======================================================================
FAIL: test_directory (filebrowser.tests.settings.SettingsTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "c:\Tools\Python26\lib\site-packages\django_filebrowser-3.3.0-py2.6.egg\filebrowser\tests\set
tings.py", line 29, in test_directory
self.assertEqual(os.path.exists(os.path.join(MEDIA_ROOT,DIRECTORY)), 1)
AssertionError: False != 1
----------------------------------------------------------------------
Ran 14 tests in 0.008s
FAILED (failures=1)
Destroying test database for alias 'default'...
I must be doing something wrong. Any help would be appreciated.
the sites.py module does not exist in version you are using, so the error message is correct.
the installation doc you are using is for version 3.4. The pip install is 3.3. The difference being in the urls.py
3.4
from filebrowser.sites import site
urlpatterns = patterns('',
url(r'^admin/filebrowser/', include(site.urls)),
)
3.3
urlpatterns = patterns('',
(r'^admin/filebrowser/', include('filebrowser.urls')),
)
The test fails because it's looking for a non-existing directory.
To find out what directory it's looking for, do the following:
% python ./manage.py shell
>>> from django.conf import settings
>>> import filebrowser.settings
>>> filebrowser.settings.MEDIA_ROOT
'/srv/repositories/project/media'
>>> filebrowser.settings.DIRECTORY
'uploads/'
Based on the output, you know what directory it's looking for, /srv/repositories/project/media/uploads in this example. Create the directory and you should be one step further on your way.
Using the "FILEBROWSER_" prefix, you can supply configuration for the filebrowser app.
I use the following in my settings.py :
FILEBROWSER_DIRECTORY = MEDIA_ROOT

Using Django Cache Middleware causes contrib.auth unit tests to fail

Problem: When I add UpdateCacheMiddleware and FetchFromCacheMiddleware to my Django project, I get unittest failures. This is regardless of the CACHE_BACKEND I use (right now I am using locmem://, but the errors are the same when I use file:///path_to_cache)
My Middleware:
MIDDLEWARE_CLASSES = (
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
)
All my test failures look like the one below: 'NoneType' object is unsubscriptable
======================================================================
Error: test_last_login (django.contrib.auth.tests.remote_user.RemoteUserTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Python26\lib\site-packages\django\contrib\auth\tests\remote_user.py",
line 87, in test_last_login
self.assertNotEqual(default_login, response.context['user'].last_login)
TypeError: 'NoneType' object is unsubscriptable
I must be missing something (or doing something wrong) as I have searched around the web for this issue, but no one seems to have encountered it.
Steps to Reproduce:
Start a new django project (django-admin.py startproject myproject) and configure settings.py
Add CACHE_BACKEND to settings.py and add the two Cache Middlewares from Django
Run python manage.py test
Notes: There is only one test failure when using dummy:// cache and it is documented at: http://code.djangoproject.com/ticket/11640
The solution to the failing tests is to set CACHE_MIDDLEWARE_SECONDS to 0 (e.g. set this to be 0 in your dev environment). This will allow the django.contrib tests to all pass.

non-consistent django error

I'm running django on Dreamhost right now with fastcgi, and I'm getting really weird behavior. First, the server runs Python 2.3. On my computer, I'm running 2.6 and all my source code works. When I put it on my host though, nothing works. Right now, when I pkill python and then load a page, the first error complains about a syntax error at 'class Item_list()' line:
from dtms.models import *
class Item_list():
def __init__(self, list = None, house_id = None):
self.list = list
self.house_id = house_id
def ret_list(self):
return self.list
Then, if I reload it again without changing anything, I get this error:
Django Version: 1.1 alpha 1 SVN-10114
Python Version: 2.3.5
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mysite.dtms']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware')
Traceback:
File "/home/victor/django/django_src/django/core/handlers/base.py" in get_response
82. callback, callback_args, callback_kwargs = resolver.resolve(
File "/home/victor/django/django_src/django/core/urlresolvers.py" in resolve
184. for pattern in self.url_patterns:
File "/home/victor/django/django_src/django/core/urlresolvers.py" in _get_url_patterns
212. raise ImproperlyConfigured("The included urlconf %s doesn't have any"
Exception Type: ImproperlyConfigured at /dtms/login/
Exception Value: The included urlconf mysite.urls doesn't have anypatterns in it
Any ideas?
class Item_list():
You can't include an empty inheritance list in Python 2.3. There seems to have been a change in the grammar that allows it now but not then.
It would normally be written:
class Item_list:
if you don't want any base classes. But generally these days you'd want to derive from object to get new-style classes.
I don't know much about your deployment environment, but in general when you've tried to import something and got an exception, it can leave behind partially-initialised modules in sys.modules that will frustrate future attempts to import them, resulting in otherwise inexplicable errors where properties and actions of the module are not where they were expected.
In general once an import has failed you should consider the environment lost and start again, but I don't know how your Django deployment copes with errors like that and process-restarting issues. Maybe the original error has left an interpreter running without having written the expected stuff to url_patterns, or something.