user5017783
user5017783

Reputation:

Running a python script after a button is clicked

So I have an html page like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Find the words</title>
    <h1>Find the Words</h1>
</head>
<body>
<p>Find the largest and the smallest word</p>
<textarea rows="25" cols="100"></textarea>
<br>
<button type="button">Find now!</button>
<br><br>
<label>Largest Word</label>
<input type='largest word'/>

<label>Smallest Word</label>
<input type='smallest word'/>

</body>
</html>

enter image description here I want to run a python script which will find the largest and smallest word from a text and post the result back. The script(words.py) is like this:

#!/usr/bin/env python3

def find_small_large_words(given_string):
    new_list = given_string.split(" ")
    sorted_list = sorted(new_list, key=len)
    return 'Smallest: {0} & Largest: {1}'.format(sorted_list[0], sorted_list[-1])


words = "Ten years on from the financial crisis, it’s hard not to have a sense of déjà vu.Financial scandal and wrangles over financial rule-making still dominate " \
         "the headlines.The cyberhacking at Equifax compromisedpersonal records for half of the adult population of the United States.At SoFi, a one-time fintech darling"

print(find_small_large_words(words))

Ultimately, I want to run the python script on click of the "Find words" button and post them back in the two boxes. How can I do that here? I have read some suggestions about using django framework. Is there any other simple way? If so, how?

Edit: I am trying this in flask. My code so far:

#!/usr/bin/env python3

from flask import *
from flask import render_template

app = Flask(__name__)

@app.route('/', methods = ['GET', 'POST'])
def homepage():

    import words
    return render_template("index.html")

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

However, I am unsure how to execute the python script specifically on the textarea input and post the output back.

Upvotes: 0

Views: 4466

Answers (2)

senaps
senaps

Reputation: 1525

first of all, you need a form to send it's content

$( document ).ready(function() {
    ///
});

$("#submit").onclick(function"() {
  $.post( "url_for('main.calculate')", function( data ) {
     $("#smallest_word").val(data.smallest);
     $("#longest_word").val(data.longest);
  });

});
<form action="" method="">
  <textarea name="txt_words"></textarea>
  <input id="submit" type="submit" name="submit" value="submit">
</form>

<input type="text" id="smallest_word" />
<input type="text" id="longest_word" />

you have two options on how to do it, they are the same but still they have their differences.

1- you can use jquery. for this, you should write a jquery post method so you can post the form containing the text box. post

then, you should get the content and again using jquery populate your inputs values. get

then, you need the view in your flask app:

@mod.route('calculate', methods=['GET', 'POST'])
def calculate():
   if request.method == 'POST':
      text = request.form.get('text_words', 'None')
      if text:
         # do calculate!
         data = {"smallest": calculated_smallest, "longest": calculated_longest}
         return jsonify(data)
   else:
       # it's a GET render the template
       return render_template('form.html')

2- you could send the form, and then return the variables for largest and smallest with render_template so you get those variables and can handle in jinija2 template that if smallest and largest are available, show their content in the input boxes. send variable to template

this is flask code and i have written in on the fl

Upvotes: 1

hafizhanindito
hafizhanindito

Reputation: 447

Judging from your objective here, I suggest you to write a javascript/jquery script, instead of python which necessitates server handling (unnecessary, since you only want it to be posted back to the html without saving it in database or do any I/O).

If you really want to run this in python though, you may need framework like flask or django as you mentioned. If you do, try to save the user input into a string variable before executing the python script. For example:

the_string_var = request(your_form_data)

but again, you may need to create form first or using AJAX/jQuery so you could send the data to your server.

Upvotes: 0

Related Questions