No module named urls / no response with django + mod_wsgi - python

I have a functioning Django application on the local development server, however when deyploying it to an Apache + mod_wsgi setup the urls don't seem to get resolved correctly, i.e. the url module within an installed app cannot be loaded. I have been debugging this for quite some time now and would greatly appreciate some help.
There is actually no real error message in the apache logs, so there might be some infinite loop going on, but I wouldn't know where or why. After a long time the request ends with error code 500 and log message: "Daemon process deadlock timer expired, stopping process 'Tianjin'." I found the url import to be the problem through painful debugging and print statements and realizing this is the point where the application gets stuck. The stack is something like this, where import(name) never returns with name being "Tianjin.urls".
import_module [__init__.py:37]
urlconf_module [urlresolvers.py:396]
url_patterns [urlresolvers.py:402]
resolve [urlresolvers.py:366]
get_response [base.py:119]
My setup:
Linux 4.2.0-27-generic #32-Ubuntu SMP x86_64 GNU/Linux
Apache/2.4.12 (Ubuntu) Server MPM: forked threaded
Python 2.7 in a virtual environment called env in the project folder
mod_wsgi-4.4.21, compiled from sources
Django 1.8.5
Directory structure in /home/TianjinAdmin/:
-IRIS
-env
-..
-Tianjin
- __init__.py
- celery.py
- settins.py
- urls.py
- wsgi.py
-TianjinUI
- __init__.py
- admin.py
- models.py
- tests.py
- urls.py
- views.py
-TianjinBE
- ...
- manage.py
Apache Virtual Host Configuration:
<VirtualHost *:80>
ServerAdmin bla#gmail.com
DocumentRoot /var/www/html
#LogLevel info ssl:warn
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
Alias /static /home/TianjinAdmin/IRIS/templates/TianjinUI/app
<Directory /home/TianjinAdmin/IRIS/templates/TianjinUI/app>
Require all granted
</Directory>
<Directory /home/TianjinAdmin/IRIS/Tianjin>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIDaemonProcess Tianjin python-path=/home/TianjinAdmin/IRIS:/home/TianjinAdmin/IRIS/env/lib/python2.7/site-packages processes=2 threads=15 display-name=%{GROUP}
WSGIProcessGroup Tianjin
WSGIScriptAlias / /home/TianjinAdmin/IRIS/Tianjin/wsgi.py
</VirtualHost>
Tianjin/wsgi.py
import os, sys
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Tianjin.settings")
#tried with and without the following two lines
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../../")))
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../")))
print >> sys.stderr, sys.path
application = get_wsgi_application()
relevant Content of Tianjin/settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#'kombu.transport.django',
'kombu.transport.django.KombuAppConfig',
'djcelery',
'TianjinBE',
'TianjinUI',
)
ROOT_URLCONF = 'Tianjin.urls'
Tianjin/urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^ui/', include('TianjinUI.urls')),
url(r'^oauth/', include('TianjinBE.urls')),
url(r'^admin/', include(admin.site.urls)),
]

Turns out, it had nothing to do with my configuration. Somewhere hidden in the logs and sometimes swallowed was the warning "Matplotlib is building the font cache using fc-list. This may take a moment.". So I had a 3rd party python library for matplot that blocked the application. Seemingly because of some permissions problem on caching files, see matplotlib taking time when being imported

Related

django mod_wsgi and apache: module not found error

I am trying to move my django project to production using apache2 and mod_wsgi. I keep getting a wsgi_error "ModuleNotFoundError" in the apache logs.
I run on ubuntu 22.04.
After going through the various posts on the web I still am not getting anywhere, so I have now started from scratch by creating a new example django app. The same error occurs.
PS, When I use "runserver" the django app displays fine in the browser. Also a simple wsgi "hello_world" app runs fine in apache. So I think the basic setup is fine.
I have created a django test application "mytest" with django-admin startproject mytest
The project is created in /home/user/myprojects/mytest, the group of all directories is www-data
In mytest I have the usual django structure
home/user/myprojects/mytest
manage.py
mytest
asgi.py
__init__.py
settings.py
urls.py
wsgi.py
The wsgi.py is:
(The django/python runs in a virtual environment I found that I needed to add code to the wsgi to actually activate the virtual environment)
"""
WSGI config for mytest project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/
"""
python_home='/home/user/.virtualenvs/myproject'
activate_this= python_home + '/bin/activate_this.py'
with open(activate_this)as f:
code=compile(f.read(),activate_this,'exec')
exec(code, dict(__file__=activate_this))
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mytest.settings')
application = get_wsgi_application()
The apache 000-default.conf is:
WSGIDaemonProcess mytest
WSGIProcessGroup mytest
WSGIScriptAlias /mytest /home/user/myprojects/mytest/mytest/wsgi.py
<Directory /home/user/myprojects/mytest/mytest>
Require all granted
</Directory>
With this setup if I run "python manage.py runserver my_ip_addr" (my_ip_addr added to allowed hosts in the settings file) I can browse to my_ip_addr and the "install worked succesfully" is displayed
Running through standard web (apache) shows:
ModuleNotFoundError: No module named 'mytest'
If I take out the django and get_wsgi_aplication part and add code to display Hello_World, like:
import os
def application(environ, start_response):
status = '200 OK'
output = b'Hello World!'
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
Then indeed hello_world is displayed
However, I cannot find why the wsgi mytest application does not run
It should rather be:
WSGIScriptAlias / /home/user/myprojects/mytest/mytest/wsgi.py
instead of:
WSGIScriptAlias /mytest /home/user/myprojects/mytest/mytest/wsgi.py
I think I solved it finally, due to this post:
Django+Apache ModuleNotFoundError: No module named 'myproject'
I had to add the project folder paths to the wsgi.py as follows:
sys.path.append('home/user/project/mytest')
sys.path.append('home/user/project/mytest/mytest')
The link to the django-served page is then:
http://ip_addr/mytest/mytest
The the comment by #NixonSparrow about the WSGIScriptAlias also made sense: changing that to WSGIScriptAlias / /home/user/project/mytest/mytest/wsgi.py then changed the browser link to http://ip_addr/mytest
The setup that worked is:
Apache configuration:
WSGIScriptAlias / /home/user/project/mytest/mytest/wsgi.py
<Directory /home/user/project/mytest/mytest>
Require all granted
</Directory>
wsgi.py:
python_home='/home/user/.virtualenvs/project'
activate_this= python_home + '/bin/activate_this.py'
with open(activate_this)as f:
code=compile(f.read(),activate_this,'exec')
exec(code, dict(__file__=activate_this))
import os
import sys
sys.path.append('home/user/project/mytest')
sys.path.append('home/user/project/mytest/mytest')
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mytest.settings')
application = get_wsgi_application()
settings.py, installed_aps:
INSTALLED_APPS = [
'mytest',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
urls.py:
urlpatterns = [
path('mytest/',views.index,name='index'),
path('admin/', admin.site.urls),
]
views.py:
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse("<h1>MyTest Hello World ....</h1>")

Deploy Django Server on Apache+Ubuntu on a special port

I have done a simple Django Project for university.
Now I want to show it on my own hosted virtual server, like www.myserver.com:8001
I'm using Ubuntu 14.04 with apache2.
In /etc/apache/site-available I have a con file named: uniproject.conf
<VirtualHost *:8001>
DocumentRoot "/var/www/uniproject/"
Servername www.myserver.com:8001
Alias /static /var/www/uniproject/static/
WSGIScriptAlias / /var/www/uniproject/uniproject.wsgi
<Directory /var/www/uniproject/>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
In /etc/apache2/ports.conf I wrote Listen 8001
In /var/www/uniproject/uniproject.wsgi
import os
import sys
sys.path = ['/var/www/uniproject'] + sys.path
os.environ['DJANGO_SETTINGS_MODULE'] = 'uniproject.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
After a2ensite uniproject.conf and service apache2 restart I'm calling www.myserver.com:8001
there comes
Not Found
The requested URL / was not found on this server.
My goal is to have, later on, about running three to five django apps/servers on my site reachable like
www.myserver.com:8001, www.myserver.com:8002, www.myserver.com:8003, etc ...
but what I do wrong?
I'm using Django 1.7.1 without virtualenv
The Apache Log says:
Target WSGI script not found or unable to stat: /var/www/uniproject, referer: http://www.myserver.com:8001/
The file structure in /var/www/uniproject is:
db3.sqlite
uniproject
uniprojectBackend
uniprojectwsgi
manage.py
static
templates
In /var/www/uniproject/uniproject are the default django files when creating a new project (setting.py, urls.py, wsgi.py, __init__.py)
drwxr-xr-x 7 root root 4096 Dec 21 21:50 uniproject
Ok here is how I solved my issue.
I'm now disabling the port stuff and use subdomain instead.
HOWTO: "Deploy various numbers of Django Apps on Apache2 running on Ubuntu 14.04"
First:
cd /etc/apache2/site-available
sudo nano someproject.conf
in someproject.conf:
<VirtualHost *:80>
ServerName someproject.mysite.com
ServerAlias www.someproject.myssite.com
DocumentRoot "/var/www/someproject/"
Alias /static /var/www/someproject/static/
WSGIScriptAlias / /var/www/someproject/wsgi.py
<Directory /var/www/someproject/>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
after that run:
sudo a2ensite someproject.conf
sudo service apache2 restart
Second:
cd /var/www/
django-admin.py startproject someproject
cd someproject
sudo nano wsgi.py
in wsgi.py
import os
import sys
path = '/var/www/someproject'
if path not in sys.path:
sys.path.append(path)
os.environ['DJANGO_SETTINGS_MODULE'] = 'someproject.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
now visit: someproject.mysite.com
This is done with django 1.7.1
Make Sure all python modules are also installed (e.g. lxml, feed parser etc.)
Sometimes there will be a bug (happen to me) in settings.py
remove or comment in settings.py:
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
#'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
After every edit in the django project run
sudo service apache2 reload
Hope this helps anyone.
With this method I'm running three django server/apps on my VM.

Deploy django with apache2

(I am in way over my head) I am trying to deploy my django server on apache2. I have already buildt a quite large front-end application (that is currently deployed with apache2) and do not want to serve any views through django, rather I want to follow the backend as service principal.
I have followed the instructions here:
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/modwsgi
After the modwsgi part I get this in my apache log file:
[Tue May 20 12:19:44 2014] [notice] Apache/2.2.22 (Debian) PHP/5.4.4-14+deb7u8 mod_wsgi/3.4 Python/2.7.3 configured -- resuming normal operations
After appending this to the apache config file:
LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so
WSGIScriptAlias / /var/www/PhotodiceServer/PhotodiceServer/wsgi.py
WSGIPythonPath /var/www/PhotodiceServer
<Directory /var/www/PhotodiceServer/PhotodiceServer>
<Files wsgi.py>
Order deny,allow
Allow from all
</Files>
</Directory>
This is the content of the wsgi file:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "PhotodiceServer.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
This is the content of the urls.py file:
from django.conf.urls import patterns, include, url
from django.contrib.auth.models import User, Group
from rest_framework import viewsets, routers
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browseable API.
url(r'^admin/', include(admin.site.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
)
# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
model = User
class GroupViewSet(viewsets.ModelViewSet):
model = Group
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'groups', GroupViewSet)
This is the installed apps:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'photod',
)
previously when i entered the ip of the webserver (a raspberry pi) i was automagically routed to index.html that is stored in var/www/.
Now when i enter the ip of the webserve i get 404 page not found, do i have to explicetly say what url will load a static file somehow? and how will this play with the routing in angular? (I have used the angular-ui-router.js)?
(if i set debug =False i get Bad Request (400) instead)
I think you are missing a couple of things in your Apache config:
AddHandler wsgi-script .py
In <Directory xxx>
Options +ExecCGI
SetHandler wsgi-script
Try these, and see what it says then.
EDIT*** as your clearly not familiar with apache!!
LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so
AddHandler wsgi-script .py
WSGIScriptAlias / /var/www/PhotodiceServer/PhotodiceServer/wsgi.py
WSGIPythonPath /var/www/PhotodiceServer
<Directory /var/www/PhotodiceServer/PhotodiceServer>
Options +ExecCGI
<Files wsgi.py>
Order deny,allow
Allow from all
</Files>
</Directory>
Another EDIT***
Here is the config I used, (although in the end I just ran uWSGI server and ProxyPass to it as it was a bit of a pain!!)
<VirtualHost *:80>
ServerName my.local.domain
SetEnv APPLICATION_ENV development
Alias /favicon.ico /path/to/project/favicon.ico
AliasMatch ^/static/(.*)$ /path/to/project/static/$1
AddHandler wsgi-script .py
WSGIScriptAlias / /path/to/project/project/wsgi.py
WSGIDaemonProcess _WSGI user=chazmead group=www-data processes=1 threads=5 python-path=/path/to/project/venv/lib/python2.7/site-packages:/path/to/project
WSGIProcessGroup _WSGI
<Directory "/path/to/project/project/">
SetHandler wsgi-script
Options Indexes FollowSymLinks ExecCGI
Order Allow,Deny
Allow from all
</Directory>
</VirtualHost>

Deploying Django project on Apache using Mod_wsgi

I am deploying a Django project on Apache. and after configuration, I open the "localhost" in the browser, and nothing showed up and the status bar just keep saying "Waiting for localhost". Here is some info.
1.Environment:
OS: Red Hat Enterprise Linux Server x86
Python: 2.7.2
Django: 1.3.1
Mod_wsgi: 3.3
Apache: 2.2.21
Django project: /var/www/html/server/video1
2.Apache Config file lines added:
LoadModule wsgi_module modules/mod_wsgi.so
WSGIScriptAlias / /var/www/html/server/video1/apache/django.wsgi
Alias /media/ /usr/local/apache2/htdocs/media/
Alias /static/ /usr/local/apache2/htdocs/static/
<Directory "/var/www/html/server/video">
Order Deny,Allow
Allow from all
</Directory>
<Directory "/usr/local/apache2/htdocs/media">
Order Deny,Allow
Allow from all
</Directory>
<Directory "/usr/local/apache2/htdocs/static">
Order Deny,Allow
Allow from all
</Directory>
3.Django.wsgi file:
import os
import os.path
import sys
sys.path.append('/var/www/html/server')
sys.path.append('/var/www/html/server/video')
os.environ['DJANGO_SETTINGS_MODULE'] = 'video1.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
4.settings.py lines added:
MEDIA_ROOT='/usr/local/apache2/htdocs/media/'
MEDIA_URL='/media/'
STATIC_ROOT='/usr/local/apache2/htdocs/static/'
STATIC_URL='/static/'
ADMIN_MEDIA_PREFIX='static/admin'
TEMPLATES_DIR = {
"/var/www/html/server/video1/templates"
}
INSTALLED_APPS = {
'django.contrib.admin'
}
5.restart apache
These are what I did, can someone help me to see if somewhere is wrong?
Thank you very much
The path '/var/www/html/server/video' doesn't match what you have in WSGIScriptAlias.
Besides that, did you actually try and deploy a WSGI hello world program first?
Also try setting LogLevel to info in Apache instead of warn. The Apache error log will then contain messages to say whether the WSGI script file is loaded. Right now not obvious whether your browser can't even contact server, or whether WSGI application loaded, but not responding.

Django WGSI paths

I am having problems setting up wgsi with django. I'm following this http://docs.djangoproject.com/en/dev/howto/deployment/modwsgi/ . Yet I am still really confused as to where to put the .wsgi file and if I need to set the sys.path. I have tried it both directly outside and inside the web root and I can't get anything to work as expected.
# /home/ben/public_html/django_test/testproject/apache/django.wsgi:
import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'testproject.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
Relivant apache conf:
DocumentRoot "/home/ben/public_html/django_test/testproject/"
WSGIScriptAlias / "/home/ben/public_html/django_test/testproject/apache/django.wsgi"
Apache Logs Error (standard apache 500 page):
ImportError: Could not import settings 'testproject.settings' (Is it on sys.path? ...
I can at get django to at least throw an error of it's own by using this:
import os
import sys
path = '/home/ben/public_html/django_test/testproject'
if path not in sys.path:
sys.path.append(path)
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
which resulted in this django error page:
ImportError at /admin/
No module named testproject.urls
I put the wsgi at same level than settings.py, and looks like this:
import os
import sys
sys.path.insert(0,os.sep.join(os.path.abspath(__file__).split(os.sep)[:-2]))
os.environ['DJANGO_SETTINGS_MODULE'] = 'yourprojectname.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
this is the apache conf file:
NameVirtualHost *:80
<VirtualHost *:80>
ServerAdmin webmaster#localhost
ServerName www.yourprojectname.com
Alias /media/ /home/diegueus9/workspace/yourprojectname/media/
<Directory /home/diegueus9/workspace/yourprojectname/media/>
Order deny,allow
Allow from all
</Directory>
WSGIScriptReloading On
WSGIDaemonProcess yourprojectname
WSGIProcessGroup yourprojectname
WSGIApplicationGroup yourprojectname
WSGIPassAuthorization On
WSGIScriptAlias / /home/diegueus9/workspace/yourprojectname/yourfile.wsgi
ErrorLog /var/log/apache2/yourprojectname-error.log
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel debug
CustomLog /var/log/apache2/yourprojectname-access.log combined
</VirtualHost>
As a quick fix you can, next to adding this to sys.path:
path = '/home/ben/public_html/django_test/testproject'
also add this:
path2 = '/home/ben/public_html/django_test'
You can also change Python path in your Apache VirtualHost:
WSGIDaemonProcess [...] python-path=/home/ben/public_html/django_test
But you should also review mod_wsgi docs and learn what Graham Dumpleton advises there.
Here is a nice tutorial that shows you how to use mod_wsgi with Django and also some other items that are not related to this question.
I just spent a few hours troubleshooting this very issue and my fix was SELinux was prohibiting access to my /django/ folder.
To check if SEStatus is blocking your access, view the log at /var/log/audit/audit.log
My fix was a simple:
restorecon -R /var/www/django/

Categories

Resources