lördag 9 juli 2022

Flask - Absolute basic client input and render

The following example shows how you can handle input with Flask and update pages, in this case with the user input sent back to the client. 

I'm making this as short as possible. 

Requirements: pip install Flask 

Implementation: 
1. In your project root dir create: A file named app.py 
2. In your project root dir create: A folder named "templates" and inside a file named "index.html" 


index.html 
<html lang="en"> 
  <head> 
  <title>Flask Basic Example</title>
  </head>  
  <body>    
  <h1>Flask Post: {{ text_to_show }}</h1>    
  <form action="/" method="POST">      
  <input type="text" name="content" />     
  <input type="submit" />    
  </form>  
  </body></html>

app.py
from flask import Flask, render_template, request
app = Flask(__name__)

@app.route("/", methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        user_input = request.form['content']
        return render_template("index.html", text_to_show=user_input)
    return render_template("index.html")

if __name__ == "__main__":
    app.run(debug=True, port=5000)

How it's used: Run app.py and go to http://127.0.0.1:5000 in your browser. Type some input, press send and the server will update the HTML with your input in a HTML paragraph. The Internet is full of extensive guides and tutorials. Sometimes you just want a quick example.

Inga kommentarer:

Skicka en kommentar