Send Python Output to HTML Field

How to send python output back to html without refreshing the page?

Here's a brief, untested version. It relies on JQuery library.

The following script section of your page can be fired from an onclick event. it runs a fetch request. It should pick up your user-inputted code, or whatever you wish to transmit to the back-end. It is POST data, so content will be contained within the request (as JSON using stringify).

<script>
let api_submit = function() {
fetch('{{ url_for('get_code') }}', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify($('.code').html())
})
.then( response => response.json() )
.then( function (result) {
$('.console').html(result.code);
});
};
</script>

This is your back-end route handling that POSTed data. The content needs to be converted from JSON. The flask render_template uses Jinja to construct the response, and this response data is then sent back to the client in the form of a python dict (one dict element called 'code'). Conveniently, in flask a dict is automatically converted to JSON in the response from the server to that POST request.

@app.route("/get_code/", methods=["GET", "POST"])
def get_code():
if request.method == "POST":
post_data = request.get_json()
code = post_data.get('code')
return dict(code=render_template("py-tut.html", code=code))
# you may need to cater for 'GET' accesses from somewhere

See if that works.

Passing input from html to python and back

Do you have a web server like apache setup this is running on?
If you don't I'm not sure this will work so you may want to have a look at Mamp To allow it to execute your python script you will also need to edit the httpd.conf file

From:

<Directory />
Options Indexes FollowSymLinks
AllowOverride None
</Directory>

To:

  <Directory "/var/www/cgi-bin">
Options +ExecCGI
AddHandler cgi-script .cgi .py
Order allow,vdeny
Allow from all
</Directory>

Alternatively

If you simply want to make an actual HTML file without setting up a server a very basic but crude way of doing this would be to simply write everything to a HTML file you create like:

fo.write("Content-type:text/html\r\n\r\n")
fo.write("<html>")
fo.write("<head>")
fo.write("<title>Hello - Second CGI Program</title>")
fo.write("</head>")
fo.write("<body>")
fo.write("<h2>Your name is {}. {} {}</h2>".format("last_name", "first_name", "last_name"))

fo.write("</body>")
fo.write("</html>")

fo.close()

Which will create a HTML document called yourfile.html in the same directory as your python project.

I don't recommend doing this, but I realise since it's an assignment you may not have the choice to use libraries. In case you, are a more elegant way would be to use something like yattag which will make it much more maintainable.

To copy the Hello World example from their website.

from yattag import Doc

doc, tag, text = Doc().tagtext()

with tag('h1'):
text('Hello world!')

print(doc.getvalue())

Update:

Another alternative if you don't have a local web server setup is to use Flask as your web server.
You'll need to structure your project like:

    /yourapp  
basic_example.py
/static/
/test.css
/templates/
/test.html

Python:

__author__ = 'kai'

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def index():
return render_template('test.html')

@app.route('/hello', methods=['POST'])
def hello():
first_name = request.form['first_name']
last_name = request.form['last_name']
return 'Hello %s %s have fun learning python <br/> <a href="/">Back Home</a>' % (first_name, last_name)

if __name__ == '__main__':
app.run(host = '0.0.0.0', port = 3000)

HTML:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="static/test.css">
<title>
CV - Rogier
</title>
</head>
<body>
<h3>
Study
</h3>
<p>
At my study we learn Python.<br>
This is a sall example:<br>
<form action="/hello" method="post">
First Name: <input type="text" name="first_name"> <br />
Last Name: <input type="text" name="last_name" />
<input type="submit" name= "form" value="Submit" />
</form>
</p>
</body>
</html>

CSS (If you want to style your form?)

p {
font-family: verdana;
font-size: 20px;
}
h2 {
color: navy;
margin-left: 20px;
text-align: center;
}

Made a basic example based on your question here
Hopefully this helps get you on the right track, good luck.

Sending HTML POST data to a Python script

While frameworks that run on WSGI, such as Flask, are much more suitable for building complex applications, a simple Python CGI script comes close to the way that PHP works.

form.html

<form method="post" name="MyFrom" action="/cgi-bin/data.py">
<input name="Data" type="text">
<input name="Submit1" type="submit" value="submit">
</form>

cgi-bin/data.py (don't forget to mark as executable)

#!/usr/bin/env python3
import cgi

print("Content-type:text/html\r\n\r\n")
print('<pre>')
form = cgi.FieldStorage()
for var in form:
print("field:", var)
print("value:", form[var].value)
print('</pre>')

You can test it using python3 -m http.server --cgi 8000 or install a full webserver like Apache with the CGI module.

How to pass HTML form input to Python script?

There is more than one way to do that, you can use CGI (a webserver that calls your python script and serves the output) or a WSGI framework like Django or Flask, or others. Of course, these also need to be served, either from a "typical" webserver like apache or Nginx or something like Gunicorn.

my recommendation is to use a framework like Flask to accomplish that task.

install it by running, preferably in a virtual env:

pip install flask

then you could write something simple as

from flask import Flask, request, render_template 

# Flask constructor
app = Flask(__name__)

# A decorator used to tell the application
# which URL is associated function
@app.route('/test.py', methods =["GET", "POST"])
def get_freq():
if request.method == "POST":
# getting input with freq = set_freq in HTML form
freq = request.form.get("set_freq") # <--- do whatever you want with that value
return "Your freq value is " + freq
return render_template("form.html")

if __name__=='__main__':
app.run()

then you will need to provide your form.html template to be served, and put it in the ./templates folder.

<form action="{{ url_for("get_freq") }}" method="post">
<label for="set_freq">Set Frequency:</label>
<input type="number" id="set_freq" name="set_freq" >
<button type="submit">submit</button>

Posting html form values to python script

in the form action form action="", put the location of your cgi script and the value of the textbox will be passed to the cgi script.
eg.

<form name="search" action="/cgi-bin/test.py" method="get">
Search: <input type="text" name="searchbox">
<input type="submit" value="Submit">
</form>

in your test.py

import cgi
form = cgi.FieldStorage()
searchterm = form.getvalue('searchbox')

thus you will get the key word entered in search text box in searchterm variable in python.

Flask: How can I send a text from python to a HTML textArea

You need to pass your data from the textarea, process it and return both values to the html

below is a sample route

@app.route('/sample', methods=["POST", "GET"])
def sample():
if request.method == 'POST':
sample_input = request.form.get('text1')
sample_output = sample_input + ' -> Processed'
return render_template('index.html', sample_input=sample_input, sample_output=sample_output)
elif request.method == 'GET':
return render_template('index.html')

sample html template

<!DOCTYPE html>
<html>
<head>
<style>
textarea {
width: 400px;
height: 400px;
}

</style>
</head>
<body>

<form action="/sample" method="post">
<h1>Input</h1>

<p><input type="submit" value="Analizar"/></p>

<textarea id="txt1" name="text1" rows="4" cols="50">
{{ sample_input }}
</textarea>
<textarea id="txt2" name="text2" rows="4" cols="50">
{{ sample_output }}
</textarea>

</form>


</body>
</html>

When there is a POST requst, it will update the textarea with the appropriate values, when it is a GET request, it will give a blank textarea

how do i print outputs to html page using python?

There are many Python web frameworks. For example, to break up a sentence using bottle:

break-sentence.py:

#!/usr/bin/env python
from bottle import request, route, run, view

@route('/', method=['GET', 'POST'])
@view('form_template')
def index():
return dict(parts=request.forms.sentence.split(), # split on whitespace
show_form=request.method=='GET') # show form for get requests

run(host='localhost', port=8080)

And the template file form_template.tpl that is used both to show the form and the sentence parts after processing in Python (see index() function above):

<!DOCTYPE html>
<title>Break up sentence</title>
%if show_form:
<form action="/" method="post">
<label for="sentence">Input a sentence to break up</label>
<input type="text" name="sentence" />
</form>
%else:
Sentence parts:<ol>
%for part in parts:
<li> {{ part }}
%end
</ol>
%end

request.forms.sentence is used in Python to access user input from <input name="sentence"/> field.

To try it you could just download bottle.py and run:

$ python break-sentence.py 
Bottle server starting up (using WSGIRefServer())...
Listening on http://localhost:8080/
Hit Ctrl-C to quit.

Now you can visit http://localhost:8080/.



Related Topics



Leave a reply



Submit