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>")
Related
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
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.
I recently moved my Django project to Apache server. I am facing a few issues with respect to dependency modules being inaccessible after moving the project to Apache.
Here are my configuration files:
This is my bemoss.conf file in the sites-available directory of Apache:
WSGIPythonPath /home/kruthika/workspace/bemoss_web_ui
WSGIPythonPath /home/kruthika/workspace/rtunetwork/volttron
WSGIPythonPath /home/kruthika/workspace/bemoss_web_ui/helper
<VirtualHost *:80>
WSGIScriptAlias / /home/kruthika/workspace/bemoss_web_ui/bemoss.wsgi
ServerName bemoss.com
Alias /static /home/kruthika/workspace/bemoss_web_ui/static
<Directory /home/kruthika/workspace/bemoss_web_ui/>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
Here is my bemoss.wsgi file:
import os
import sys
sys.path = ['/home/kruthika/workspace']+sys.path
print sys.path
os.environ['DJANGO_SETTINGS_MODULE']='bemoss_web_ui.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
My project is accessing a few more python files from another project. I added a reference to those in my .conf file above and in settings.py file as given below.
PROJECT_DIR = os.path.dirname(__file__)
print PROJECT_DIR
sys.path.insert(3,os.path.join(PROJECT_DIR,'ZMQHelper'))
sys.path.insert(1,os.path.join(PROJECT_DIR,'helper'))
sys.path.insert(2, '/home/kruthika/workspace/rtunetwork/volttron')
print sys.path
This is my project folder definition:
When I try to access a link, whose views.py file refers to the above mentioned dependencies, it throws a import module error as given below.
My question here is how to refer to my dependent modules/python classes so that the files are imported properly.
All these imports were working fine when I executed the project on Django's development server. Is there some Apache configuration I am missing or doing wrong? I am new to server configurations and I think I am missing something here.
Ι have developed a Django project and uploaded it to a cloud VΜ. Currently i have access to it through 8080 port.
python manage.py runserver 0.0.0.0:8080
If i enter the url without the 8080 port, it shows the "it works" page. How can i set my Django project to run by default on 80 port?
I am using Ubuntu 12.04 server
As docs say, runserver isn't meant as a deployment server. It also mentions that you probably can't start it on port 80 unless you run it as root.
Here is the kind of file you will need to put in /etc/apache2/sites-enabled, you need to adjust the paths in it. You also need to load mod_wsgi which you can do via apt-get.
<VirtualHost 192.168.1.14:80>
ServerAdmin youremail#whatever.com
ServerName www.whatever.com
ServerAlias whatever.com
Alias /robots.txt /home/dimitris/Python/mysite/site_media/robots.txt
Alias /favicon.ico /home/dimitris/Python/mysite/site_media/favicon.png
Alias /static/ /home/dimitris/Python/mysite/site_media/static
WSGIDaemonProcess mysite user=dimitris processes=1 threads=5
WSGIProcessGroup mysite
WSGIScriptAlias / /home/dimitris/Python/mysite/deploy/mysqite_wsgi.py
# Possible values include: debug, info, notice, warn, error, crit, alert, emerg.
LogLevel debug
ErrorLog ${APACHE_LOG_DIR}/mysite.error.log
CustomLog ${APACHE_LOG_DIR}/mysite.access.log combined
ServerSignature Off
</VirtualHost>
Most of this assumes you are running in a virtualenv, that means you will need a wsgi file to get things running. The above file sets up apache to run your "wsgi" file which looks something like this:
import os
from os.path import abspath, dirname, join
import sys
with open("/tmp/mysite.sys.path", "w") as f:
for i in sys.path:
f.write(i+"\n")
#redirect sys.stdout to sys.stderr for libraries that use
#print statements for optional import exceptions.
sys.stdout = sys.stderr
sys.path.insert(0, abspath(join(dirname(__file__), "../../")))
sys.path.insert(0, abspath(join(dirname(__file__), "../../lib/python2.7/site-packages/")))
from django.conf import settings
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
mod_wsgi, then opens this one file and executes it. application is the part that waits for requests from the webserver, and the rest behaves just like runserver except it can be multi-process and multi-threaded.
In the terminal while in a virtual environment, run:
sudo ./manage.py runserver 80
You will be asked for your password and it will run the server on port 80.
so here's the setting:
The whole site is working fine if I remove the application (whose name
is myapp) in the INSTALLED_APPS section in the settings file I added WSGIPythonHome in apache2.conf
I can successfully access the apps via the the interactive python shell in Django (python manage.py shell). I can create, update and delete data.
I am using the standard Apache 2 setup for Ubuntu 10.04 Lucid Lynx(sites-enabled, mods-enabled, apache2.conf, etc)
I am running a virtualenv located in /home/ygamretuta/dev/myproject
My django project is located in /home/ygamretuta/dev/site1
error Log file says this (last 2 lines):
File "/home/ygamretuta/dev/myproject/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
TemplateSyntaxError: Caught ImportError while rendering: No module named myapp
my django.wsgi contains this:
import os, sys
sys.path.append('/home/ygamretuta/dev')
os.environ['DJANGO_SETTINGS_MODULE'] = 'site1.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
my virtual host file for site1.com (contained in the sites-available folder) contains this (stripped of other details):
WSGIDaemonProcess ygamretuta processes=2 maximum-requests=500 threads=1
WSGIProcessGroup ygamretuta
WSGIScriptAlias / /home/ygamretuta/dev/site1/apache/django.wsgi
What could I have missed? I am getting e 500 Internal Server Error if the custom apps (the ones I made with manage.py startapp) are not commented out
Append /home/ygamretuta/dev/site1 to sys.path.