Django wsgi.py + Apache can't deploy, but - django

Environment and version: Windows 8-64bit, Wamp Apache 2.4.9, Python 3.4.2, Django 1.8
Deploying Django with apache using wsgi.py
followed following post got mod_wsgi setup
WSGIScriptAlias /mysite/mysite/wsgi "C:/wamp/www/mysite/mysite/wsgi.py"
WSGIPythonPath "C:/wamp/www/mysite/mysite/"
<Directory "C:/wamp/www/mysite/mysite/">
<Files wsgi.py>
Order deny,allow
Require all granted
</Files>
</Directory>
Directory:
wamp
|
www
|
testweb1
manage.py
|
testweb1 - settings.py
- urls.py
- wsgi.py
Inside wsgi.py(original code):
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testweb1.settings")
application = get_wsgi_application()
The problem is when starting Wamp Apache server, the icon appear green.
Server Online
But when I enter my ip address and port, for example 125.138.0.1:8080
The page only gives me this:
Apache/2.4.9 (Win64) mod_wsgi/4.4.2 Python/3.4.2 PHP/5.5.12 Server at 125.138.0.1 Port 8080
I had done so many research and followed the doc from
https://code.google.com/p/modwsgi/wiki/IntegrationWithDjango
tried many ways in wsgi.py , still couldn't get let Apache the deploy Django site from home IP address
By the way, in Apache httpd.conf
# Virtual hosts
Include conf/extra/httpd-vhosts.conf
Also tried
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/modwsgi/
os.environ["DJANGO_SETTINGS_MODULE"] = "{{ project_name }}.settings"

Your WSGIScriptAlias setting is wrong. The first argument should be the path you want your application served at, which is usually the root. So:
WSGIScriptAlias / "C:/wamp/www/mysite/mysite/wsgi.py"

Related

Django on apache: Could not find platform dependent libreries <exe_prefix>

I'm trying to deploy a django app in an Apache Server (Wamp) using a virtual environtment, but getting that error. Everything is going well, the problem seems to be happen in the wsgi.py file.
The wsgi.py never start the venv so this never start the app.
Here is my httpd-vhost.conf:
ServerName my.app.name
ServerAdmin myadminname#localhost.com
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
WSGIPassAuthorization On
Alias /static C:/wamp/apache2/htdocs/<myappname>/frontend/build/static/
<Directory "C:/wamp/apache2/htdocs/<myappname>/frontend/build/static/">
Allow from all
Require all granted
</Directory>
<Directory "C:/wamp/apache2/htdocs/<myappname>/<mysetting's django folder>">
<Files wsgi.py>
Allow from all
Require all granted
</Files>
</Directory>
#WSGIDaemonProcess <my.app.group> python-path="C:/wamp/apache2/htdocs/<app.name>/env/Lib/site-packages"
#WSGIProcessGroup <my.app.group>
WSGIScriptAlias / "C:/wamp/apache2/htdocs/<app.name>/<settings folder>/wsgi.py"
</VirtualHost>
Here is my wsgi.py file:
import os
import sys
# Add the virtual environment path to the system path
sys.path.append('C:/wamp/apache2/htdocs/<app.name>/env/Lib/site-packages')
# activate_this = 'C:/wamp/apache2/htdocs/<app.name>/env/Scripts/activate_this.py'
# execfile(activate_this, dict(__file__=activate_this))
# exec(open(activate_this).read(),dict(__file__=activate_this))
# Activate the virtual environment
activate_env = 'C:/wamp/apache2/htdocs/<app.name>/env/Scripts/python'
exec(open(activate_env, 'rb').read(), {'__file__': activate_env})
# Set the DJANGO_SETTINGS_MODULE environment variable
# os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings')
os.environ['DJANGO_SETTINGS_MODULE'] = 'app.settings'
# Import the Django application from the Django project
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
In the wsgi.py file there are two ways I found for activate the venv. The venv don't have the activate_this.py file but there was an answer I found answer-here that say you simply copying it from the virtualenv package solve the problem. I tried and worked (in Windows 10). But then I tried in a lower Windows version and got that error. Then I found the other solution without the activate_this.py file but still don't work.

Django: how to configure Apache to serve Django apps with mod_wsgi

I tried to set up a Django app with Apache and mod_wsgi, but ran into a problem that I have no ideas where is the cause. The app works fine with the command "python manage.py runserver", but when I tried to run it with Apache, I got the following errors in the Apache error log file.
Current thread 0x00007fb4880ad940 (most recent call first):
<no Python frame>
Python path configuration:
PYTHONHOME = '/data/anaconda3/envs/partsdb'
PYTHONPATH = (not set)
program name = 'python3'
isolated = 0
environment = 1
user site = 1
import site = 1
sys._base_executable = '/usr/bin/python3'
sys.base_prefix = '/data/anaconda3/envs/partsdb'
sys.base_exec_prefix = '/data/anaconda3/envs/partsdb'
sys.platlibdir = 'lib64'
sys.executable = '/usr/bin/python3'
sys.prefix = '/data/anaconda3/envs/partsdb'
sys.exec_prefix = '/data/anaconda3/envs/partsdb'
sys.path = [
'/data/anaconda3/envs/partsdb/lib64/python38.zip',
'/data/anaconda3/envs/partsdb/lib64/python3.8',
'/data/anaconda3/envs/partsdb/lib64/python3.8/lib-dynload',
]
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized
ModuleNotFoundError: No module named 'encodings'
I have the following lines in an Apache conf file.
WSGIPythonHome /data/anaconda3/envs/partsdb
WSGIPythonPath /data/partsdb/partsdb
WSGIScriptAlias / /data/partsdb/partsdb/wsgi.py
<Directory "/data/partsdb/partsdb">
<Files wsgi.py>
Require all granted
</Files>
</Directory>
I also replaced the following two lines in the Apache conf file
WSGIPythonHome /data/anaconda3/envs/partsdb
WSGIPythonPath /data/partsdb/partsdb
with the following two lines, but got the same errors.
WSGIDaemonProcess partsdb python-path=/data/partsdb/partsdb python-home=/data/anaconda3/envs/hla3db_venv
WSGIProcessGroup partsdb
The file /data/partsdb/partsdb/wsgi.py just contains the following lines of codes.
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'partsdb.settings')
application = get_wsgi_application()
Upon a brief debugging, I found out that the errors were from this line in wsgi.py.
from django.core.wsgi import get_wsgi_application
My machine's OS is redhat 8, and the Apache version is 2.4.37. Thanks for any info/hints.
Try the following code:
WSGIDaemonProcess partsdb python-path=/data/partsdb/partsdb python-home=/data/anaconda3/envs/hla3db_venv
WSGIProcessGroup partsdb
WSGIApplicationGroup %{GLOBAL}
WSGIPythonHome /data/anaconda3/envs/partsdb
WSGIPythonPath /data/partsdb/partsdb
WSGIScriptAlias / /data/partsdb/partsdb/wsgi.py
<Directory "/data/partsdb/partsdb">
<Files wsgi.py>
Require all granted
</Files>
</Directory>
Alias /static /path/to/directory/defined/as/STATIC_ROOT/
# The first part is defined by STATIC_URL in settings.py
<Directory /path/to/directory/defined/as/STATIC_ROOT>
Require all granted
</Directory>
<VirtualHost *:80>
ServerName mysite.app
ServerAdmin webmaster#localhost
# You do not need to specify DocumentRoot
# I have seen advice not to do so
ErrorLog ${APACHE_LOG_DIR}error.log
CustomLog ${APACE_LOG_DIR}access.log combined
</VirtualHost>
Please note I used this for a single app running in daemon mode as suggested in the documentation, on a Ubuntu server. Check the permissions on the folders, in my case I had to change permissions to allow apache to read and write to the folders the site was in.
You can also look at the answer Graham Dumpleton gave a few years back here:
Apache with virtualenv and mod_wsgi : ImportError : No module named 'django'

Ubuntu + Python3.6 + Apache2_web access error: No module named django.core.wsgi

Ubuntu16(x64) + Python3.6(installed by anaconda) + Django1.11.3(installed by conda) + Apache2.4.18.
With this configuration__ect/apache2/site-available/000-default.conf
<VirtualHost *:80>
ServerAdmin webmaster#localhost
DocumentRoot /var/www/mblog
WSGIDaemonProcess mblog python-path=/var/www/mblog
WSGIProcessGroup mblog
WSGIScriptAlias / /var/www/mblog/mblog/wsgi.py
<Directory /var/www/mblog/mblog>
<Files wsgi.py>
Order deny,allow
Require all granted
</Files>
</Directory>
</VirtualHost>
and the apache www directory for python project as below:
enter code here/var/www/mblog/(755)
|-- manage.py(755)
|
|-- mblog(dir 755)
| `|-- wsgi.py(644)
| `-- urls.py(644)
|-- templates(dir)
| `-- *.html(644)
The wsgi.py is configured as below (the files is granted):
import os, sys
sys.path.append('/var/www/mblog/mblog')
# poiting to the project settings
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mblog.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
After all of these config, the browser display:"500 Internal Server Error"
So I look for the error of /var/log/apache2/error.log as below:
File "/var/www/mblog/mblog/wsgi.py", line 31, in <module>
from django.core.wsgi import get_wsgi_application
ImportError: No module named django.core.wsgi
I am confused about all of the explain of website explanation but all of these cannot solve this question.
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/modwsgi/
Could you please give me a hand to solve this problem?
Thank you!
You either haven't told mod_wsgi where the Python virtual environment is that you are using and which Django is installed in, or your mod_wsgi is compiled for a different version of Python than you want to use and which Python is installed in.
Check what mod_wsgi is compiled for by doing what is described in:
http://modwsgi.readthedocs.io/en/develop/user-guides/checking-your-installation.html#python-installation-in-use
http://modwsgi.readthedocs.io/en/develop/user-guides/checking-your-installation.html#python-shared-library
For how to set up a Python virtual environment (which is recommended be used), see:
http://modwsgi.readthedocs.io/en/develop/user-guides/virtual-environments.html

How do I get Apache to reliably serve a large number of ports?

I have a dedicated server using Apache to listen to nine non standard ports (8xxx) which are supplying API services over SSL. Ports 80 and 443 are used to serve static content and an 'overwatch' service that indicates the status of the other services.
After a few days, the services start to fail because it appears that Apache is directing the service requests to the overwatch service rather than to the intended service. Restarting Apache fixes this issue until it happens again.
The services are implemented using wsgi.
There is a legacy pyramid API service configured as follows:
WSGIApplicationGroup %{GLOBAL}
WSGIPassAuthorization On
WSGIDaemonProcess pyramid user=ubuntu group=ubuntu threads=4 \
python-path=/home/ubuntu/ev_mis/lib/python2.7/site-packages
WSGIScriptAlias /mis /home/ubuntu/ev_mis/mis.wsgi
<Directory /home/ubuntu/ev_mis>
WSGIProcessGroup pyramid
Order allow,deny
Allow from all
</Directory>
The other eight API services use Django and are configured like this:
# Built automatically on Wed Sep 25 13:59:51 2013
Listen 8325
<VirtualHost _default_:8325>
DocumentRoot /usr/local/services/h/rb/mis/mis_site/mis_site
Alias /media /usr/local/services/h/rb/mis/mis_site/mis_site/media
Alias /static /usr/local/services/h/rb/mis/mis_site/mis_site/assets
<Directory /usr/local/services/h/rb/mis/mis_site/mis_site>
Order allow,deny
Allow from all
</Directory>
SetEnv DJANGO_SETTINGS_MODULE mis_site.settings.h
WSGIScriptAlias / /usr/local/orb_services/h/rb/mis/mis_site/mis_site/mis_site/wsgi.py
SSLEngine On
SSLCertificateFile /etc/apache2/ssl/domain.crt
SSLCertificateKeyFile /etc/apache2/ssl/domain.key
SSLCertificateChainFile /etc/apache2/ssl/chain.crt
SSLOptions +StrictRequire
</VirtualHost>
Finally there is the overwatch service configuration:
<VirtualHost *:80>
DocumentRoot /var/www
Alias /static /var/www/static
<Directory /var/www/>
Order allow,deny
Allow from all
</Directory>
Alias /thumbnails /var/www/thumbnails
<Directory /var/www/thumbnails>
Order allow,deny
Allow from all
</Directory>
WSGIScriptAlias / /var/www/overwatch/overwatch/wsgi.py
ErrorLog ${APACHE_LOG_DIR}/error.log
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
This is an example wsgi.py file:
import os
from os.path import abspath, dirname
from sys import path
from os import environ
SITE_ROOT = dirname(dirname(abspath(__file__)))
path.append(SITE_ROOT)
from django.core.wsgi import get_wsgi_application
def application(req_environ, start_response):
environ["DJANGO_SETTINGS_MODULE"] = req_environ.get("DJANGO_SETTINGS_MODULE",
environ.get("DJANGO_SETTINGS_MODULE",
None))
return get_wsgi_application()(req_environ, start_response)
For example: https://example.com/ yields the overwatch status table and https://example.com:8123/data/ yields service data on one of the services.
Analysis reveals that apache has mis-directed the call to the overwatch service. For example https://example.com:8123/data/ now yields page not found the debug trace reveals that it has been served by the overwatch wsgi service.
Once this happens, it happens consistently until I restart the apache service. Then everything is fine for a few days until it happens again. Apache does not report any configuration issues and starts/restarts fine.
Currently the server is only experiencing very light test traffic but it is scheduled to go live soon and I have no idea how to address this issue... short of perhaps biting the bullet and delaying launch while I reconfigure the whole thing to use nginx/gunicorn instead of apache which feels like a cop out.
A few comments.
You should not set DocumentRoot to a directory above where your project code is. If you were to inadvertently comment out the WSGIScriptAlias, all your project code, including the settings file with database passwords could be downloaded by someone.
You can't use 'SetEnv DJANGO_SETTINGS_MODULE mis_site.settings.h' in Apache to specify where the Django settings module is. It needs to be set in the wsgi.py file.
Why aren't you using daemon mode of mod_wsgi for your Django sites as well? You would be running multiple instances in sub interpreters of the one process and if you aren't configuring Django correctly, that could result in requests being handled by the wrong application. See http://blog.dscpl.com.au/2012/10/requests-running-in-wrong-django.html
UPDATE 1
Instead of using:
from django.core.wsgi import get_wsgi_application
def application(req_environ, start_response):
environ["DJANGO_SETTINGS_MODULE"] = req_environ.get(
"DJANGO_SETTINGS_MODULE". environ.get("DJANGO_SETTINGS_MODULE", None))
return get_wsgi_application()(req_environ, start_response)
You should be using:
from django.core.wsgi import get_wsgi_application
_application = get_wsgi_application()
def application(req_environ, start_response):
environ["DJANGO_SETTINGS_MODULE"] = req_environ.get(
"DJANGO_SETTINGS_MODULE", environ.get("DJANGO_SETTINGS_MODULE", None))
return _application(req_environ, start_response)
You are calling get_wsgi_application() on every request, which is a bad idea. It causes a new instance of the WSGI handler to be created on each request, which is not necessary. Doing so will also screw up the operation of monitoring tools such as New Relic.

apache 500 internal error when updating from django 1.3 to 1.4

Originally when I installed Django 1.3 with wsgi on my ubuntu server I used the included setup.py file and so when I wanted to update followed the Remove any old versions of Django section of the install guide by renaming the "django" folder in my site-packages "django.old" and then installing the new version by using the the setup.py file for Django 1.4
After restarting my apache server I got a standard 500 Internal error. I checked the apache error log and discovered that ADMIN_MEDIA_PREFIX has been deprecated so following the Django 1.4 release notes I removed ADMIN_MEDIA_PREFIX from the settings file and moved the admin files into the static directory under a folder called "admin" as indicated.
I restarted my apache server again and received the same standard 500 error but this time when I tried running a tail on the apache error log no new errors registered.
Without any further error messages I am really stuck so any help will be appreciated.
Below is the content of my apache site config file and the wsgi file
site config:
<VirtualHost *:80>
ServerAdmin me#mysite.com
ServerName www.mysite.com
ServerAlias mysite.com
# Indexes + Directory Root.
# DirectoryIndex index.html index.htm index.php
DocumentRoot /home/www/www.mysite.com/htdocs/
# CGI Directory
ScriptAlias /cgi-bin/ /home/www/www.mysite.com/cgi-bin/
<Location /cgi-bin>
Options +ExecCGI
</Location>
# Logfiles
ErrorLog /home/www/www.mysite.com/logs/error.log
CustomLog /home/www/www.mysite.com/logs/access.log combined
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /home/www/www.mysite.com/htdocs/>
Options FollowSymLinks MultiViews
AllowOverride All
allow from all
</Directory>
### Connect Django to the URL using WSGI (the django recommended method)
WSGIScriptAlias /myproject /django/myproject/django.wsgi
### Alias to the location of the static dir (images, css, js etc.)
Alias /myproject/static /django/myproject/static
<Directory /django/myproject/static>
Order deny,allow
allow from all
</Directory>
</VirtualHost>
django.wsgi:
import sys
import os
import django.core.handlers.wsgi
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
application = django.core.handlers.wsgi.WSGIHandler()
sys.path.insert(0, '/django/myproject/')
sys.path.insert(0, '/django/myproject/')
from django.core.handlers.wsgi import WSGIHandler
application = WSGIHandler()
Please note I have tried to remove or rename any identifying information from these files for security reasons, so if there is an obvious syntax error etc. it is probably due to this editing. The original versions of these files are the same accept for the name changes and worked well under Django 1.3
django 1.4 have a wsgi.py file configuratiom included:
See the documentation:
https://docs.djangoproject.com/en/1.4/howto/deployment/wsgi/#the-application-object