I was trying to run my webpage in localhost. I am using python http.server to run the code in localhost. It works for GET requests but not working for POST.
python -m http.server --cgi 8080
It is showing
"Error code: 501
Message: Can only POST to CGI scripts.
Error code explanation: HTTPStatus.NOT_IMPLEMENTED - Server does not support this operation."
CGI scripts have to be in a special directory, like cgi-bin:
Only directory-based CGI are used
cgi_directories¶
This defaults to ['/cgi-bin', '/htbin'] and describes directories to treat as containing CGI scripts.
So you can use them this way:
In a terminal, run: python3 -m http.server --cgi 8080
and in another one:
$ cat cgi-bin/foo.py
#!/usr/bin/env python3
import sys
print('200 OK\r\n\r\nfoo')
$ chmod u+x cgi-bin/foo.py
$ curl http://localhost:8080/cgi-bin/foo.py -X POST
foo
Related
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.
I am trying to run a simple web server with Python. It works fine when I run with below command.
python -m http.server 8000
But when I make a Windows service with same code, it fails with error 1053.
sc create TestWebServer binPath="C:\Python37\python.exe -m http.server 8000" start=auto
I found that some relative posts say debug can solve this problem, but it doesn't work for me.
sc create TestWebServer binPath="C:\Python37\python.exe -m http.server 8000 debug" start=auto
Edited
I made a python code like below.
import os
from http.server import HTTPServer, CGIHTTPRequestHandler
os.chdir('.')
server = HTTPServer(server_address=('', 8000),
RequestHandlerClass=CGIHTTPRequestHandler)
server.serve_forever()
And I made it as Windows service, but it still fails with error 1053.
sc create TestWebServer binPath="C:\Python37\python.exe C:\TestWebServer.py" start=auto
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.
I am asking it because I write very simply app but IT DON'T WORK.
I wrote this command in terminal in the /dir:
python3 -m http.server --cgi
My script is in dir/cgi-bin/hp.py and that code:
#!/usr/bin/env python3
print"Content-type: text/html"
print()
print"<h1>Hello world!</h1>"
This I saw in window of browser:
Error response
Error code: 403
Message: CGI script is not executable ('/cgi-bin/hp.py').
Error code explanation: HTTPStatus.FORBIDDEN - Request forbidden --
authorization will not help."
How can I fix it?
Here are the following steps which I tried to reproduce the problem:
# app.py
print("Content-type: text/html")
print()
print("<h1>Hello world!</h1>")
Created a file app.py in cgi-bin directory
Used command to run http.server with cgi
python -m http.server --bind localhost --cgi 8000
I tried accessing the path "http:localhost/cgi-bin/" got Error 403
Now the resolving part, which is opening the link in browser.
I ran the command:
python -mwebbrowser http://localhost:8000/cgi-bin/app.py
After the while it gave me the result, and I was able to access the link for the step 2 also.
I hope that helps you.
Result:
When I run python -m SimpleHTTPServer 8000 or python -m CGIHTTPServer 8000 in my shell I am hosting the content of my current directory to the internet.
I would like to make the following cgi_script.py work correctly using the above command in the command line when I browse to 192.xxx.x.xx:8000/cgi_script.py
#!/usr/bin/env python
print "Content-Type: text/html"
print
print """\
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
"""
But this script is displayed literally and not only the "Hello World!" part.
Btw I changed the file permissions to 755 for cgi_script.py as well as the folder I am hosting it from.
Try with python -m CGIHTTPServer 8000.
Note that you have to move the script to a cgi-bin or htbin directory in order to be runnable.
SO doesn't allow me to comment so I'm adding this as a separate answer, addition to rodrigo's.
You can use another parameter cgi_directories which defaults to ['/cgi-bin', '/htbin']. More info here
In Python3 the command line is simply
python3 -m http.server --cgi 8000
When I ran into this issue I found that depending on which directory you are in when you run the python -m CGIHTTPServer 8000 command yields different results. When attempting to run the command while in the cgi-bin directory the browser continued to return the raw script code. once I cd'ed one level higher and ran the python -m CGIHTTPServer 8000 command again my script began executing.
#Bentley4 -ifyou are still not able to do,
try importing cgi.
#!C:\Python34\python.exe -u
import cgi
print ("Content-type:text/html")
HTH
This work for me, run the python -m CGIHTTPServer 8000 command same menu level with cgi-bin,and move cgi_script.py into cgi-bin folder.In browser type http://localhost:8000/cgi-bin/cgi_script.py