I'm trying to get started with Python but can't get my server setup up correctly for localhost(using Ampps). Python is running just fine through IDLE and command line, however, when I open up the file in the browser the code is displayed and not run.
I followed this http://www.imladris.com/Scripts/PythonForWindows.html tutorial for getting cgi set up, but it's not working.
Here's the code for my "hello world" program, if that makes any difference.
#!/usr/bin/env python
# -*#!/usr/bin/python
print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<head>'
print '<title>Hello Word - First CGI Program</title>'
print '</head>'
print '<body>'
print '<h2>Hello Word! This is my first CGI program</h2>'
print '</body>'
print '</html>'
Any suggestions?
Your web server is treating your python code as a static file rather than an executable. The goal here is that you want Apache to execute python and send the stdout back to the user's browser.
I'm not familiar with Ampps, but the basic Apache flow to getting this setup is something like this.
AddHandler .py
#!\Python26\python
ScriptInterpreterSource registry
to your httpd.conf, and make sure that windows opens *.py files with Python.exe by default. This can be tested by double-clicking a script. If it doesn't execute, right-click it, choose open-with, then other, and then browse to your python.exe. Make sure to check the "always use this program to open files of this type" box. There's a Microsoft Knowledge Base article on this here.Finally, mod_wsgi or FastCGI is the preferred method for getting Apache to execute python, with the prior holding preference to lower traffic sites (10's of thousands of requests per day). I'd also advise looking into web frameworks such as web.py (very lightweight) or django (heavier weight, but saves you tons of time if you're collecting user input or interfacing with a database).
The given solution worked for me on raspberry pi 3 B+:
1) try to edit: sudo nano /etc/apache2/sites-enabled/000-default.conf
2) Add the below code inside this file:
<Directory /var/www/html>
Options +ExecCGI
AddHandler cgi-script .py
# DirectoryIndex index.py
</Directory>
3) restart apache2 : sudo service apache2 restart
4) in your code just add the few lines above:
#!/usr/bin/env python3
import cgitb
cgitb.enable()
print("Content-Type:text/html;charset=utf-8")
print()
print("Hello world")
5) Your code should work ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With