Django project not working with Apache and mod-wsgi - django

I created a droplet(cloud server) on DigitalOcean and with no-ip.com I gave it the hostname - project.ddns.net.By ssh(ing) into the droplet I installed pip and virtualenv.
Inside /var/www/ I created a virtualenv and cloned the repository from github of my project.The directory struture is -
project_revamped (root of the project)
->requirements
->base.txt
->dev.txt
->project (django project)
->static
->media
->apps (folder which contains apps)
->manage.py
->project
->urls.py
->settings
->base.py
->dev.py
I installed apache2 and mod_wsgi using -
sudo apt-get install apache2
sudo apt-get install libapache2-mod-wsgi
I then installed mysql,created a database and installed all requirements
pip install -r base.txt
I created a virtualhost project.conf on the path -
/etc/apache2/sites-available/project.conf
the content of file is this -
<VirtualHost *:80>
ServerAdmin example#gmail.com
ServerName project.ddns.net
ServerName www.project.ddns.net
WSGIScriptAlias / /var/www/project_revamped/project/project/wsgi.py
<Directory /var/www/project_revamped/project/project>
Order deny,allow
Allow from all
</Directory>
</VirtualHost>
Then I gave this command to activate this conf file -
a2ensite project.conf
The content of my wsgi.py in my django project is -
import os
import sys
import site
#Add the site-packages of the chosen virtualenv to work with
site.addsitedir('/var/www/.virtualenvs/projectenv/local/lib/python2.7/site-packages')
#Add the app's directory to the python path
sys.path.append('/var/www/project_revamped/project')
sys.path.append('/var/www/project_revamped/project/project')
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings.dev'
#Activate your virtualenv
activate_env = os.path.expanduser('/var/www/.virtualenvs/projectenv/bin/activate_this.py' )
execfile(activate_env, dict(__file__=activate_env))
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
After changing the files I finally gave the commands -
service apache2 reload
service apache2 restart
However after doing these things right the corresponding ip says there is some problem the server and sends 500 error.I guess the problem is somewhere in my configuration because apache server was responding working fine.After I include django project with it the problem starts.
Can anybody please help me here in the configuration? I am stuck in this for past 2 days and every different article on the internet tells the different story.

Have a look at the official documentation. I think you're missing the WSGIPythonPath-directive.
As #BurhanKhalid stated, this linked tutorial is complete and tested and should nearly exactly match your setup.

Related

Django rest API deploy on apache

I have created a django application and deployed it on the server.I have run the application through :-
python manage.py runserver 8000 &
and handle the requests on the apache server through proxy
ProxyPass "/" "http://www.example.com/"
ProxyPassReverse "/" "http://www.example.com/".
But there is a issue that I am facing while testing the api through JMeter, when i am running a test case for 10 users my python service over the server gets killed automatically.
What i am doing wrong or what i have to do more to resolve the above test scenario,please suggest?
First of all you need to deploy it on other server like apache. Below I am sharing how as usual configuration of apache2 to deploy a python django project.
Considering virtual environment is created else see how to create
virtual environment
Apache installation:
You need to install apache if not installed yet. Here I am showing the apache2 installation and some other installation which we need.
sudo apt-get update
sudo apt-get install apache2
sudo a2enmod wsgi
sudo apt-get install python3-pip apache2 libapache2-mod-wsgi-py3
configuration of 000-default.conf file : Generally the apache2 is located on linux m at path /etc/apache2/sites-available/000-default.conf. And the configuration file may like that.
<VirtualHost *:80>
ServerName www.something.com
# this is the document root of your project
DocumentRoot /path/to/my-project
# The directory which you can access with base path EX: www.something.com/static/images/image.png
Alias /static /path/to/my-project/static
<Directory /path/to/my-project/static>
Require all granted
</Directory>
<Directory /path/to/my-project/my-project>
<Files wsgi.py>
Header set Access-Control-Allow-Origin "*"
Require all granted
</Files>
</Directory>
WSGIDaemonProcess my-project python-home=/path/to/my_env python-path=/path/to/my-project
WSGIProcessGroup my-project
WSGIScriptAlias / /path/to/my-project/my-project/wsgi.py
ErrorLog /path/to/my-project/logs/error.log
CustomLog /path/to/my-project/logs/access.log combined3
</VirtualHost>
Django project wsgi.py : The django project you created there have a wsgy.py and this file may look like.
python_home = '/path/to/my_env'
import sys
import site
sys.path.append('/path/to/my-project')
sys.path.append('/path/to/my_env/bin')
sys.path.append('/path/to/my_env/lib/python3.6/site-packages')
# Calculate path to site-packages directory.
python_version = '.'.join(map(str, sys.version_info[:2]))
site_packages = python_home + '/lib/python%s/site-packages' % python_version
# Add the site-packages directory.
site.addsitedir(site_packages)
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my-project.settings")
application = get_wsgi_application()
After that you can start you apache2 sever sudo service apache2 start
Also you need to give the permission of you project directory sudo chmod -R 777 /path/to/my-project
This is the basic configuration of apache2 with python django project. Hope this will help to configure any linux machine with your python django project
You cannot using python manage.py runserver 8000 on a server, it's for development ONLY.
You can see the documentation here https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/
A basic conf for Apache would be :
<VirtualHost *:80>
ServerName yoursite.com
ServerAdmin your#site.com
Alias /media/ /path/to/django-app/media/
<Directory /path/to/django-app/media/>
Require all granted
</Directory>
WSGIScriptAlias / /path/to/django-app/conf/wsgi.py
<Directory /path/to/django-app/conf/>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
</VirtualHost>
You need to adapt this for your project.
If you need to install mod_wsgi : https://modwsgi.readthedocs.io/en/develop/user-guides/quick-installation-guide.html
For me i would use https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/uwsgi/ it's more convenient (pip install uwsgi)

Deploying multiple django sites with mod_wsgi apache linux

I wish to deploy multiple Django sites (say 2 for now - www.example.com, www.example2.com) using apache2 mod_wsgi. Here are the steps I followed in a fresh Ubuntu 16.04 installations.
I've set alias python=python3 in my .bashrc as I am working in python3
packages installed:
apache2 - sudo apt-get install apache2
mod_wsgi - sudo apt-get install libapache2-mod-wsgi-py3
Django(V1.11) - sudo apt-get install python3-django
Then I've created two projects inside
/var/www/
django-admin startproject example
django-admin startproject example2
then I did the followings for both the projects (I've mentioned only one, the other one is exactly the same except replacing example with example2)
/var/www/example/example/settings.py
ALLOWED_HOSTS = ['example.com', 'www.example.com']
/var/www/example/example/wsgi.py
#os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example.settings")
os.environ["DJANGO_SETTINGS_MODULE"] = "example.settings"
/etc/apache2/sites-available/example.conf
<VirtualHost *:80>
ServerName www.example.com
ServerAlias example.com
ServerAdmin admin#example.com
DocumentRoot /var/www/example
WSGIScriptAlias / /var/www/example/example/wsgi.py
ErrorLog /var/www/example/error.log
</VirtualHost>
Also, I've added
/etc/apache2/apache2.conf
WSGIPythonPath /var/www/example
I've called a2ensite for both example.conf and example2.conf
Once I restart apache I could now access www.example.com successfully, but www.example2.com gives an internal server error(500). I thought that's because I've only included one path for WSGIPythonPath in apache2.conf and changed it as
/etc/apache2/apache2.conf
WSGIPythonPath /var/www/example:/var/www/example2
But however, I now get an internal server error(500) for both.
in both cases, the error message is ImportError: No module named example
This is my first deployment by the way. Hense I have no prior experience.
Please direct me what I should do to get both sites up and running.

Django, mod_wsgi, psycopg2 ImproperlyConfigured: Error loading psycopg2 module: No module named _psycopg

I have a Django 1.5, Python 2.7 site running under Apache with mod_wsgi on a CentOS 6.4 server.
I have rebuilt this site using Django 1.6 and Python 3.3. Deploying it to the same server and changing the paths in httpd.conf I get the subject error. This new install works as expected using ./manage.py runserver.
Here are the two WSGI definitions from httpd.conf:
WSGIScriptAlias / /home/ccdgen/CCDGEN2/apache/wsgi.py
WSGIPythonPath /home/ccdgen/CCDGEN2/ccdgen/ccdgen:/home/ccdgen/CCDGEN2/ccdgen:/home/ccdgen/CCDGEN2/lib/python3.3/site-packages
<Directory /home/ccdgen/CCDGEN2/ccdgen>
<Files wsgi.py>
Order allow,deny
Allow from all
</Files>
</Directory>
#WSGIScriptAlias /ccdgen /home/ccdgen/CCDGEN/apache/wsgi.py
#WSGIPythonPath /home/ccdgen/CCDGEN/mlhim/ccdgen:/home/ccdgen/CCDGEN/mlhim:/home/ccdgen/CCDGEN/lib/python2.7/site-packages
#<Directory /home/ccdgen/CCDGEN/mlhim>
# <Files wsgi.py>
# Order allow,deny
# Allow from all
# </Files>
#</Directory>
The wsgi.py file is the same on both installations:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mlhim.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
Any ideas? Obvious oversights? Thanks
I had this problem recently:
ImproperlyConfigured: Error loading psycopg2 module: No module named _psycopg
... and this command was the answer:
sudo apt-get install libapache2-mod-wsgi-py3
Reference:
http://python.6.x6.nabble.com/ImproperlyConfigured-Error-loading-psycopg2-module-No-module-named-psycopg-td5044145.html
The problem was that mod_wsgi was compiled for Python 2.7 and it needed to be recompiled for Python 3.3. I did not find a new mod_wsgi available anywhere as a package so I recompiled it.
Since Python 3 is an alternate install on CentOS 6.4 .configure had a difficult time producing a good Makefile, even passing the --with-python option. I needed to edit Makefile a bit after getting the information from python3.3-config --cflags and also with --ldflags options.
HTH someone in the future.
Try these commands Debian, Ubuntu
sudo apt-get install python-dev
sudo apt-get install libpq-dev
For RedHat Enterprise, Fedora, CentOS
sudo yum install python-devel
sudo yum install postgresql-libs
Then Install psycopg2
pip install psycopg2
As has been mentioned, mod_wsgi has not been compiled for python 3. One option is to use Software Collections and/or go with nginx, and "pip install uwsgi" which saves a lot of compiling and running custom packages.

ImportError: No module named django.core.wsgi Apache + VirtualEnv + AWS + WSGI

I am trying to publish my site on an Amazon's EC2 Instance, and I keep getting a 500 error. I really don't know why.
//Log Files
[Sun Feb 17 23:12:48.066802 2013] mod_wsgi (pid=2102): Target WSGI script '/srv/www/app/poka/apache/wsgi.py' cannot be loaded as Python module.
[Sun Feb 17 23:12:48.066840 2013] mod_wsgi (pid=2102): Exception occurred processing WSGI script '/srv/www/app/poka/apache/wsgi.py'.
[Sun Feb 17 23:12:48.066864 2013] Traceback (most recent call last):
[Sun Feb 17 23:12:48.066889 2013] File "/srv/www/mysite/poka/apache/wsgi.py", line 26, in <module>
[Sun Feb 17 23:12:48.066920 2013] from django.core.wsgi import get_wsgi_application
[Sun Feb 17 23:12:48.066945 2013] ImportError: No module named django.core.wsgi
//Apache Config Files
WSGIScriptAlias / /srv/www/app/mysite/apache/wsgi.py
WSGIDaemonProcess mysite python-path=/srv/www/app/mysite:/home/ec2-user/.virtualenvs/mysite-main/lib/python2.7/site-packages
WSGIProcessGroup mysite
<Directory /srv/www/app/mysite/apache/>
<Files wsgi.py>
Order deny,allow
Allow from all
</Files>
</Directory>
<Directory /srv/www/app/mysite/apache/>
Order deny,allow
Allow from all
</Directory>
<Directory /home/ec2-user/app/mysite/static>
Order deny,allow
Allow from all
</Directory>
<Directory /home/ec2-user/app/mysite/media>
Order deny,allow
Allow from all
</Directory>
//wsgi.py
import os
import sys
import site
site.addsitedir('/home/ec2-user/.virtualenvs/mysite-main/lib/python2.7/site-packages')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
path = '/srv/www/app/mysite'
if path not in sys.path:
sys.path.append(path)
I know that this is an old thread but I've just bumped into the same issue and I don't think that this is caused by a missing package. As the Django core distribution contains the correct wsgi handler already.
The problem here is that when wsgi.py is executed it's missing the packages of the site-packages from your virtualenv. (If you have activated your virtualenv, and done pip install django then everything is fine. You have the necessary django packages).
As far as I'm concerned, I fixed the issue modifying the sys.path in my Path/to/Project/Project/wsgi.py file.
You have to append your project dir and your virtualenv site-packages to the sys.path List.
Here is my wsgi.py file contained in my project (Talking about the wsgi.py created with django-admin.py start-project)... that I had to modify in order to make it work with Apache
# =====================
# wsgi.py file begin
import os, sys
# add the hellodjango project path into the sys.path
sys.path.append('<PATH_TO_MY_DJANGO_PROJECT>/hellodjango')
# add the virtualenv site-packages path to the sys.path
sys.path.append('<PATH_TO_VIRTUALENV>/Lib/site-packages')
# poiting to the project settings
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hellodjango.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# wsgi.py file end
# ===================
Make sure:
you added mod_wsgi to the Apache modules dir
mod_wsgi must be compiled for the OS, Apache and Python version you have
added the load module command into your httpd.conf to load mod_wsgi module
LoadModule wsgi_module modules/mod_wsgi.so
configured Django specifics in your httpd.conf or any conf you include in your httpd.conf
Based on the documentation How to use Django with Apache and mod_wsgi
WSGIScriptAlias / <PATH_TO_PROJECT>/hellodjango/hellodjango/wsgi.py
WSGIPythonPath <PATH_TO_PROJECT>:<PATH_TO_VIRTUALENV>/Lib/site-packages
<Directory <PATH_TO_PROJECT>/hellodjango/hellodjango>
<Files wsgi.py>
Order deny,allow
Require all granted
</Files>
</Directory>
Hope this helps. It worked for me.
I had the same issue. My libapache2-mod-wsgi was python 2.x and not python 3.x
found the solution here: https://stackoverflow.com/a/28118284/2489042
credits to #nima
$ sudo apt-get remove libapache2-mod-python libapache2-mod-wsgi
$ sudo apt-get install libapache2-mod-wsgi-py3
Warning from #alxs before you copy/paste these commands:
If there are python 2 projects running on the server that use wsgi and apache, the above commands will effectively shut them down.
Add this to the Apache configuration file:
WSGIPythonHome /home/ec2-user/.virtualenvs/mysite-main
I had a similar error just now. It turns out that our Django code was developed on python 3.5, but for some reasons the people who deployed our server setup virtualEnv with python 2.7. We redeployed with python 3.5 and everything worked for us
Below was the error message I received:
$ python serviceStartup.py
Traceback (most recent call last):
File "serviceStartup.py", line 10, in <module>
from django.core.wsgi import get_wsgi_application
ImportError: No module named django.core.wsgi
Hope this will help with anyone seeing a similar error message!
For me, this indicated Django wasn't installed on the sever. Fixed via
pip install Django
In general, make sure you installed requirements:
pip install -r requirements.txt
If using a virtual environment, activate it before installing requirements.
You've configured everything very well my friend, just need to give the apache user permission to access both project and virtualenv dirs.
Example:
sudo chown -R www-data:www-data /home/ubuntu/projects
sudo chown -R www-data:www-data /home/ubuntu/virtualenv
This solved my problem with ImportError: No module named django.core.wsgi (virtualenvs folders) and ImportError: No module named <project-name>.settings (projects folders)
At first glance, I am sorry for my English. I also faced this issue, and I have solved it by changing 'wsgi.py' file to:
import os
import django
from django.core.handlers.wsgi import WSGIHandler
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "eisentask.settings.production")
django.setup(set_prefix=False)
application = WSGIHandler()
I am using Centos and the nginx and gunicorn for my project...
I had this problem...
wsgi file is not reachable maybe it's bcz of the your current directory
I changed my current directory and It worked...
my project name is coda so I typed
cd coda
and then
gunicorn --bind 0.0.0.0:8001 coda.wsgi
In case someone came here using AWS Lightsail bitnami..
The problem is that 'python install packages in a directory that apache do not see'.
so: packages get installed in '/home/bitnami/.local/lib/python3.8/site-packages/' and Apache looks in '/opt/bitnami/python/lib/python3.8/site-packages/'.
The temporary solution I followed is copying packages to Apache eyes folder with this command 'cp -r /home/bitnami/.local/lib/python3.8/site-packages/* /opt/bitnami/python/lib/python3.8/site-packages/'
Hi I got the same issue in Ubuntu 20.04 server. I fixed it by installing apache2-dev
sudo apt-get install apache2-dev
In mod_wsgi documentation its important to have both apache2 and apache2-dev installed.
Run these commands:
$ sudo apt-get remove libapache2-mod-python libapache2-mod-wsgi
$ sudo apt-get install libapache2-mod-wsgi-py3
For me it was some variables that needed to be setted (for windows) :
set PYTHONHOME=F:\path\to\python
set PYTHONPATH=F:\path\to\python

Django + uWSGI via NGINX on Ubuntu 11.10

I'm trying do deploy a django project. I tried a lot of tutorials, but had no luck. I use a new clean Ubuntu 11.10. I've performed
apt-get install nginx
apt-get install uwsgi
service nginx start
I've created folder /deploy/project1 and put there manage.py and other files.
My current /deploy/project1/project1/wsgi.py contains:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project1.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
So, could you tell me how to deploy my django app for domain.com properly?
I've also installed Django via pip and easy_install
What should I add in /etc/nginx/sites-enabled/default.
Assuming that you have installed all requirement and you are using the aptitude packages then you don't need the wsgi.py. All the configuration is in the uwsgi ini/xml/yaml file. (take the format that you prefer).
Here is a minimal example for example.com file for nginx(/etc/nginx/sites-available/examplecom for ubuntu 11.10)
server {
listen 80;
server_name example.com;
access_log /var/log/nginx/projectname.log;
location /media {
alias /vagrant/test/projectname/media/;
}
location /static {
alias /vagrant/test/projectname/static/;
}
location / {
uwsgi_pass unix:///run/uwsgi/projectname/socket;
include uwsgi_params;
}
}
Create a symbolic link to /etc/nginx/sites-enabled
sudo ln -s /etc/nginx/sites-available/examplecom /etc/nginx/sites-enabled/examplecom
or
sudo /usr/sbin/nxensite examplecom
You are done with NGINX.
Go to /etc/uwsgi/apps-available and create your ini file
sudo vim /etc/uwsgi/apps-available/projectname.ini
[uwsgi]
virtualenv=/home/vagrant/.virtualenvs/projectenv
thread=3
master=1
env = DJANGO_SETTINGS_MODULE=projectname.settings
module = django.core.handlers.wsgi:WSGIHandler()
chdir = /path/to/my/django/project
socket = /run/uwsgi/projectname/socket
logto = /var/log/uwsgi/projectname.log
Point your ini to /etc/uwsgi/apps-enabled/projectname.ini
sudo ln -s /etc/uwsgi/apps-available/projectname.ini /etc/uwsgi/apps-enabled/projectname.ini
For more information, see any of these files on your system:
/etc/uwsgi/apps-available/README
/etc/uwsgi/apps-enabled/README
/usr/share/doc/uwsgi/README.Debian.gz
/etc/default/uwsgi
You are done. You can now restart nginx & uwsgi
sudo service nginx restart
sudo service uwsgi restart
Cheers!
Do not forget that Debian's, Ubuntu's and its derivates' uwsgi package does not require installation of its Python plugin — uwsgi-plugin-python, because uWSGI does not necessarily uses only Python (there are plugins for Lua, Erlang and other languages). However, Django requires Python plugin. Install it:
sudo apt install uwsgi-plugin-python
Unlike PIP's installation, you should explicitly mention uwsgi's plugin used in the app's config by adding a plugins = python line to it (if you use Python), like this:
[uwsgi]
plugins = python
uwsgi-socket = /var/sockets/django.sock
chmod-socket = 660
chdir = /home/v/django
module = project.wsgi
Unless you do this, there will be no Python-specific options available. And Debian's/Ubuntu's uWSGI will be just quiet about it!