Running Python CGI on Cloud9 - python

I can get Python CGI programs to run in other environments but would value help getting to "hello world" with the Cloud9 environment.
My simple programs runs fine, but I cannot get the HTML/web version of even a simple program.
The run gives me a suggestion of:
Your code is running at https://workspacename-username.c9.io.
Important: use os.getenv(PORT, 8080) as the port and os.getenv(IP, 0.0.0.0) as the host in your scripts!
But I do not know what to do with that.
My simple code follows. I also tried to run it as filename.cgi, but that does not work.
#!/usr/bin/env python
print "Content-Type: text/html"
print "<html>"
print "<head><title>My first CGI program</title></head>"
print "<body>"
print "<p> It works!! </p>"
print "</body></html>"

You need to install Flask first, you can do it by the command:
$ sudo easy_install Flask
your code should be smth like this:
import os
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello():
html= "<html>"
html+= "<head><title>My first CGI program</title></head>"
html+= "<body>"
html+= "<p> It works!! </p>"
html+= "</body></html>"
return html
app.run(host = os.getenv('IP','0.0.0.0'), port=int(os.getenv('PORT',8080)))
After you start application, you'll see
Your code is running at https://workspacename-username.c9users.io.
* Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
now you can open https://workspacename-username.c9users.io, it will work

Related

Python runs on terminal, not on web browser

I'm trying to run a simple python script on my webserver, but it's not showing up in the web browser.
In terminal I check if python is installed:
whereis python
python: /usr/bin/python2.7 /usr/bin/python2.7-config /usr/bin/python /usr/lib/python2.7 /usr/lib64/python2.7 /etc/python /usr/local/bin/python3.9-config /usr/local/bin/python3.9 /usr/local/lib/python3.9 /usr/include/python2.7 /opt/imh-python/bin/python2.7 /opt/imh-python/bin/python2.7-config /opt/imh-python/bin/python3.9 /opt/imh-python/bin/python /usr/share/man/man1/python.1.gz
This tells me that I have python installed. I created a simple file that contains this code:
#! /usr/bin/python
print('Content-Type: text/html\r\n\r\n')
print('\r\n')
print('Hello World')
I ran dos2unix and chmod a+x on the file.
I ran the file in terminal and get this output:
Content-Type: text/html
Hello World
When I try to open the file in the web browser this is the output I get:
#! /usr/bin/python
print('Content-Type: text/html\r\n\r\n')
print('\r\n')
print('Hello World')
I changed the single quotes in the print statement to double. I tried different ways of entering new lines, but nothing seems to work. Am I missing or overlooking something crucial here?
The browser doesn't have a Python interpreter. So opening the file in a browser is just going to show your source code. If you want it to show on a browser you need to run it on a server where it can be interpreted. A simple solution is to use Flask, which comes with a development server. Once you've installed flask:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello():
return 'Hello World'
app.run()
Then navigate to http://localhost:5000 in your browser.

Running python script on xampp

I googled this and tried everything but I could not run my test.py on apache.
I have updated httpd.conf file to AddHandler .py
#!/usr/local/opt/python/bin/python3.7
print("Hello World!")
When I open this file in browser I am getting this error
Error message:
End of script output before headers: test.py
Have you tried to use Flask instead? It start a server that you can access via browser.
Here you can find an Hello world tutorial, or also here.
First, you have to install Flask: pip install Flask.
Then the server code, saved in a python file, for example your_server.py, has to look like this:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
You can run the script, then go to http://localhost:5000/ and you'll see the 'Hello World!' message.
Now you can modify the method hello() to do what you need, or create other method/operations.
The tutorial can give you more details, but this is the main concept.

How do you execute a server-side python script using http.server?

I have a collection of python scripts, that I would like to be able to execute with a button press, from a web browser.
Currently, I run python -m http.server 8000 to start a server on port 8000. It serves up html pages well, but that's about all it does. Is it possible to have it execute a python script (via ajax) and return the output, instead of just returning the full text of the .py file.
Additionally, if not, is there a simple (as in only 1 or 2 files) way to make this work? I'm looking for the equivalent of PHP -s, but for python.
For completeness, this is my html
<h1>Hello World</h1>
<button>
Click me!
</button>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.js"> </script>
<script>
$('button').click(function(){
$.get('/gui/run_bash.py');
});
</script>
Add --cgi to your command line.
python -m http.server --cgi 8000
Then place your python scripts in ./cgi-bin and mark them as executable.
$ mkdir cgi-bin
$ cp hello.py cgi-bin/hello.py
$ chmod +x cgi-bin/hello.py
You may need to slightly modify your python scripts to support the CGI protocol.
Here is the server running:
$ cat cgi-bin/hello.py
#! /usr/bin/env python3
print("Content-Type: application/json")
print()
print('{"hello": "world"}')
radams#wombat:/tmp/z/h$ python -m http.server --cgi
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
127.0.0.1 - - [20/Mar/2018 18:04:16] "GET /cgi-bin/hello.py HTTP/1.1" 200 -
Reference: https://docs.python.org/3/library/http.server.html#http.server.CGIHTTPRequestHandler
http.server merely serves static files, it does not do any serverside processing or execute any code when you hit a python file. If you want to run some python code, you'll have to write an application to do that. Flask is a Python web framework that is probably well-suited to this task.
Your flask application might look something like this for executing scripts...
import subprocess
from flask import Flask
app = Flask(__name__)
SCRIPTS_ROOT = '/path/to/script_dir'
#app.route('/run/<script_name>')
def run_script(script_name):
fp = os.path.join(SCRIPTS_ROOT, script_name)
try:
output = subprocess.check_output(['python', fp])
except subprocess.CalledProcessError as call:
output = call.output # if exit code was non-zero
return output.encode('utf-8') # or your system encoding
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8000)
And of course, I should include an obligatory warning 'having a webserver execute commands like this is insecure', etc, etc. Check out the Flask quickstart for more details.

Premature end of script headers Error in python cgi script

I am running to a problem a vps I recently moved to. I am trying to run a python cgi script, but I am getting an apache Premature end of script headers Error.
(I chmod +x the script file)
The script is pretty simple:
#!/usr/bin/env python
import cgi, cgitb
cgitb.enable()
print "Content-type: text/html"
print "<html><body>hello scritp</body></html>"
Now if I name the script as test**.py** it runs fine on server. But if I do it the correct way, calling it test**.cgi** I receive a Internal Server Error.
I run the script from the terminal
./test.cgi
I get no errors
Content-type: text/html
<html><body>hello scritp</body></html>
Did anyone encountered before this issue? And a solution for it? :)
Cheers
change the header as:
print "Content-type: text/html\n\n"
There must be at least an empty line between HTTP headers and body.
So
print "Content-type: text/html\n" will work just fine
Reference: Wikipedia

How to execute python script on the BaseHTTPSERVER created by python?

I have simply created a python server with :
python -m SimpleHTTPServer
I had a .htaccess (I don't know if it is usefull with python server)
with:
AddHandler cgi-script .py
Options +ExecCGI
Now I am writing a simple python script :
#!/usr/bin/python
import cgitb
cgitb.enable()
print 'Content-type: text/html'
print '''
<html>
<head>
<title>My website</title>
</head>
<body>
<p>Here I am</p>
</body>
</html>
'''
I make test.py (name of my script) an executed file with:
chmod +x test.py
I am launching in firefox with this addres: (http : //) 0.0.0.0:8000/test.py
Problem, the script is not executed... I see the code in the web page...
And server error is:
localhost - - [25/Oct/2012 10:47:12] "GET / HTTP/1.1" 200 -
localhost - - [25/Oct/2012 10:47:13] code 404, message File not found
localhost - - [25/Oct/2012 10:47:13] "GET /favicon.ico HTTP/1.1" 404 -
How can I manage the execution of python code simply? Is it possible to write in a python server to execute the python script like with something like that:
import BaseHTTPServer
import CGIHTTPServer
httpd = BaseHTTPServer.HTTPServer(\
('localhost', 8123), \
CGIHTTPServer.CGIHTTPRequestHandler)
###  here some code to say, hey please execute python script on the webserver... ;-)
httpd.serve_forever()
Or something else...
You are on the right track with CGIHTTPRequestHandler, as .htaccess files mean nothing to the the built-in http server. There is a CGIHTTPRequestHandler.cgi_directories variable that specifies the directories under which an executable file is considered a cgi script (here is the check itself). You should consider moving test.py to a cgi-bin or htbin directory and use the following script:
cgiserver.py:
#!/usr/bin/env python3
from http.server import CGIHTTPRequestHandler, HTTPServer
handler = CGIHTTPRequestHandler
handler.cgi_directories = ['/cgi-bin', '/htbin'] # this is the default
server = HTTPServer(('localhost', 8123), handler)
server.serve_forever()
cgi-bin/test.py:
#!/usr/bin/env python3
print('Content-type: text/html\n')
print('<title>Hello World</title>')
You should end up with:
|- cgiserver.py
|- cgi-bin/
` test.py
Run with python3 cgiserver.py and send requests to localhost:8123/cgi-bin/test.py. Cheers.
Have you tried using Flask? It's a lightweight server library that makes this really easy.
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return '<title>Hello World</title>'
if __name__ == '__main__':
app.run(debug=True)
The return value, in this case <title>Hello World</title>, is rendered has HTML. You can also use HTML template files for more complex pages.
Here's a good, short, youtube tutorial that explains it better.
You can use a simpler approach and use the --cgi option launching the python3 version of http server:
python3 -m http.server --cgi
as pointed out by the command:
python3 -m http.server --help

Categories