<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>html Archives - Creatronix</title>
	<atom:link href="https://creatronix.de/tag/html/feed/" rel="self" type="application/rss+xml" />
	<link>https://creatronix.de/tag/html/</link>
	<description>My adventures in code &#38; business</description>
	<lastBuildDate>Wed, 23 Mar 2022 07:28:59 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
	<item>
		<title>Bringing AJAX to Flask</title>
		<link>https://creatronix.de/bringing-ajax-to-flask/</link>
		
		<dc:creator><![CDATA[Jörn]]></dc:creator>
		<pubDate>Fri, 20 Jan 2017 12:29:47 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[filter]]></category>
		<category><![CDATA[Flask]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[wsgi]]></category>
		<guid isPermaLink="false">http://creatronix.de/?p=385</guid>

					<description><![CDATA[<p>Flask is a micro web framework which is really fun to use. With the following snippet You have a complete web app working within seconds. from flask import Flask # 1 app = Flask(__name__) # 2 @app.route('/') # 3 def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run() #4 All this snippet does is&#8230;</p>
<p>The post <a href="https://creatronix.de/bringing-ajax-to-flask/">Bringing AJAX to Flask</a> appeared first on <a href="https://creatronix.de">Creatronix</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Flask is a micro web framework which is really fun to use. With the following snippet You have a complete web app working within seconds.</p>
<pre>from flask import Flask # 1
 
app = Flask(__name__)   # 2

@app.route('/')         # 3
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()           #4</pre>
<p>All this snippet does is</p>
<ol>
<li>Importing the Flask module,</li>
<li>Creating the app,</li>
<li>Defining an so called endpoint and finally</li>
<li>Running the web app in a container.</li>
</ol>
<p>Flask brings its own WSGI server called &#8220;werkzeug&#8221;. Please use it just for development purposes. It is not suitable for live applications.</p>
<h2>Rendering a Template</h2>
<p>Because the days of writing HTML as strings in a servlet are over, Flask comes with a template language called &#8220;Jinja2&#8221;. We replace the line</p>
<pre>return 'Hello World!'</pre>
<p>with the render_template function and pass a template and the message into the function:</p>
<pre>from flask import render_template
... 
@app.route('/') 
def hello_world(): 
    hello_string = "Hello World"
    <strong>return render_template("index.html", 
                           hello_message=hello_string)</strong></pre>
<p>Jinja2 uses curly brackets to identify their template code blocks.</p>
<pre>&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;title&gt;Title&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
<strong>{{ hello_message }}</strong>
&lt;/body&gt;
&lt;/html&gt;</pre>
<pre>{{ hello_message }} # is equivalent to
{% print hello_message %}</pre>
<p>So if You want to show a list on your page containing your favorite fruits You can fetch a list of fruits from the server and let the template engine replace the markup with the data before handing the rendered page to the browser. We use a simple list for demonstration.</p>
<pre>@app.route('/static_item_list')
def static_item_list():
    fruits = ["Apple", "Banana", "Lemon"]
    return render_template("static_item_list.html", 
                           fruits=fruits)</pre>
<pre>&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Fruit&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
  {% for fruit in fruits %}
     &lt;tr&gt;
       &lt;td&gt;{{ fruit }}&lt;/td&gt;
      &lt;/tr&gt;
   {% endfor %}
   &lt;/tbody&gt;
&lt;/table&gt;</pre>
<h2>Bringing AJAX to Flask</h2>
<p><img fetchpriority="high" decoding="async" class="alignnone size-full wp-image-4475" src="https://creatronix.de/wp-content/uploads/2017/01/sequence_chart_ajax.png" alt="" width="364" height="365" srcset="https://creatronix.de/wp-content/uploads/2017/01/sequence_chart_ajax.png 364w, https://creatronix.de/wp-content/uploads/2017/01/sequence_chart_ajax-300x300.png 300w, https://creatronix.de/wp-content/uploads/2017/01/sequence_chart_ajax-150x150.png 150w, https://creatronix.de/wp-content/uploads/2017/01/sequence_chart_ajax-100x100.png 100w" sizes="(max-width: 364px) 100vw, 364px" /><br />
When we wanted to filter a list back in the old days, we had to do a complete roundtrip by sending a POST with parameters to the server, waiting for the response and rendering a new page. Ugh! In Flask it looks like this:</p>
<pre>&lt;<strong>form</strong> <strong>method="POST"</strong>&gt;
&lt;table&gt;
    &lt;thead&gt;
        &lt;tr&gt;
            &lt;th&gt;Fruit&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;
                &lt;input <strong>name="filter"</strong>/&gt;
                <strong>&lt;button&gt;Search&lt;/button&gt;</strong>
            &lt;/td&gt;
        &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;
        {% for fruit in fruits %}
            &lt;tr&gt;
                &lt;td&gt;{{ fruit }}&lt;/td&gt;
            &lt;/tr&gt;
        {% endfor %}
    &lt;/tbody&gt;
&lt;/table&gt;
&lt;/form&gt;</pre>
<pre>@app.route('/item_list_with_filter', methods=["GET", "POST"])
def item_list_with_filter():
    fruits = ["Apple", "Banana", "Lemon"]
    
    if "filter" in request.form:
        fruit_filter_value = request.form["filter"]
    else:
        fruit_filter_value = ""

    filtered_items = []
    for fruit in fruits:
        if fruit_filter_value.lower() in fruit.lower():
            filtered_items.append(fruit)

    return render_template("item_list_with_filter.html",
                           fruits=filtered_items)</pre>
<p>Nowadays You can just refresh those parts of a site where the data should be updated. I will demonstrate this with some jQuery functionality, but You can do it as well in plain old vanilla JavaScript.</p>
<p>This is the udpated HTML page. Please note that the table body is empty and does not contain template language code.</p>
<pre>&lt;table id="items"&gt;
    &lt;thead&gt;
        &lt;tr&gt;
            &lt;th&gt;Fruit&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;
                &lt;input id="filter"/&gt;
            &lt;/td&gt;
        &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;&lt;/tbody&gt;
&lt;/table&gt;</pre>
<p>First of all we bind a keyup event to the filter input. To ensure that the complete page is already loaded, we do it in the document-ready function:</p>
<pre>$(document).ready(function(){
...
    $("#filter").keyup(get_table_data); 
...
});</pre>
<p>To fetch data from the server we use the getJSON-function.</p>
<pre class="result notranslate"><i>$</i>.getJSON( url, [data], [callback] )</pre>
<p>This function is a shortcut for</p>
<pre>$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});
</pre>
<p>As URL we have to provide an endpoint that accepts GET requests, as data we give the value from the input field and last but not least as callback a function that will use the data from the response to update the table.</p>
<pre>function get_table_data(){
    $.getJSON('/_items', {
        filter: $("#filter").val()
        }, function(data){update_table.call(this, data)}
    )
}</pre>
<p>Let&#8217;s have a look at the before mentioned endpoint:</p>
<pre>@app.route('/_items')
def items():
    <strong>filter_value = request.args.get('filter', "", type=str)</strong>
    fruits = ["Apple", "Banana", "Lemon"]

    filtered_items = []
    for fruit in fruits:
        if filter_value.lower() in fruit.lower():
            filtered_items.append(fruit)

    <strong>return jsonify(fruits=filtered_items)</strong></pre>
<p>There are two interesting parts here: To get the arguments from the request we use</p>
<pre>request.args.get()</pre>
<p>The get method takes the argument name, a default value and a type. Instead of returning a rendered template we use the method</p>
<pre>jsonify<strong>()</strong></pre>
<p>That&#8217;s all it takes to get JSON data from a Flask application. The missing piece is the function which alters the content on the client side after receiving the data. It looks like this</p>
<pre>function update_table (data) {
    var $tbody = $("#items").find("tbody");
    $tbody.empty();
    var rows = data.fruits.length;
    for (var i = 0; i &lt; rows; i++) {
        var row = "&lt;tr&gt;&lt;td&gt;" + data.fruits[i] + "&lt;/td&gt;&lt;/tr&gt;";
        $tbody.append(row);
    }
}</pre>
<p>This function clears the body of the table via empty(), iterates over the data and appends the new rows to the table body.  and Bob&#8217;s your uncle!</p>
<p>The post <a href="https://creatronix.de/bringing-ajax-to-flask/">Bringing AJAX to Flask</a> appeared first on <a href="https://creatronix.de">Creatronix</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
