Return value from python script via CGI - python

I work on a raspberry Pi. I did a small html page with 2 buttons calling executables via CGI and doing things. I would like to add a temperature display on the same page.
I have a small python script that reads the temperature of a sensor and I can successfully display it on console or via direct CGI (typing the url, the only thing displayed is the temperature). I would like to see the temperature directly on my html page, and be able to refresh the value by clicking a button.
I can't find any answer that might help me returning a value from the python script and displaying it in a textbox or something. Do you have any track for me to follow ?

You can write out a complete html page with CGI
A simple CGI script would be
temp=100
print("Content-Type: text/html") # HTML is following
print() # blank line, end of headers
print("<!doctype html>")
print("<html><head><title>Example</title></head><body>")
print("<p>Temperature is:",temp)
print("</p>")
peint('<a href="#">Reload<a>')
print("</body></html>")
you can also use javascript in a page to (re)load the value with Ajax - there are examples on the page (only replace the php-script with your python-cgi)

Related

Running a Python Program in the backend on an HTML button click

I am developing a location based web app/website. The website involves an HTML webpage, which has a button which when clicked by the user should:
Extract the user location coordinates
Run a python Program whose input will be the extracted user location, perform some manipulation.
Finally display real-time results back to the html webpage/ i.e. user computer screen.
The python Program is currently accepting the user location by using geocoder function. The program is successfully running on my system/PC.
I have an AWS EC2 Ubuntu server, to which the location of the vehicle GPS device is being sent.
Finally once everything is set up, I will be hosting/deploying the website so that individual users can test it on their system. I am aware of the hosting part.
Can someone please tell me how do I get along with the task of running the python program on an HTML button click and sending back real time results (which is the output of the python program) back to the html webpage?
To run python code on a buttonClick, you can set a href attribute to a link, which you catch in your flask backend. For example <a href="http://myapp/runthiscode"/> in the HTML and app.rout("/runthiscode") in flask. After that, the manipulation, you can give the updated variables to the page, by redirecting with redirect("/", args=args). args are the updated variables, which you can use in the HTML. For example like this: <a> {{ args }} </a>
The simplest way I can think of doing this is creating a basic API endpoint to do this data processing and return it to your frontend.
The process will look like:
User clicks button
Grab the user's longitutde and latitude (most likely using this, though from the sounds you might be able to do this already)
Submit a POST request to your Flask backend
Render the response in the frontend
Jonas answer gives you a rough sense of what this would look like; the only thing I would add is a tutorial. This one from FreeCodeCamp looks great.

How do I display Python output on a HTML page

When I run the Python script it runs perfectly fine and displays the output on the shell however I want to display the output in html, how do I do it?
I already use Django but I feel like it is very tedious to display it on the html page. Do any of you know how to retrieve the output from shell to html page without being it to complicated?
I also tried REMI, and many more but I can't seem to find the perfect way to display it

How can one create an open web interface to a Python script that accepts and returns text?

I have a Python script that accepts text from a user, interprets that text and then produces a text response for that user. I want to create a simple web interface to this Python script that is accessible to multiple people at once. By this I mean that person A can go to the website for the script and begin interacting with the script and, at the same time, person B can do the same. This would mean that the script is running in as many processes/sessions as desired.
What would be a good way to approach this?
Maybe you should try a python web framework like django or flask .etc
Make a simple website that offers a webpage that contians a form to input text ,and when people visit the url, put their text in the form and submit, your code can handle it and return a webpage to show the result.

Python cgi script not opening a html file in local directory

I have a simple python module that generates a web page containing a list of links. This page is automatically opened in a browser through webbrowser.open('file://' + file.name): no problems here.
From this web page, when clicking on on a link (which has a href like http://localhost/cgi-bin/script.py?param1=Something) it lunches a cgi script that performs some operations with the passed value and at the end generates a new web page, stored locally in my machine (e.g. in a path like /home/user/web/out/) in a folder where I correctly set all rwx permissions.
Well, I've been trying to automatically open this new page in the browser for two days now, attempting with all the solutions I found searching through documentations and forums. I tried with webbrowser.open() again, but then I realized that I can't use it because from the web server I can't open a new browser window itself. Then I tried with redirection, printing first a header (print "Content-type: text/html\n\n") and then
print "Status: 302 Moved"
print "Location: file:///home/user/web/out/abc.html\n\n"`
but this just shows a plain blank page. I gave a try to other redirecting solutions, like
print "<meta http-equiv='refresh' content='0' url='file:///home/user/web/out/abc.html'>"
print "<script type="text/javascript">location.href='file:///home/user/web/out/abc.html';</script>"
print "<script type="text/javascript">windows.open('file:///home/user/web/out/abc.html');</script>"
I even tried inserting a Button with a POST method that triggers the opening of the new page, without success: I keep getting a plain blank page.
It is worth to say that, if I manually open this abc.html page in the browser, it is properly shown.
I think this has to do with the fact that the html page I'm opening from the web server is in locally stored, but I don't know how to solve this. Can somebody point me to the right direction?
A CGI-Script can not redirect I remember.
Note that status code 200 is sent prior to execution of a CGI script, so
scripts cannot send other status codes such as 302 (redirect).
This is some code:
self.send_response(200, "Script output follows")
module: http.server (Python 3)
But you can just open the file and use sys.stdout.write or shutil to copy its content to stdout.

CGI & Python - return choice to python script

I have a python script that, once executed from command line, performs the needed operations and exit. If, during the execution, the program is not able to perform a choice, he prompts the user and asks them to take a decision!
Now I have to implement a web interface, and here comes the problems ... I created an htm file with a simple form that, once the user "submits" he passes the parameters to a cgi script that contains just one line and runs my python program ! And it seems to work.
My question is: if it happens that the program needs to ask the user for a choice, how can I return this value to my python script? To prompt the user for a choice I need to create a webpage with the possible choices ... Does anybody know how can I open a webpage with python ?
The second and most important question is: how can I return a value from a web page to my "original" python module? In python I would simply make a
return choice
but with a web page I have no idea how to do it.
Recap:
Starting from a web page, I run a cgi script ! Done
This CGI script runs my python program... Done
If the program is not able to take a decision,
3a create a web page with the possible choices I can do it
3b display the created web page ????????
3c return the response to the original python module ????????
"Does anybody know how can I open a webpage with python ? The second and most important question is: how can I return a value from a web page to my "original" python module ??"
This is all very simple.
However, you need to read about what the web really is. You need to read up on web servers, browsers and the HTTP protocol.
Here's the golden rule: A web server responds to HTTP requests with a web page.
The second part of that rules is: A Request is a URL and a method (GET or POST). There's more to a request, but that's the important part.
That's all that ever happens. So, you have to recast your use case into the above form.
Person clicks a bookmark; browser makes an empty request (to a URL of "/") and gets a form.
Person fills in the form, clicks the button; browser POST's the request (to the URL in the form) and gets one of two things.
If your script worked, they get their page that says it all worked.
If your script needed information, they get another form.
Person fills in the form, clicks the button; browser POST's the request (to the URL in the form) and gets the final page that says it all worked.
You can do all of this from a "CGI" script. Use mod_wsgi and plug your stuff into the Apache web server.
Or, you can get a web framework. Django, TurboGears, web.py, etc. You'll be happier with a framework even though you think your operation is simple.
I think you could modify the Python script to return an error if it needs a choice and accept choices as arguments. If you do that, you can check the return value from your cgi script and use that to call the python script appropriately and return the information to the user.
Is there a reason why you can't call the python script directly? I suspect you'd end up with a neater implementation if you were to avoid the intermediate CGI.
What webserver are you using? What cgi language? Perl maybe?
Web pages don't return values, and they aren't programs - a web page is just a static collection of HTML or something similar which a browser can display. Your CGI script can't wait for the user to send a response - it must send the web page to the user and terminate.
However, if the browser performs a second query to your CGI program (or a different CGI program) based on the data in that page, then you can collect the information that way and continue from that point.
Probably easier if you write your cgi in python then call your python script from the cgi script.
Update your script to separate the UI from the logic.
Then it should be relatively easy to interface your script with the (python) cgi script.
For python cgi reference:
Five minutes to a Python CGI
http://docs.python.org/library/cgihttpserver.html
I think first off you need to separate your code from your interface. When you run a script, it spits out a page. You can pass arguments to it using url parameters. Ideally you want to do your logic, and then pass the results into a template that python prints to the cgi.

Categories