Sorry if I seem lost, but I have very little experience deploying web applications and searching online isn't helping. As the title states, I am running Ubuntu, Apache2, PostgreSQL, and Django , -- and I repeatedly get error messages, most of which are either vague and/or have no clear solutions. Plus my ignorance on the specific interactions quicksands any attempt at finding a solution, so i will be very specific.
Installations:
apache2 libapache2-mod-wsgi-py3 -- for python 3
I can't remember if I installed django or if it automatically packaged with my PyCharm package.
PostgreSQL - works fine.
The Application:
It is a cloud computing platform, so it needs to receive files, store files, and render files.
Works fine with Django's web server attached.
has static files and needs to write to a media folder
settings.py:
- DEBUG = True
- WSGI_APPLICATION = 'example.wsgi.application'
-DATABASES =
'default':
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'example',
'USER': 'example',
'PASSWORD': 'example',
'HOST': 'localhost',
'PORT': '',
000-default.conf
<VirtualHost *:80>
ServerName FireAnts.localhost
ServerAlias www.FireAnts.localhost
DocumentRoot /var/www/FireAnts
<Directory /var/www/FireAnts/FireAnts>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIDaemonProcess FireAnts python-path=/var/www/FireAnts python-home=/var/www/FireAnts/venv
WSGIProcessGroup FireAnts
WSGIScriptAlias / /var/www/FireAnts/FireAnts/wsgi.py
</VirtualHost>
ERRORS, per the log
Currently, i'm getting "No module named 'django'".
Frequently i get "populate" is not reentrant -- an issue which seems to have a million possible solutions.
Target WSGI cannot be loaded as Python module.
I temporarily got another script to work by deleting all lines writing to an error.txt file -- a file that exists for both packages and generates syntax errors. For some unexplained reason, it broke again with the "No module name django" failure. Also, i moved the entire package from an outside directory to the '/var/www/' (and modified the 000-default.conf file). that shouldn't generate any issues because the virtual environment traveled with the package and the database should still connect from the outside. But I assume this generated the 500 error before by writing to a file that no longer has write permissions. Could my database be generating the error some how (by blocking the connection)? If a user uploads a package later on, it will write to the media folder temporarily. Even if it didn't write yet, could this break it? Do any more modification need to be made when moving the package to the /var/www directory? I have no clue what could be generating these errors. It must be an apache configuraton error because it works with Django's web server, and only breaks with apache2...
Sorry for the mess and lack of organization; i just have no clue where I could have messed up. - but every attempted fix just breaks it again. I would appreciate any and all help.
You maybe missing out providing the WSGIDaemonProcess correctly in your default conf. Try giving as
WSGIDaemonProcess FireAnts python-path=/var/www/FireAnts/venv/path/to/bin/python:/var/www/FireAnts/FireAnts
Where replace <path/to/> with correct path to your venv. You have to give complete path of the python executable.
Edit the wsgi.py file of your project
/var/www/FireAnts/FireAnts/wsgi.py:
import os
import sys
from django.core.wsgi import get_wsgi_application
path = '/var/www/FireAnts'
if path not in sys.path:
sys.path.insert(0, path)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "FireAnts.settings")
application = get_wsgi_application()
Okay, so i figured out the answer.
Everything was configured the correct way, but there was a missing installation with an unclear error message.
I located the file that generates the "populate() isn't reentrant" message, found the line that provides the error message, and instructed it to continue by replacing "raise RuntimeError("populate() isn't reentrant")" with "self.app_configs = {}". Instead of receiving a vague, unclear answer, the error log reported a missing "psycopg2" import. I activated the venv directory and installed psycopg2. After that, it worked.
Related
I cannot for the life of me figure of why this flask application I'm trying to launch is not working. I am running it on a $5 Digital Ocean droplet. Here's (hopefully) everything you need to know about it:
Directory layout (contained within /var/www/):
FlaskApp
FlaskApp
__init__.py
static
templates
venv
flaskapp.wsgi
__init__.py:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "yay it worked"
if __name__ == "__main__":
app.run()
flaskapp.wsgi:
#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/FlaskApp/")
from FlaskApp import app as application
application.secret_key = 'Add your secret key'
FlaskApp.conf (contained in /etc/apache2/sites-availble):
<VirtualHost *:80>
ServerName the.ip.blah.blah
ServerAdmin admin#mywebsite.com
WSGIScriptAlias / /var/www/FlaskApp/flaskapp.wsgi
<Directory /var/www/FlaskApp/FlaskApp/>
Order allow,deny
Allow from all
</Directory>
Alias /static /var/www/FlaskApp/FlaskApp/static
<Directory /var/www/FlaskApp/FlaskApp/static/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
venv was created from calling virtualenv venv within /var/www/FlaskApp/FlaskApp/. I installed flask in venv using pip install flask after entering venv using source venv/bin/activate.
Wsgi has been enabled (a2enmod wsgi). FlaskApp.conf was enabled (a2ensite FlaskApp). And, finally, I restarted apache many times, but to no success (service apache2 restart).
I was following this guide on how to set up a flask application.
Here is a screenshot of what my error looks like:
Any help on getting this to work would be greatly appreciated.
Thanks in advance.
EDIT: I found the problem: ImportError: No module named flask. This is a little strange since I did do pip install flask within the virtualenv. When I just open a python console session in the virtualenv and try import flask I get no error, so not sure what's going on.
Also, how is this application even using venv? I don't see it getting accessed anywhere so how is it even using it? Perhaps this is why i'm getting the ImportError, because I only have flask installed on the virtualenv but it's not being used?
The problem is essentially that you are installing Flask, and possibly other required libraries, in a virtual environment but the python (wsgi interface) is running with the system python which does not have these extra libraries installed.
I have very little recent experience running Python on Apache (I come from an era of mod_python and cgi), but apparently one way to handle this is to use the site package to add the site-packages from your venv to the Python that is executed. This would go in your .wsgi file.
import site
site.addsitedir('/path/to/your/venv/lib/pythonX.X/site-packages')
I think the best way to solve your problem is to add tell your wsgi file about your virtual environment and activate it:
put the following code in your your flaskapp.wsgi
activate_this = '/path/to/env/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))
and restart apache.
hope it will help!
find more here
I am Using python 2.7.2,Django 1.3.1, Apache 2.2.22 on WindowsXP(win32). By the documentation i found here i did the step by step, but when the directory section is given
`Alias /media/ C:/Programs/TestDjango/mysite/media/
<Directory C:/Programs/TestDjango/mysite/media/>
Order deny,allow
Allow from all
</Directory>
WSGIScriptAlias / C:/Programs/TestDjango/mysite/apache/django.wsgi
<Directory C:/Programs/TestDjango/mysite/apache>
Order deny,allow
Allow from all
</Directory>`
and restarted the Apache, On opening localhost/mysite i get a Microsoft Visual C++ Library runtime error, and the Apache error log shows "Caught ImproperlyConfigured while rendering: Error loading pyodbc module: DLL load failed: A dynamic link library (DLL) initialization routine failed."....My Django app run in WAMP but wish to know where did i go wrong using Apache2.2.22 alone. Followed many Django documentation but still the same, Please to help me find where did i go wrong. thanks
(identation was fixed by guettli)
I got it solved, it was the version problem, as i worked with Apache 2.2.21 instead of Apache 2.2.22, its working. i followed the step in this link.
Install Python 2.7.2, Django 1.3.1 and Apache2.2.21
Install the modwsgi module.
The module file will be named something like mod_wsgi-win32-ap22py26-2.6.so get mod_wsgi.
Copy it to the modules directory of the Apache installation. E.g., C:/Program Files/Apache Software Foundation/Apache2.2/modules.
Rename it to mod_wsgi.so. Right click--> properties click Unblock and apply
Open Apache's http.conf file.
Add the line LoadModule wsgi_module modules/mod_wsgi.so before all the other LoadModule entries.
Configure Apache for your Django project by adding the following to end of http.conf:
# Static content
Alias /media/ C:/Programs/TestDjango/mysite/media/
<Directory C:/Programs/TestDjango/mysite/media/>
Order deny,allow
Allow from all
</Directory>
# Django dynamic content
WSGIScriptAlias / C:/Programs/TestDjango/mysite/apache/django.wsgi
<Directory C:/Programs/TestDjango/mysite/apache>
Order deny,allow
Allow from all
</Directory>`
Where icardtest is the Django project root. The paths below icardtest will be specific to your project. This configuration serves all static media via the URL space /media/ and all the rest via WSGI and Django.
Create a file django.wsgi and add the following to it:
` import os
import sys
sys.path.append('C:/Programs/TestDjango')
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()`
Restart Apache.
Your error has to do with your python setup, not Apache.
Error loading pyodbc module: DLL load failed: A dynamic link library (DLL) initialization routine failed.
This means that the Python you are using with Apache cannot load the pyodbc module. Once you fix this error, you can proceed.
I am trying to execute a Python program using Apache. However, Apache will only serve the file and not actually execute it. The permissions on the file are r/w/x and it is in /var/www. I will post the contents of httpd.conf and the program code after. I also tried to running the python script as a .cgi file but that did not work as well. I have both the mod_python and mod_wsgi modules loaded into apache as well.
Python sample:
#!/usr/bin/python
# enable debugging
import cgitb
cgitb.enable()
print "Content-Type: text/plain\r\n\r\n"
print
print "Hello World!"
httpd.conf:
AddHandler cgi-script .cgi .pl
AddHandler python-program .py
I know its a small httpd.conf file but when I installed apache, there was nothing in the file. I should also mention that this is just so that I learn the basics of running python in apache. It is not meant for production.
Thanks for the help!
Edit
The OS I'm using is Ubuntu 10.04 and the version of apache is 2. I have python version 2.6 which is automatically used when #!/usr/bin/env python is invoked.
I am getting two main errors, the first is that the file is not being found even though the permissions of the file and folder are 777. The error from the log is
[Sun Feb 05 13:29:44 2012] [error] [client 192.168.1.3] File does not exist: /var/www/poit-0.1
This error is for a different python script that I did not write. What is weird is that the file shows up in the index of the folder when accessed from a browser window. However, when I navigate to the file, I get the above error.
The other error that I am getting is premature end of headers. The error is below:
[Sun Feb 05 12:10:19 2012] [error] (8)Exec format error: exec of '/var/www/pyth.py' failed
[Sun Feb 05 12:10:19 2012] [error] [client 192.168.1.3] Premature end of script headers: pyth.py
The first line of httpd.conf: AddHandler cgi-script .cgi .pl is irrelevant, since you're testing python scripts and not perl scripts. And you should define those directives within the location of your python script, and tell apache that it should execute cgi scripts in that location: Options +ExecCGI. This snippet would be a start:
<Directory /path/to/sample.py />
Options +ExecCGI
AddHandler cgi-script .py
</Directory>
Addendum 1:
As per my last comment, try this script. It should spit information about the cgi environment.
#!/usr/bin/python
import cgi
cgi.test()
Addendum 2:
I got your script to work with the above configuration. The problem is that script is written in python2. And the default interpreter apache is invoking to execute the script, is python3 (at least in my case, and chances are this would be the same for you too).
This is a python3 version of the hello world script:
#!/usr/bin/env python
# enable debugging
import cgitb
cgitb.enable()
print("Content-Type: text/plain;charset=utf-8")
print()
print("Hello World!")
Addendum 3:
For the first error, make sure the permission and the ownership of whatever directory and files you're attempting to deploy are properly set. And try adding those directives to httpd.conf:
Order allow,deny
Allow from all
Which will get you this:
<Directory /path/to/sample.py />
Options +ExecCGI
AddHandler cgi-script .py
Order allow,deny
Allow from all
</Directory>
For the second error, unless I am missing something, it looks like apache is invoking python 3 interpreter to execute your script. To rule out this possibility, you might try the following:
ls -al /usr/bin/python*
This will list the python interpreters available on your system. If you have more than one interpreter you'll get something similar to this output:
/usr/bin/python -> python3*
/usr/bin/python2.6*
/usr/bin/python3*
If not, it would be this output:
/usr/bin/python -> python2.6*
/usr/bin/python2.6*
To make sure, this is not the issue you're having, try with this modified sample script:
#!/usr/bin/python2.6
# enable debugging
import cgitb
cgitb.enable()
print "Content-Type: text/plain\r\n\r\n"
print
print "Hello World!"
You'll notice that I explicitly mentioned the version of the interpreter apache should invoke, which is ugly. But for the sake of testing, you can do it. Of course you should map #!/usr/bin/python2.6, to whatever binary you have on your server, and make sure you don't mix python 3 comtipable code with python 2 interpreter and vice versa.
Re: The Exec format error.
I've run in to this myself a couple of times before. I had the exact same (cryptic) error message.
I was developing Python (3) scripts to use via CGI in Notepad++ on my Windows machine, and then uploading them to my Linux server.
After much frustration, I discovered that this issue is related to line endings and you need to convert Windows line endings (\r\n) to UNIX line endings (\n).
In Notepad++ (6.1.5), you can achieve this by going to the Edit menu and selecting the EOL conversion option and then saving the file.
**For apache2 version 2.4
sudo apt-get install python
sudo apt-get install apache2
edit file /etc/apache2/conf-enables/serve-cgi-bin.conf
====comment old section and add code below:
ScriptAlias /cgi-bin/ /var/www/cgi-bin/
<Directory "/var/www/cgi-bin">
AddHandler cgi-script .py
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
</Directory>
=========================================
edit file /etc/apache2/apache2.conf
***add code below:
<Directory "/var/www/cgi-bin">
AllowOverride None
Options ExecCGI
Order allow,deny
Allow from all
</Directory>
<Directory "/var/www/cgi-bin">
Options All
</Directory>
<Directory /usr/local/apache2/cgi-bin>
Require all granted
</Directory>
Note!
use for apache2.4
file python keep in directory: /var/www/cgi-bin/
You can test :go to http://localhost/cgi-bin/<namefile>.py
referrence
https://www.linux.com/blog/configuring-apache2-run-python-scripts
In my case, it was a trivial issue. I had to add this line:
#!/usr/bin/python3
to the top of every .py file I wanted to run.
Then, everything started working correctly.
I had the same symptom and my config looked okay compared to the answers above.
I found that my new install was not configured to load mod_cgi.so
Loading the required module looks a bit like this. If restarting the server will give you an error that the file was not found, figure out where the file is adjust the path accordingly.
LoadModule cgi_module modules/mod_cgi.so
I'm assuming you are using firefox. I read somewhere else on the 'net that it could be related to the firefox addons installed on a machine.
I was getting this error and I use firefox 20. Switched to Opera and I did not get any more errors and the python scripts seemed to execute just fine.
Edit: It was actually an eval() method call I had overlooked that had appended "(" and ")" to the results of the script that caused my failure. Once I removed them, it worked for me.
I noticed you did not post the javascript, html, or whatever it is you use to call the script in the first place. Perhaps you could post it for us? I did a direct copy/paste example from a blog site without looking at what I had copied. That was my error.
I am trying to deploy a Django project and am using Apache2 with mod_wsgi. Here are the relevant lines in my Apache conf file:
WSGIScriptReloading On
WSGIDaemonProcess myprojectcom
WSGIReloadMechanism Process
WSGIProcessGroup myprojectcom
WSGIApplicationGroup myprojectcom
WSGIPassAuthorization On
WSGIScriptAlias / /home/myproject/myproject/deploy/deploy.wsgi
I've used a very similar conf file for many other deployments, but this is the first time that I'm getting the following error:
/etc/apache2/sites-available$ sudo /etc/init.d/apache2 restart
Syntax error on line 8 of /etc/apache2/sites-enabled/myproject.com:
Invalid command 'WSGIReloadMechanism', perhaps misspelled or defined by a module not included in the server configuration
Action 'configtest' failed.
The Apache error log may have more information.
...fail!
I don't see any syntax error, though. I'm on Ubuntu, using the libapache2-mod-wsgi package. What could be wrong?
Remove the whole line:
WSGIReloadMechanism Process
It isn't needed any more and the directive was removed completely in mod_wsgi 3.X.
You should preferable not rely on old blog posts for how to set up mod_wsgi and use the actual mod_wsgi documentation on the mod_wsgi site instead.
When I'm executing
django-admin.py startproject site
it works.
But if I'm only copying site folder it doesn't work.
Why?
<VirtualHost *:80>
ServerName django.stanislavfeldman.com
# Django settings
WSGIScriptAlias / /var/www/django/wsgi_handler.py
WSGIDaemonProcess django.stanislavfeldman.com maximum-requests=200 stack-size=524288
ErrorLog /var/www/django/error.log
LogLevel warn
</VirtualHost>
wsgi_handler.py:
import os, sys
sys.path.append('/var/www/django')
os.environ['DJANGO_SETTINGS_MODULE'] = 'site.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
If you have something like this in apache configs:
WSGIScriptAlias /path /base/path/devel/your_project.wsgi
And this inside your_project.wsgi:
sys.path.append('/base/path')
os.environ['DJANGO_SETTINGS_MODULE'] = 'devel.settings'
Then apache will look at /base/path/devel/settings.py. If you move or copy /base/path/devel to /base/path/production you have to edit DJANGO_SETTINGS_MODULE at your_project.wsgi pointing to 'production.settings'.
Ensure you have read:
http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango
and also watch this presentation:
http://code.google.com/p/modwsgi/wiki/WhereToGetHelp?tm=6#Conference_Presentations
Your problem is going to be a sys.path or permissions issue which are both covered by the above.
That you are using 'maximum-requests=200 stack-size=524288' options to WSGIDaemonProcess directive makes me question whether you have referred to the mainstream documentation as basic instructions don't tell you to use them. Instead looks like you have used some arbitrary persons blog post for how to set it up, or relying on some folklore given to you on an IRC channel. :-)
Check your python path to make sure that WSGI can reference it.
I had a problem with a symlink not being followed from the site-packages dir. Double check your apache config and symlinks as well.
This doesn't appear to be the problem in your case, but I ran smack into the same ImportError when I used the WSGIPythonPath directive (instead of the .wsgi file) to set up sys.path. That worked fine until I switched to running WSGI in daemon mode. Once you do that, you have to use the python-path argument to the WSGIDaemonProcess directive instead.