0

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.

6
  • Have you tried a onclick event with your button? Commented Oct 2, 2017 at 8:31
  • If you have a web server, you could google for cgi. Other than that, read the tutorial of your favourite web frame work. Commented Oct 2, 2017 at 8:32
  • @Tomm I thought onclick event only executes scripts written in php or js. I will take a look. Commented Oct 2, 2017 at 8:34
  • @AnttiHaapala Is this task possible with Flask? Commented Oct 2, 2017 at 8:34
  • It should be possible with Flash, i would suggest Flask over jquery aswell Commented Oct 2, 2017 at 8:34

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I just started to learn flask. My flask app code so far is this: #!/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 not sure how to run the python function specifically on the input given in the textarea.
you should paste this code in your question, it'll be more easy to read and better place for it, i'll update my answer for you, but i just give you snippet so you can try and learn!
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.