Apache and wsgi config for Django - django

I'm struggling to get my Django stuff to appear on my web browser. If I use python3 manage.py runserver 192.168.0.10:8000, I can see the Django install and admin page, but I'd like to see it without specifying a port number, and I'm aware that using run server is the development side, rather than deployment. Also worth noting that I have not used any form of VirtualEnv as this is a dedicate Pi/Project, and I was getting confused with the libraries, local python install, virtual python install etc.
I have Django / MySQL / Apache2 up-to-date (as far as I can tell) and there is Django data in the correct db/table.
When navigating to 192.168.0.10/ or 192.168.0.10/admin, I get no error page or default apache page. It sits there for about 5 minutes, then gives me 'can't find page'.
Trying to narrow things down, I think I've got one of three problems:
Apache isn't configured correctly
Permissions/ownership issue of MySQL (e.g. apache not reading from table)
Permissions/ownership issue of dir's (e.g. /var/www)
I posted a similar question not too long ago, I've revisited that and the links that came with it, but it's not helped. I did have PHP and a VirtualEnv installed that time, and this is a fresh installation without either. I'm looking to have php install to have a bit of a gui to manage the MySQL should I need to, so I might do then after posting this and see if it helps.
Django's settings.py: I'll provide the important bits:
DEBUG = True
ALLOWED_HOSTS = ['192.168.0.10', '127.0.0.1']
.....
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'init_command': 'SET sql_mode=`STRICT_TRANS_TABLES`',
'read_default_file': '/etc/mysql/my.cnf',
},
}
}
......
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MySQL/my.cnf =
# The MariaDB configuration file
#
# The MariaDB/MySQL tools read configuration files in the following order:
# 1. "/etc/mysql/mariadb.cnf" (this file) to set global defaults,
# 2. "/etc/mysql/conf.d/*.cnf" to set global options.
# 3. "/etc/mysql/mariadb.conf.d/*.cnf" to set MariaDB-only options.
# 4. "~/.my.cnf" to set user-specific options.
#
# If the same option is defined multiple times, the last one will apply.
#
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# This group is read both both by the client and the server
# use it for options that affect everything
#
[client-server]
# Import all .cnf files from configuration directory
#!includedir /etc/mysql/conf.d/
#!includedir /etc/mysql/mariadb.conf.d/
[client]
database = blog_data
host = localhost
user = root
password = xxx
default-character-set = utf8
#SET sql_mode='STRICT_TRANS_TABLES'
/etc/apache2/sites-available/000-default.conf =
...
Alias /static /home/pi/test_blog_app/blog/static
<Directory /home/pi/test_blog_app/blog/static>
Require all granted
</Directory>
<Directory /home/pi/test_blog_app/blog/blog>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIDaemonProcess testblogapp python-path=/home/pi/test_blog_app python-home=/usr/lib/python3/dist-packages
WSGIProcessGroup testblogapp
WSGIScriptAlias / /home/pi/test_blog_app/blog/blog/wsgi.py
Output of sudo nano var/log/apache2/error.log (last few lines) =
Current thread 0xb6fa8e40 (most recent call first):
[Sun Oct 01 16:11:20.397787 2017] [core:notice] [pid 2390:tid 3069873728] AH00052: child pid 2476 exit signal Aborted (6)
[Sun Oct 01 16:11:20.398262 2017] [core:notice] [pid 2390:tid 3069873728] AH00052: child pid 2477 exit signal Aborted (6)
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'
Current thread 0xb6fa8e40 (most recent call first):
VERSIONS
O/S - Raspbian 9.1
Apache - 2.4.25
Django - 1.11.5
Python - 3.5.3
MySQL - (Maria) 10.1.23-MariaDB-9+deb9u1 Raspbian 9.0
PHP - 7.0.19-1
EDIT I've attempted to re-install mod_wsgi using
sudo apt-get purge --auto-remove libapache2-mod-wsgi-py3 &
sudo apt-get install libapache2-mod-wsgi-py3
However, no result

Related

Apache and mod_wsgi WSGIDaemonProcess config error

I'm having a lot of difficulty with apache(Apache/2.4.7 (Ubuntu 14.04)) and mod_wsgi and my django site. My configuration has been working for a long time, then I'm not sure what I did (possibly because I moved the virtualenv, and didn't reflect this accurately in the config, or possibly just a server upgrade, I'm not sure), but now I get errors like
#/var/log/apache2/error.log
[Mon Dec 22 08:47:04.693620 2014] [:info] [pid 21082:tid 139779033159552] mod_wsgi (pid=21082): Starting process 'mysite.com' with uid=999, gid=999 and threads=4.
[Mon Dec 22 08:47:04.693744 2014] [:alert] [pid 21084:tid 139779033159552] (2)No such file or directory: mod_wsgi (pid=21084): Unable to change working directory to '/home/djangoUser'.
[Mon Dec 22 08:47:04.693769 2014] [:alert] [pid 21084:tid 139779033159552] mod_wsgi (pid=21084): Failure to configure the daemon process correctly and process left in unspecified state. Restarting daemon process after delay.
and
#/srv/apache/log/mysite_error.log
[Mon Dec 22 08:49:31.295810 2014] [core:error] [pid 13999:tid 139778670376704] [client 1.169.91.80:2836] Script timed out before returning headers: mysite.com_wsgi.py
I tried reinstalling and re-enabling mod_wsgi:
sudo aptitude install libapache2-mod-wsgi
a2enmod wsgi
service apache2 restart
and this did not help.
My wsgi file for django looks like:
#/srv/apache/mysite.com_wsgi.py (perms are www-data.www-data 644 on file, 755 dir above)
#!/usr/bin/env python
settings_module = "settings"
os.environ["DJANGO_SETTINGS_MODULE"] = settings_module
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
and my apache conf looks like:
#/etc/apache2/sites-enabled/mysite.com.conf:
<VirtualHost *:80>
# Admin email, Server Name (domain name), and any aliases
ServerAdmin me#gmail.com
ServerName www.mysite.com
ServerAlias mysite.com
WSGIScriptAlias / /srv/apache/mysite.com_wsgi.py
# Log file locations
LogLevel info
ErrorLog /srv/apache/log/mysite.com_error.log
CustomLog /srv/apache/log/mysite.com_access.log combined
WSGIDaemonProcess mysite.com processes=4 threads=4 display-name=%{GROUP} user=djangoUser group=djangoUser python-path=/srv/mysite:/srv/mysite/venv/lib/python2.7/site-packages
WSGIProcessGroup: mysite.com
<Directory "/srv/apache">
Require all granted
</Directory>
<Directory "/srv/www/mysite.com/media">
Require all granted
</Directory>
<Directory "/srv/www/mysite.com/static">
Require all granted
</Directory>
</VirtualHost>
Some dir structure notes:
The django site files are at /srv/mysite which is djangoUser.djangoUser 755 (and all files/dirs below are owned by djangoUser too). The virtual env is at /srv/mysite/venv and again all owned by djangoUser with same perms pip install gave them. Other files inside /srv/mysite/ are also owned by djangoUser with dir 500, files 400.
The wsgi file is at /srv/apache and it and the apache dir are www-data.www-data with the wsgi file 644 and dir above 755.
The static files are at /srv/www/mysite.com/static with everything owned by www-data, and dir .....I can actually access say the favico or robots file without problem...www.mysite.com/favicon.ico shows it without error.
Has anyone got any ideas what the problem could be? I thought at first it must be permissions, but I cannot see any issues.
Finally /etc/passwd shows the djangoUser as
djangoUser:x:999:999::/home/djangoUser:/bin/false

Mod_wsgi fails to load django.core.handlers.wsgi

Ok, after 5-6 hours of trying, I give up. I have searched the web, tried all solutions suggested, but nothing is solving my problem.
Goal: Set up Django on my Ubuntu 12.04 VPS.
Problem: Exception occurred processing WSGI script [...] ImportError: No module named django.core.handlers.wsgi in /etc/log/apache2/error.log.
Solutions tried: 1) Appending the site-packages directory to the sys path in Djangos' wsgi.py file, 2) re-installing mod_wsgi, 3) making sure mod_wsgi is compiled for the same Python version as Django is installed with, 4) chmod 777 for the site-packages directory.
Environment: Ubuntu 12.04 VPS, Django installation in virtualenv, Python version 2.7.3, Django version 1.6.1, mod_wsgi built from mod_wsgi-3.4.tar.gz.
Full error message:
mod_wsgi (pid=23691): Exception occurred processing WSGI script '/var/www/mySite/djangoSite/djangoSite/wsgi.py'.
Traceback (most recent call last):
File "/var/www/mySite/djangoSite/djangoSite/wsgi.py", line 7, in <module>
import django.core.handlers.wsgi
ImportError: No module named django.core.handlers.wsgi
mod_wsgi (pid=23691): Target WSGI script '/var/www/mySite/djangoSite/djangoSite/wsgi.py' cannot be loaded as Python module.
mod_wsgi (pid=23691): Exception occurred processing WSGI script '/var/www/mySite/djangoSite/djangoSite/wsgi.py'.
Traceback (most recent call last):
File "/var/www/mySite/djangoSite/djangoSite/wsgi.py", line 7, in <module>
import django.core.handlers.wsgi
ImportError: No module named django.core.handlers.wsgi
Conf file from sites-available:
<VirtualHost *:80>
ServerAdmin admin#mysite.com
ServerName mysite.com
DocumentRoot /var/www/mysite.com/djangoSite
WSGIDaemonProcess djangoSite python-path=/var/www/mysite.com/djangoSite:~/Envs/myEnv/lib/python2.7/site-packages
WSGIProcessGroup djangoSite
WSGIScriptAlias / /var/www/mysite.com/djangoSite/djangoSite/wsgi.py
Alias /static/ /var/www/mysite.com/djangoSite/static/
<Directory /var/www/mysite.com/djangoSite/static>
Order deny,allow
Allow from all
</Directory>
<Directory /var/www/mysite.com/djangoSite/djangoSite>
<Files wsgi.py>
Order deny,allow
Allow from all
</Files>
</Directory>
</VirtualHost>
wsgi.py:
import os
import sys
sys.path.append('/var/www/mysite.com/djangoSite/')
sys.path.append('/var/www/mysite.com/djangoSite/djangoSite/')
activate_this = '/root/Envs/myenv/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))
os.environ['DJANGO_SETTINGS_MODULE'] = 'djangoSite.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
Site structure
/var/www/
-- mysite.com
-- djangoSite
-- manage.py
-- djangoSite
-- settings.py, wsgi.py etc.
In your wsgi.py, try adding this to activate virtual env:
import os
import sys
sys.path.append('/Path_To/Virtual_Env/Project_Dir/')
#This is important if multiple apps are running (instead of setdefault)
os.environ["DJANGO_SETTINGS_MODULE"] = "app_name.settings"
activate_this = '/Path_To/Virtual_Env/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))
In you apache config, you mainly need only(No Deamon Process required):
WSGIScriptAlias / /var/www/mysite.com/djangoSite/djangoSite/wsgi.py
Alias /static/ /var/www/mysite.com/djangoSite/static/
See from the Create Virtual Host section of this link
Make sure you are using absolute paths in your Apache2 config file. I assume you have been able to run python manage.py shell to get a working Django shell? I would tackle the Apache2 config file; I'm sure your issue is there.
~/Envs/myEnv/lib/python2.7/site-packages
I think that's your problem right there: the ~ is, if it is expanded at all, expanded to the home of the www-data user. You can validate that by doing something like this:
import sys
print >> sys.stderr, sys.path
in your wsgi file; then check your error log. If it doesn't end up in the main error log, add an ErrorLog to your vhost to get per-vhost error logging.
Also, /root/ is not readable for the www-data user, you need to move your virtual env somewhere accessible.

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.

Django on Mac OS X: OperationalError 'role "_www" does not exist'. PostgreSQL or Psycopg issue?

I'm new to web development with Django, so please bear with me and thank you in advance for your help.
I've been using Django's own web server and SQLite while learning. However, now I'm struggling trying to get a more complex setup working for my next project.
My setup (Apache, Python, mod_wsgi, PostgreSQL server, psycopg and Django) should be working fine to the best of my knowledge. I created my Django project and visited localhost on my browser, where I got the "Welcome to Django! It worked!" page. However, when I tried to enable the admin and visited localhost/admin/ I get the following error (note that I can visit this page without errors using Django's own web server):
OperationalError at /admin/
FATAL: Role "_www" does not exist
Request Method: GET
Request URL: http://localhost/admin/
Django Version: 1.4.3
Exception Type: OperationalError
Exception Value: FATAL: role "_www" does not exist
Exception Location: /Library/Python/2.7/site-packages/psycopg2/__init__.py in connect, line 178
I'm guessing something is not right with PostgreSQL or psycopg, but I'm unsure what exactly. This is how I got here:
Mac OS X Mountain Lion (10.8.2) fresh install.
Installed Xcode from Mac App Store, then command line tools from Xcode's preferences.
Didn't update Apache or Python, I'm using whatever was installed by default (Apache 2.2.22 and Python 2.7.2).
Installed mod_wsgi 3.4 from source
$ curl -O http://modwsgi.googlecode.com/files/mod_wsgi-3.4.tar.gz
$ tar xvfz mod_wsgi-3.4.tar.gz
$ cd mod_wsgi-3.4
$ ./configure
$ make
(Note: I had to enter the following line for "make" to work:)
$ sudo ln -s /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/ /Applications/Xcode.app/Contents/Developer/Toolchains/OSX10.8.xctoolchain
$ make install
Edited httpd.conf, added the following and restarted Apache:
LoadModule wsgi_module libexec/apache2/mod_wsgi.so
Installed PostgreSQL 9.2.2 by downloading the Postgres.app (http://postgresapp.com) and copying it to my Applications folder.
Ran the app, added the following to my ~/.bash_profile (for Terminal to use Postgres.app's psql by default, rather than the one that comes pre-installed on Mac OS X) and then created a new database to use with my django project:
PATH="/Applications/Postgres.app/Contents/MacOS/bin:$PATH"
Installed psycopg 2.4.6 from source. I downloaded the file, unpacked it and then from the unpacked directory:
$ python setup.py install
Installed Django 1.4.3 from source. Created a new project and a new app. Edited the settings.py to uncomment the admin app and enter my database settings (as described on Postgres.app's website: http://postgresapp.com/documentation#toc_3). The database settings look as follows:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'my_db_name',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
Edited urls.py to uncomment the admin related lines:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
)
Added the following text at the end of https.conf:
WSGIScriptAlias / /Users/antubel/Projects/Django/antubel_com/antubel_com/wsgi.py
WSGIPythonPath /Users/antubel/Projects/Django/antubel_com
<Directory /Users/antubel/Projects/Django/antubel_com>
<Files wsgi.py>
Order deny,allow
Allow from all
</Files>
</Directory>
Restarted Apache. Tried to load localhost/admin/ on my browser and got the error mentioned above.
Please help :)
Thanks,
Dasuevia
Because your settings file doesn't specify a user to connect to Postgres with, you're trying to connect using the user account that's running your code (and because it's being run by mod_wsgi under Apache, that user is _www).
If you're using Postgres.app to run Postgres for you, you will need to set your database USERNAME value to the username for your account on the system - so if your username was foo, set USERNAME to foo like so:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'my_db_name',
'USER': 'foo',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
You can also update your apache config to run your code as a different user - take a look at WSGIDaemonProcess in the mod_wsgi docs if you'd like to get that going instead.

Apache Django "client denied by server configuration" error

I found a similar question here, but didn't help me.
I basically have apache setup on my OS X. I also have Django installed.
However, when i try to load the page through the browser locally, i get:
Forbidden
You don't have permission to access / on this server.
I have an original httpd.conf with the only modification of enabling vhosts in which I have:
<VirtualHost *:80>
ServerAdmin webmaster#dummy-host.example.com
DocumentRoot "/Dropbox/project/www/"
ServerName touch.loc
# ServerAlias www.dummy-host.example.com
ErrorLog "/Dropbox/project/www/log/error.log"
CustomLog "/Dropbox/project/www/log/access.log" common
</VirtualHost>
And the error.log file gives:
[Tue May 03 20:22:56 2011] [error] [client 127.0.0.1] Directory index forbidden by Options directive: /Dropbox/project/www/
I read around and it looks like i have to add the following to the httpd.conf:
<Directory /Dropbox/project/www >
Order deny,allow
Allow from all
</Directory>
In which case i get:
[Tue May 03 20:27:55 2011] [error] [client 127.0.0.1] client denied by server configuration: /Dropbox/project/www/
Can someone help me fix this annoyance? How can I further Investigate it?
Does it have to do with users/groups?
UPDATE:
I then added the Options +Indexes and the permissions opened. However when i try to load the page, file structure appears instead of the wsgi file to pickup and load the website. What would be the reason for that?
here is my .wsgi file:
import os
import sys
sys.stdout = sys.stderr
# Add the virtual Python environment site-packages directory to the path
import site
site.addsitedir('/usr/lib/python2.6/dist-packages')
#If your project is not on your PYTHONPATH by default you can add the following
sys.path.append('/Dropbox/project/www/')
sys.path.append('/Dropbox/project/www/project')
# Avoid ``[Errno 13] Permission denied: '/var/www/.python-eggs'`` messages
os.environ['PYTHON_EGG_CACHE'] = '/Dropbox/project/www/mod_wsgi/egg-cache'
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
You seem to be missing anything in your Apache configuration that actually serves the Django application. You need to read the Django mod_wsgi documentation - the first line of code there is what you're missing.
Note that your code should not live under the DocumentRoot.
The problem I see is in Dropbox folder
I have made so:
chmod o+x /home/your_name/Dropbox
That resolves permissions