Python Forum

Full Version: Connecting python script into HTML with flask
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I'm currently working on a project and I need some help with flask since I'm a bit new to flask I dont know how to connect my python script into html.

Say, I have input_data.html and input_data.py how do I connect them with flask? When user input the sentence and click the button, my script (input_data.py) will process the input and display the output on text area below.

[Image: unknown.png]

Any help or guidance would be appreciated.
There are couple or more ways do do this.
when push Submit button on server request.form will get the text from input field.
Can send text back(redirect) to same page.
A other way is send back to same page with Ajax(that dos not reload the page).
A basic example.
app.py:
from flask import Flask, render_template, request, redirect, url_for
 
app = Flask(__name__)
@app.route('/')
def index():
   return render_template("index.html")

@app.route('/text', methods=['GET', 'POST'])
def text(comments=[]):
    if request.method == "GET":
        return render_template("index.html", comments=comments)    
    comments.append(request.form["text_input"])  
    return redirect(url_for('text'))

if __name__ == '__main__':
   app.run(debug=True)
index.html:
<!doctype html>
<html>
<head>
  <title>Some title</title>
  <link rel=stylesheet type=text/css href="{{ url_for('static', filename='css/style.css') }}" />
</head>
<body>
  <h2>Form</h2>
  <form action="/text" method="post">
    Input text:<br>
    <input type="text" name="text_input" value="">
    <br>
    <input type="submit" value="Submit">
  </form>
  <div id='foo'>
    <br>
    {% for comment in comments %}
    <div class="row">
      {{ comment }} 
    </div>
    {% endfor %}
  </div>
</body>
</html>
So to server and send back to view.
A common way is to use jinja2 build into Flask to sent stuff to html {{ comment }}.
[Image: RmWrDq.jpg]