I've got a bit of webdev experience, and just started learning python. I've created a python script that takes in an argument, and then runs a program, and prints print statements into the console. I'm curious if it's possible to put this program behind a webpage.
i.e. Webpage with a dropdown, chose the option and click a "Go" button. Then the python script is run with the option you chose, and your report is shown on the page.
I've looked at a few similar posts: Execute a python script on button click
run python script with html button
but they seem to offer very different solutions, and people seem to think the PhP idea is insecure. I'm also looking for something a bit more explicit. I'm fine to change the python script to return ajson or something instead of just print statements.
1 Answer 1
A pretty common way to communicate between a webpage and a python program is to run the python as a WSGI server. Effectively the python program is a separate server which communicates with the webpage using GETs and POSTs.
One nice thing about this approach is that it decouples the Python app from the the web-page proper. You can test it by sending http requests directly to a test server while you're developing.
Python includes a built-in WSGI implementation, so creating a WSGI server is pretty simple. Here's a very minimal example:
from wsgiref.simple_server import make_server
# this will return a text response
def hello_world_app(environ, start_response):
status = '200 OK' # HTTP Status
headers = [('Content-type', 'text/plain')] # HTTP Headers
start_response(status, headers)
return ["Hello World"]
# first argument passed to the function
# is a dictionary containing CGI-style environment variables
# second argument is a function to call
# make a server and turn it on port 8000
httpd = make_server('', 8000, hello_world_app)
httpd.serve_forever()
4 Comments
fetch("http://you/url/here?param=somevalue") You'd write the server to parse the query string and process it in the results.