Django+Apache | ImportError: No Module named django - python

I am hosting my django app on Linode with Ubuntu OS and i have configured apache webserver.
When I try to access the site i get 500 Internal Server error
Apache logs show the following error
Traceback (most recent call last):
File "/home/mosajan/artistry/artistry/wsgi.py", line 12, in <module>
from django.core.wsgi import get_wsgi_application<br>
ImportError: No module named 'django'
Target WSGI script '/home/mosajan/artistry/artistry/wsgi.py' cannot be loaded as Python module.
Exception occurred processing WSGI script '/home/mosajan/artistry/artistry/wsgi.py'.
wsgi.py
import os
import sys
from django.core.wsgi import get_wsgi_application
sys.path.append('home/mosajan/artistry/')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'artistry.settings')
application = get_wsgi_application()
apache2 conf file
artistry.conf
Alias /static /home/mosajan/artistry/static
<Directory /home/mosajan/artistry/static>
Require all granted
</Directory>
<Directory /home/mosajan/artistry/artistry>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIScriptAlias / /home/mosajan/artistry/artistry/wsgi.py
WSGIDaemonProcess artistry python-path=/home/mosajan/artistry python-home=/home/mosajan/artistry/venv
WSGIProcessGroup artistry
WSGIPythonHome /home/mosajan/artistry/venv
WSGIPythonPath /hom/mosajan/artistry
File structure

This answer assumes that you manually activated the venv and that when you do something like python manage.py runserver 0.0.0.0:8000 in your project folder, are you able to see the project and run it without any errors. If that's the case, this means you have installed django as well as other needed project requirements / packages, so you can deactivate the venv for now.
Let's start by making sure that the server's IP address was added to ALLOWED_HOSTS in your settings.py file.
Now, with the venv deactivated, make sure to install Apache 2.4 with the service httpd with the module wsgi which is gonna help the Django app behave as a web app totally compatible with Apache 2.4. If you're using yum as a package manager, then you'd run something like this
yum install -y httpd python36u-mod_wsgi
Let's now add a group www
groupadd www
and edit the group
vim /etc/group
and add in the end of the file
www:x:10000:root,apache
Go to the root directory and run the following commands to make the www group owner of this directory
chown root.www -R /home/mosajan
chmod 775 -R /home/mosajan
Now in your Apache virtual host configuration file artistry.conf, the version you're presenting has an error in the last line (WSGIPythonPath /hom/mosajan/artistry). Fix it by using WSGIPythonPath /home/mosajan/artistry instead, save the file and check if the Apache config file if fine by running
httpd -t
You should get Syntax OK if all is well. I'm assuming you have that code inside a <VirtualHost *:8000></VirtualHost> block and would add as well an ErrorLog to it as well and probably would structure the file differently. Check if it works, if it doesn't then I would put some more thought into it. You can use this documentation page as reference (How to use Django with Apache and mod_wsgi).
Then, in your wsgi.py file I would change the sys.path.append line to have '/home/mosajan/artistry', so you would have something like this
import os, sys
from django.core.wsgi import get_wsgi_application
sys.path.append('/home/mosajan/artistry')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'artistry.settings')
application = get_wsgi_application()
Then, open port 80, enable and start httpd and check the result in the browser
enable httpd
systemctl start httpd
systemctl status httpd
You should see that it's starting fine and now when you go to the browser you should be able to see the project working just fine.

Related

How to deploy Python Flask app to Apache (Httpd) running on Amazon Linux EC2 instance

I'm really struggling here. I have a simple Python Flask REST API that I've developed. The API runs fine in my local development environment (Mac OS X) and when directly executed via the console on my EC2 instance.
I want to move this service into production and as such would like to host it behind Apache running on the EC2 instance. This is where I keep hitting a wall and I can't seem to get past the configurations and errors. I've research several articles online and questions here, none seem to be able to help me.
I'm hoping someone here can please provide me with step-by-step directions on how to deploy my service to production behind Apache running on an Amazon Linux EC2 instance.
Here are the steps I've taken:
Launched a basic Amazon Linux EC2 instance.
Apply updates to the instance, sudo yum update
Install Apache and WSIG, sudo yum install httpd24 mod24_wsgi
Start Apache, sudo service httpd start
Configure Apache to start automatically, sudo chkconfig httpd on
Test by hitting the DNS of my EC2 box. I successfully get the Amazon Linux AMI test page.
Adjust permissions on /var/www as follows
sudo groupadd www
sudo usermod -a -G www ec2-user
Logon/off and confirm membership, groups
sudo chown -R root:www /var/www
sudo chmod 2775 /var/www
find /var/www -type d -exec sudo chmod 2775 {} \;
find /var/www -type f -exec sudo chmod 0664 {} \;
Test by hitting DNS of my EC2 box - still good so far.
Now that I know my instance is running, I would like to create two folders where I can test and run my Python Flask code. I do so as follows:
I create two folders, one for development and one for production.
/var/www/rest-dev/
/var/www/rest-prod/
I setup a virtual environment within each of the folders and install Flask.
virtualenv env
env/bin/pip install Flask
I then place a copy of my service in each folder.
Then I set permissions on app.py, chmod a+x app.py
I can successfully execute ./app.py and test the service by hitting the DNS name + port 5000. It works.
Now this is where I get tripped up. My goal is to be able to hit api.example.com and have my service's root load up. In the example code below, "Hello, World!" should simply display.
I've followed the tutorials found here with no luck.
http://peatiscoding.me/geek-stuff/mod_wsgi-apache-virtualenv/
http://webpy.org/cookbook/mod_wsgi-apache
http://www.jakowicz.com/flask-apache-wsgi/
After executing any of the steps in any of the articles above, I get an HTTP error page and nothing loads anymore, including the default Amazon Linux AMI test page. Below are the pieces of code and configurations that I've changed. I haven't changed my httpd.conf ... should I? There are probably several other things I'm missing.
Can someone please help me by providing me the necessary steps in detail to correct my mistakes?
Many thanks in advance!
When I view the error_log for HTTPD, it lists errors like this:
mod_wsgi (pid=8270): Target WSGI script '/var/www/rest-dev/deploy.wsgi' cannot be loaded as Python module.
mod_wsgi (pid=8270): Exception occurred processing WSGI script '/var/www/rest-dev/deploy.wsgi'.
Traceback (most recent call last):
File "/var/www/rest-dev/deploy.wsgi", line 16, in <module>
from app import app as application
File "/var/www/rest-dev/app.py", line 2, in <module>
from flask import Flask
ImportError: No module named flask
Here is my deploy.wsgi file, located in the rest-dev folder:
import os
import sys
import site
# Add virtualenv site packages
site.addsitedir(os.path.join(os.path.dirname(__file__), 'env/local/lib64/python2.7/site-packages'))
# Path of execution
sys.path.append('/var/www/rest-dev')
# Fired up virtualenv before include application
activate_env = os.path.expanduser(os.path.join(os.path.dirname(__file__), 'env/bin/activate_this.py'))
execfile(activate_env, dict(__file__=activate_env))
# import my_flask_app as application
from app import app as application
Here is my vhost.conf file located in /etc/httpd/conf.d/
<VirtualHost *:80>
ServerName api.example.com
WSGIDaemonProcess webtool user=ec2-user group=www threads=5 home=/var/www/rest-dev/
WSGIScriptAlias / /var/www/rest-dev/deploy.wsgi
<directory /var/www/rest-dev>
WSGIProcessGroup webtool
WSGIApplicationGroup %{GLOBAL}
WSGIScriptReloading On
Order deny,allow
Allow from all
</directory>
</VirtualHost>
Here is my app.py example service code for reference:
#!env/bin/python
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return "Hello, World!"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
Turns out, in my deploy.wsgi file I'm referencing lib64 instead of just lib. All the site packages exist in lib.
After changing it and restarting Apache, I'm able to successfully hit my service from the URL.

Run django app with apache

I create a django app and run it with runserver command and it works.But i want to run it with apache so i install wampserver 2.5 with apache 2.4.9 .After that download mod_wsgi‑3.5.ap24.win‑amd64‑py3.4.zip from here and put it in apache modules folder and add this codes to httpd.conf :
LoadModule wsgi_module modules/mod_wsgi.so
WSGIPythonHome E:/software/Python34
WSGIPythonPath E:/software/Python34/python.exe
WSGIScriptAlias /ms "E:/software/wamp/bin/apache/apache2.4.9/htdocs/mysite/mod.wsgi.py"
Alias /ms "E:/software/wamp/bin/apache/apache2.4.9/htdocs/mysite"
and put my django app to mysite folder.but now wamp not run and remain yellow.
Note that this is my application's version:
-- python 3.4 -- Django 1.7 -- wamp 2.5 -- apache 2.4.9 --
and this is codes inside mod.wsgi.py:
import os, sys
path = r'E:\software\wamp\bin\apache\apache2.4.9\htdocs\mysite'
if path not in sys.path:
sys.path.append(path)
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
sorry for my terrible English
following links will help you out.
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/modwsgi/
https://docs.djangoproject.com/en/1.4/howto/deployment/wsgi/modwsgi/
https://www.digitalocean.com/community/tutorials/how-to-run-django-with-mod_wsgi-and-apache-with-a-virtualenv-python-environment-on-a-debian-vps
I just followed these steps and its worked for me.
Hope that help you too.

Making Django work with Apache

I have a test django project that I have been using the django development server for. I want to start using an actual apache server to properly simulate a production environment. I am using Mac OS X.
I have been using this tutorial here, but in the first set of instructions I am getting a 403 from localhost. The browser says I do not have permission to access / on the server.
When I comment out the apache config line from the tutorial, WSGIScriptAlias / /Users/username/Projects/django_books/django_books/django.wsgi I can access localhost.
This is the contents of my django.wsgi file:
import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'django_books.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
path = '/Users/username/Projects/django_books/django_books'
if path not in sys.path:
sys.path.append(path)
What is causing the 403 and why can't I see my django application?
EDIT
Directory structure:
django_books
apache (empty directory right now)
random_book
__init__.py
models.py
views.py
django_books
__init__.py
django.wsgi
settings.py
urls.py
views.py
wsgi.py
media
static
css
style.css
manage.py
2ND EDIT
Permissions on all the directories:
/Users/username/Projects/django_books/django_books/django.wsgi
-rw-r--r--
/Users/username/Projects/django_books/django_books
drwxr-xr-x
/Users/username/Projects/django_books/
drwxr-xr-x
/Users/username/Projects/
drwxr-xr-x
/Users/username/
drwxr-xr-x+
/Users/
drwxr-xr-x
According to my small experience I think you must add the following lines "just below the import sys line to place your project on the path" (so juste under "import sys") like it's said in the tutorial you quote. Also, erase the second "django_books" in your path because you want to link to your site not the app in your site ;-) ("mysite" in the tutorial, not mysite/mysite)
import os
import sys
path = '/Users/username/Projects/django_books'
if path not in sys.path:
sys.path.append(path)
os.environ['DJANGO_SETTINGS_MODULE'] = 'django_books.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
Bye
It's likely an issue related either to your Apache installation, python library, or the filesystem's permissions.
Testing Apache
You don't say it in your question, but I assume from your link you are working with Apache2 and mod_wsgi.
You can test if Apache and mod_wsgi (or your wsgi module) are working properly by placing a dummy wsgi script in the place of django.wsgi . This script (stolen from mod_wsgi's docs) doesn't rely on Django and helps make sure that Apache can read and execute the wsgi script:
# test version of django.wsgi
def application(environ, start_response):
status = '200 OK'
output = 'Hello World!'
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
And restart apache
sudo service apache2 restart
Go ahead and test the page. Did it work? Great. Undo the changes to the django.wsgi script, restart Apache and test again. If the Django site still doesn't work, we need to keep looking. If the test script didn't work, there may be a problem with your Apache installation. Check apache's error log for more information about what happened. On linux it's commonly at /var/log/apache2/error.log . mod_wsgi could be improperly installed, the script's daemon may not have appropriate permission to the wsgi file.
Correcting permission errors
Apache may not be able to read and execute the wsgi file. Running ls -l in the wsgi file's directory as indicated in other answers will tell you the user and group a file belongs to (and if that user and group can read, write, or execute a given file). It's common for a default installation to have the wsgi permissions like so:
-rw------- 1 www-data www-data 1470 Aug 29 16:00 django.wsgi
If you want to use a different user for the daemon process, you need to make sure that the apache conf file defines WSGIDaemonProccess
WSGIScriptAlias / /Users/username/Projects/django_books/django_books/django.wsgi
WSGIDaemonProcess wsgi_user processes=2 threads=15 display-name=%{GROUP}
WSGIProcessGroup wsgi_group
Testing changes to these files and restarting Apache can help narrow down what's up. Keep checking the Apache log files.
Apache Configuration
Django's tutorial on setting up mod_wsgi is good, but read through mod_wsgi's wiki as well. There are a lot of helpful things to consider in your apache conf file besides WSGIScriptAlias. Make sure there is a tag pointing to the folder with your wsgi file. If there are non-public files (like django project files) in that directory, either use the apache directory (update your apache conf file) or add a tag under the node to keep those other files private. While you're in there, you may notice other things that look wrong, like an improperly configured servername, multiple virtual hosts, or other errors.
Testing Python
If you're using virtualenv (do it), make sure that
1. The WSGIDaemonProcess variable defines the appropriate site-packages and the wsgi script's location in the variable's python-path attribute
2. The daemon has rights to read the site packages in your virtualenv.
3. Your wsgi script properly imports django and your site's settings.
Logging Apache
You can increase the level of logging reported by Apache by adding a few lines to your Apache conf file. This setup gives you very verbose logging that you may want during deployment (make sure to make a log folder):
LogLevel info
ErrorLog /Users/username/Projects/django_books/logs/apache_error.log
CustomLog /Users/username/Projects/django_books/logs/apache_access.log combined
I would suspect that the www-data (or whatever user apache is running as) doesn't have access to /Users/username/Projects/django_books/django_books.
su to that user and try and access that directory and the wsgi file within it.
To print all the relevant permissions:
ls -ld /Users /Users/username /Users/username/Projects /Users/username/Projects/django_books /Users/username/Projects/django_books/django_books /Users/username/Projects/django_books/django_books/django.wsgi
You should also check the apache error logs, they might tell you what is going wrong.

Can't deploy a simple Flask application on Webfaction

I have been trying to get Flask to work on my webfaction server for hours with no results.
I followed the instructions at http://flask.pocoo.org/snippets/65/
I have my index.py file stored under htdocs.
import sys
yourappname = "/home/<myusername>/webapps/myapp/htdocs"
if not yourappname in sys.path:
sys.path.insert(0, yourappname)
from yourappname import app as application
Then I have added this to my httpd.conf file:
WSGIPythonPath /home/yourusername/webapps/yourapp/htdocs/
#If you do not specify the following directive the app *will* work but you will
#see index.py in the path of all URLs
WSGIScriptAlias / /home/yourusername/webapps/yourapp/htdocs/index.py
<Directory /home/yourusername/webapps/yourapp/htdocs/>
AddHandler wsgi-script .py
RewriteEngine on
RewriteBase /
WSGIScriptReloading On
</Directory>
then i have myapp.py in the same htdocs directory next to index.py:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
I have my domain pointed to my project in webfaction. The default index.py was working prior to me overwriting with the new one as stated in the instructions. However, I only get the server 500. I apologize but I am a complete noob when it comes to linux and managing servers. I cannot even access my error log under users because it says I do not have permission.
I think that it has something to do with my installation of flask on the linux server, i installed it through easy install it says it installed all of the dependencies and did not give any errors.
A couple of suggestions:
Shouldn't you have myapp everywhere you have yourappname in your index.py?
Also, I am assuming that you have made the appropriate substitutions in `WSGIPythonPath /home/yourusername/webapps/yourapp/htdocs
Have you tried restarting the apache server by issuing a ~/webapps/<app_name>/apache2/bin/restart

Deploying Django with WSGI: App Import Error

I am new in apache, linux and python world. I am trying to deploy django application on apache using WSGI (the recommended way).
My django project directory structure is as follows...
/
/apache/django.wsgi
/apps/ #I put all my apps in this directory
/apps/providers/
/apps/shopping/
/apps/...
/middleware/
...
In apache I have following settings....
LoadModule wsgi_module modules/mod_wsgi.so
WSGIScriptAlias / D:/Projects/project-name/apache/django.wsgi
<Directory "D:/Projects/project-name/apache/">
Allow from all
Order deny,allow
</Directory>
django.wsgi file has got following code...
import os
import sys
import settings
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')
os.environ['DJANGO_SETTINGS_MODULE'] = 'project_name.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
On running I found this error in the appache's error.log...
Error occured on this line. from apps.providers.models import Provider
Import Error: No module named providers.models
I don't know why it is giving me this error. It should have loaded Provider from apps.providers.models but it is trying to load it from providers.model.
Any solution will be appreciated.
Thanks
Try this:
sys.path.insert(0, os.path.join(os.path.abspath(os.path.dirname(__file__)),'..'))
It puts your project folder at the first position and it uses os.path.join to go one directory up (which might be better on windows).
It might be the case that there is another "apps" module on your python path.

Categories