Can't run Python scripts on an Apache web server (Windows 7) - python

Here's the Python script itself (test.py):
#!/Users/misha/AppData/Local/Programs/Python/Python35-32
print("Content-Type: text/html\n")
print("\n\n")
print("<h1>Test</h1>")
I have this in my Apache's configuration file httpd.conf:
<Directory "c:/Apache24/htdocs">
...
...
Options Indexes FollowSymLinks ExecCGI
...
...
</Directory>
AddHandler cgi-script .cgi .py
I restart Apache--everything else works just fine, but when I try to point to my Python test file in my browser, the server throws an Internal Server Error at me.
Here's my Apache's latest log file entries (I have edited them a little bit just for readability's sake):
(localhost-error.log)
[Thu Feb 11 14:24:39.357362 2016] [cgi:error] [pid 16872:tid 1028]
(OS 5)Access is denied. : [client 127.0.0.1:54957] AH01223:
couldn't spawn child process: C:/Apache24/htdocs/test.py
(localhost-access.log)
127.0.0.1 - - [11/Feb/2016:14:24:39 -0800] "GET /test.py HTTP/1.1"
500 528
I don't even know what to do now.

It may be that Apache can't find the python interpreter. You should make sure the shebang in your file is correct. Test if you can run the file from a different folder.

Make sure you put shebang line in your code.
And check your script permissions. It should be executable.
To change file permission to executable in Linux: chmod +x filename.py
I don't know about windows.

Related

500 Internal Server Error on .py execution

I am trying to have a python script execute on the click of an image but whenever the python script gets called it always throws a 500 Internal Server Error? Here is the text from the log
[Sun Feb 15 20:31:04 2015] [error] (2)No such file or directory: exec of '/var/www/forward.py' failed
[Sun Feb 15 20:31:04 2015] [error] [client 192.168.15.51] Premature end of script headers: forward.py, referer: http://192.168.15.76/Testing.html
I don't understand why it is saying Premature end of script header? I can execute a basic python script that just prints an html header or text. The file I am trying to execute just has some basic wiringPi code that executes fine from the sudo python forward.py command?
EDIT
This is the script I'm trying to execute:
#!/usr/bin/python
import time
import wiringpi2 as wiringpi
wiringpi.wiringPiSetupPhys()
wiringpi.pinMode(40, 1)
wiringpi.digitalWrite(40, 1)
time.sleep(2)
wiringpi.digitalWrite(40, 0)
wiringpi.pinMode(40, 0)
Things to check:
Make sure the script is executable (chmod +x forward.py) and that it has a she-bang line (e.g. #!/usr/bin/env python).
Make sure the script's owner & group match up with what user apache is running as.
Try running the script from the command line as the apache user. I see that you're testing it with sudo. Does it really need sudo? If so whatever user is running as apache will also need sudoers access.
Since it looks like you're using CGI, try adding: import cgitb; cgitb.enable(); to the top of your script. This will catch any exceptions and return it as a response instead of causing the script to die.
In addition to #lost-theory's recommendations, I would also check to make sure:
You have executable permission on the script.
Apache has permission to access the folder/file of the script. For example:
<Directory /path/to/your/dir>
<Files *>
Order allow,deny
Allow from all
Require all granted
</Files>
</Directory>

Apache mod_wsgi throwing error "403 Forbidden" when deploying a Django project

I have been trying to deploy a Django site using mod_wsgi on a CentOS server recently, but so far when I try to access the django site through my laptop, the web page has only been displaying error: 403 Forbidden You don't have permission to access / on this server.
In addition to reading all the obvious documentation, I have looked at these previous questions:
Django + mod_wsgi + Apache = 403 Forbidden
Error message “Forbidden You don't have permission to access / on this server”
Forbidden You don't have permission to access / on this server
Apache mod_wsgi error: Forbidden You don't have permission to access / on this server
Django on apache wtih mod_wsgi (Linux) - 403 Forbidden
Environment:
Centos 6.5
Python 2.6
Django 1.6
I am running the following version of apache:
# apachectl -V
Server version: Apache/2.2.15 (Unix)
Server built: Apr 3 2014 23:56:16
Server's Module Magic Number: 20051115:25
Server loaded: APR 1.3.9, APR-Util 1.3.9
Compiled using: APR 1.3.9, APR-Util 1.3.9
Architecture: 64-bit
Server MPM: Prefork
threaded: no
forked: yes (variable process count)
I installed mod_wsgi using Yum and have confirmed it is installed on the server:
# httpd -M | grep wsgi
wsgi_module (shared)
Syntax OK
My httpd.conf wsgi config snippet is as follows:
#
# Add WSGI configuration
#
WSGIScriptAlias / /usr/local/django/basic/basic/apache/wsgi.py
WSGIPythonPath /usr/local/django/basic/
WSGIDaemonProcess ###.###.###.###
WSGIProcessGroup ###.###.###.###
<Directory /usr/local/django/basic/basic/apache>
<Files wsgi.py>
Options FollowSymLinks
Order deny,allow
Allow from all
</Files>
</Directory>
Finally my wsgi.py script is:
"""
WSGI config for basic project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
import sys
path = "/usr/local/django/basic/basic/apache"
if path not in sys.path:
sys.path.append(path)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "basic.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
Output from error log:
[Fri Oct 24 14:10:43 2014] [error] [client (redacted)] Symbolic link not allowed or link target not accessible: /usr/local/django/basic
[Fri Oct 24 14:11:25 2014] [error] [client (redacted)] Symbolic link not allowed or link target not accessible: /usr/local/django/basic
[Fri Oct 24 14:14:02 2014] [error] [client (redacted)] Symbolic link not allowed or link target not accessible: /usr/local/django/basic
Notes:
The django project is in my user's home directory but has a symbolic link in `/usr/local/django/ pointing to it
In the past when I have worked on projects Error 403 usually meant that the permissions on a file were wrong, but I had check that and the files should all allow the apache user to access them
My web server works fine when I comment out the wsgi related lines of the Apache config.
Sorry, that I posted this a bit late. This was the final fix to my apache config that ultimately worked.
WSGIScriptAlias /basic /var/www/django/basic/basic/wsgi.py
WSGIPythonPath /var/www/django/basic/
<Directory /var/www/django/basic/basic>
Options FollowSymLinks
<Files wsgi.py>
Order allow,deny
Allow from all
</Files>
</Directory>
Alias /static /var/www/django/basic/basic/static
And this is the final version of my wsgi.py file in python. The key line of code here was the PYTHON_EGG_CACHE. That variable was by default set to a directory that did not exist. I set it to /tmp/.python-eggs Make sure that .python-eggs has correct permissions for the apache user to read/write to it wherever you may place this file.
"""
WSGI config for basic project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
import sys
path = "/usr/local/django/basic/basic/apache"
if path not in sys.path:
sys.path.append(path)
os.environ['PYTHON_EGG_CACHE'] = '/tmp/.python-eggs'
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "basic.settings")
#print os.getenv("DJANGO_SETTINGS_MODULE")
#print os.getenv("PYTHON_EGG_CACHE")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
Side note:
A friendly reminder to make sure that every file in your django application is readable, (and writeable if needed) by the apache user. Git once overwrote a file to an old permission I had set up once and it took me a little time to figure out the permissions had changed without realizing it.
May be you forget set DocumentRoot. You should make the DocumentRoot can be read and wrote by apache users.
just do like this:
sudo chown -R www_default:www_default /path/to/you/DocumentRoot
and you can also do like this :
sudo chmod -R 755 /path/to/your/DocumentRoot

Can't figure out error log when installing Django on fastCGI apache server

I get this error from the error log when trying to install Django on a FastCGI apache server.
[Tue Feb 19 10:28:54 2013] [warn] [client 74.59.229.207] (104)Connection reset by peer: mod_fcgid: error reading data from FastCGI server
[Tue Feb 19 10:28:54 2013] [error] [client 74.59.229.207] Premature end of script headers: mysite.fcgi
[Tue Feb 19 10:28:54 2013] [error] [client 74.59.229.207] Premature end of script headers: 500.php
I don't understand if the problem come from the server settings or my .fcgi code.
.htaccess
AddHandler fcgid-script .fcgi
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(media/.*)$ - [L]
RewriteRule ^(adminmedia/.*)$ - [L]
RewriteCond %{REQUEST_URI} !(mysite.fcgi)
RewriteRule ^(.*)$ mysite.fcgi/$1 [L]
mysite.fcgi
#!/usr/bin/python
import sys, os
sys.path.insert(0, "/home2/lacliniq/opt/python27/bin/python")
sys.path.insert(1, "/home2/lacliniq/opt/python27/lib")
os.chdir("/home2/lacliniq/public_html/checkupappdev")
os.environ['DJANGO_SETTINGS_MODULE'] = "firstaid.settings"
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")
I feel like the .fcgi code is ok since it run as expected when run from shell.
If someone could help me get on the right path, it would really help out!
Like Jordan said, it's a problem with the fcgi file.
I was having the same problem trying to get Django working on bluehost. A couple of things to check first are that the fcgi file is set to 755 and make sure your settings file is properly formatted by using:
python manage.py runserver
If those things are OK, try the solution I found at https://my.hostmonster.com/cgi/help/585. From the directions there:
cd <fcgi directory>
unset PYTHONPATH
./mysite.fcgi
If you get a error like:
bad interpreter: No such file or directory
it means that the shebang (#!) line points to a file or directory that doesn't exist or that the fcgi was uploaded via ftp in binary mode instead of ascii.
Try changing "the point of view": run the fcgi file as apache user (I'm sure there will be some interesting messages displayed).
E.g.
$ sudo su www-data
$ cd <fcgi directory>
$ ./mysite.fcgi
It's likely a problem with your .fcgi file, or even more likely, some trouble configuring your django site.
Try running your .fcgi directly in a shell with ./mysite.fcgi. It should spit out some errors, which will give you something to troubleshoot with.

Executing a Python script in Apache2

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.

Mod_wsgi syntax error: "Invalid command import"

i'm trying to setup mod_wsgi to serve my django media files (i want to use this also in a developement env)
I followed this guide to correctly setup mod_wsgi.
This is my wsgi file ("django.wsgi")
import os, sys
path = '/home/smau/Workspace/Maynard/tothego_frontend/'
if path not in sys.path:
sys.path.append(path)
#Calculate the path based on the location of the WSGI script.
apache_configuration= os.path.dirname(__file__)
project = os.path.dirname(apache_configuration)
workspace = os.path.dirname(project)
sys.path.append(workspace)
os.environ['DJANGO_SETTINGS_MODULE'] = 'tothego_frontend.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
This is my conf file ("django.conf")
Alias /site_media/ "/home/smau/Workspace/Maynard/tothego_frontend/site_media/"
<Directory "/home/smau/Workspace/Maynard/tothego_frontend/site_media">
Order allow,deny
Options Indexes
Allow from all
IndexOptions FancyIndexing
</Directory>
WSGIScriptAlias / "/home/smau/Workspace/Maynard/tothego_frontend/srv/mod_wsgi/django.wsgi"
<Directory "/home/smau/Workspace/Maynard/tothego_frontend/srv/mod_wsgi">
Allow from all
</Directory>
This is my "httpd.conf"
Include /home/smau/Workspace/Maynard/tothego_frontend/srv/mod_wsgi/django.wsgi
Everything seems to be like the guide, however, when i try to start/restart apache i get this error
root#archimedes:/etc/apache2# /etc/init.d/apache2 restart
Syntax error on line 1 of /home/smau/Workspace/Maynard/tothego_frontend/srv/mod_wsgi/django.wsgi:
Invalid command 'import', 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!
This is /var/log/apache2.log
[Thu Jul 14 11:39:31 2011] [notice] Apache/2.2.17 (Ubuntu) PHP/5.3.5-1ubuntu7.2
with Suhosin-Patch mod_wsgi/3.3 Python/2.7.1+ configured -- resuming normal operations
[Thu Jul 14 11:44:28 2011] [notice] caught SIGTERM, shutting down
PHP Warning: PHP Startup: Unable to load dynamic library
'/usr/lib/php5/20090626/gd.so'- /usr/lib/php5/20090626/gd.so: cannot open shared object file:
No such file or directory in Unknown on line 0
The log doesn't seem (to me...) anyhow related to my problem. Why do i keep getting the "import" error? Did i give you enought information or do you need something else? I guess my pythonpath is correct:
You're supposed to include the configuration file (django.conf), not the WSGI script (django.wsgi).

Categories

Resources