avatarMaxence LQ

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

7052

Abstract

<b>browser will understand it</b>.</p><p id="480c">Let’s improve our endpoint to send back a simple HTML message:</p><div id="66d7"><pre><span class="hljs-variable">@web_app</span>.route(<span class="hljs-string">"/"</span>) <span class="hljs-keyword">def</span> <span class="hljs-title function_">helloworld</span>(): <span class="hljs-keyword">return</span> <span class="hljs-string">"<p>I'm <strong>alive</strong>!</p>"</span></pre></div><p id="0363">Now you can restart your program and reload the page, and you should see the word “alive” in bold.</p><p id="02b0">That’s cool, our web app now returns HTML!</p><h1 id="717d">Debug Mode</h1><p id="1299">Something quite annoying when working on your app is to have to restart the program each time you make any change. Luckily, as always with Python, things are well made. <i>Flask</i> has a debug mode, that <b>allows changes to happen without restarting your program</b>. Let’s enable it:</p><p id="d945">It’s not complicated, just add a keyword argument to the <code>run</code> method:</p><div id="535c"><pre>web_app.<span class="hljs-built_in">run</span>(<span class="hljs-attribute">debug</span>=<span class="hljs-literal">True</span>)</pre></div><p id="2452">And now, you can restart your app (one last time):</p><div id="13e4"><pre>* Serving Flask app <span class="hljs-string">'a-super-name'</span> (lazy loading)

  • Environment: production <span class="hljs-built_in">WARNING</span>: This <span class="hljs-keyword">is</span> a development <span class="hljs-keyword">server</span>. <span class="hljs-keyword">Do</span> <span class="hljs-keyword">not</span> use it <span class="hljs-keyword">in</span> a production deployment. Use a production WSGI <span class="hljs-keyword">server</span> <span class="hljs-keyword">instead</span>.
  • <span class="hljs-keyword">Debug</span> mode: <span class="hljs-keyword">on</span>
  • Running <span class="hljs-keyword">on</span> http://<span class="hljs-number">127.0</span><span class="hljs-number">.0</span><span class="hljs-number">.1</span>:<span class="hljs-number">5000</span>/ (Press CTRL+C <span class="hljs-keyword">to</span> quit)
  • Restarting <span class="hljs-keyword">with</span> stat
  • Debugger <span class="hljs-keyword">is</span> active!
  • Debugger PIN: <span class="hljs-number">775</span><span class="hljs-number">-216</span><span class="hljs-number">-152</span></pre></div><p id="c29d">And as you can see, the app is now in debug mode.</p><p id="837d">Now, let’s see what happens if you make a change to the file:</p><div id="4c1a"><pre><span class="hljs-comment">* Detected change in '/path/app.py', reloading</span> <span class="hljs-comment">* Restarting with stat</span> <span class="hljs-comment">* Debugger is active!</span> <span class="hljs-comment">* Debugger PIN: 775-216-152</span></pre></div><p id="2bb3">As you can see, the app reloads by itself, which is frankly really useful.</p><h1 id="f2ae">HTML Templates</h1><p id="9b69">The last thing I want to show you today, as it’s really practical, is templates. HTML <b>templates are <i>Flask</i> must-knows</b>.</p><h2 id="29f8">HTML in a Separated File</h2><p id="a46b">We saw previously how to return HTML, just as string, but let’s be honest, it’s not practical at all, who would write HTML in a string inside of a Python file??</p><p id="e0c8">No, it’s a lot better to write your HTML in a <code>.html</code> file, and templates are made to do that, and actually, they can do more than that.</p><p id="46d5" type="7">It’s always better to separate your code into different files, particularly to separate mark up from code.</p><p id="b07f">We’ll focus on the Python part, that is to say, loading the template and returning it, then I will tell you more about templates.</p><p id="c19e">Before everything, to load a template, you need to import <code>render_template</code> from <i>Flask</i>:</p><div id="ca8e"><pre><span class="hljs-keyword">from</span> flask <span class="hljs-keyword">import</span> Flask, render_template</pre></div><p id="1b47">Now, in our endpoint, we can use that function to load an HTML template:</p><div id="0a0b"><pre><span class="hljs-variable">@web_app</span>.route(<span class="hljs-string">"/"</span>) <span class="hljs-keyword">def</span> <span class="hljs-title function_">helloworld</span>(): <span class="hljs-keyword">return</span> render_template(<span class="hljs-string">"first-template.html"</span>)</pre></div><p id="38e6">You can choose any other name for your HTML file.</p><h2 id="c3a0">Writing Templates</h2><p id="3362">Before going any further, we need a file, so let’s create it (the name must match the one you placed in your function call).</p><p id="4767">This file must be placed in a <code>templates/</code> folder. (<b><i>Flask</i> automatically looks for the template here</b>. That can be changed, but that's for another article.)</p><p id="f934">If you’re familiar with HTML, you know every HTML file must start by specifying the doctype, here is a pattern you can <b>copy-paste</b> before continuing:</p><div id="659c"><pre><span class="hljs-meta"><!doctype <span class="hljs-keyword">html</span>></span> <span class="hljs-tag"><<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>></span> <span class="hljs-tag"><<span class="hljs-name">head</span>></span> <span class="hljs-tag"><<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"utf-8"</span>></span> <span class="hljs-tag"><<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1"</span>></span> <span class="hljs-tag"><<span class="hljs-name">title</span>></span>A simple template<span class="hljs-tag"></<span class="hljs-name">title</span>></span> <span class="hljs-tag"></<span class="hljs-name">head</span>></span> <span class="hljs-tag"><<span class="hljs-name">body</span>></span> <span class="hljs-comment"><!-- Content --></span> <span class="hljs-tag"></<span class="hljs-name">body</span>></span> <span class="hljs-tag"></<span class="hljs-name">html</span>></span></pre></div><p id="18a2">As you can see, for now, <b>it’s just pure HTML</b>, we’ll see in a minute how to add more functionality to it.</p><p id="db2d">Before that, let’s add some content to the file so that we can check everything is working well:</p><div id="e237"><pre><span class="hljs-tag"><<span class="hljs-name">body</span>></span> <span class="hljs-tag"><<span class="hljs-name">p</span>></span>I'm alive as a <span class="hljs-tag"><<span class="hljs-name">strong</span>></span>template<span class="hljs-tag"></<span class="hljs-name">strong</span>></span>!<span class="hljs-tag"></<span class="hljs-name">p</span>></span> <span class="hljs-tag"></<s

Options

pan class="hljs-name">body</span>></span></pre></div><p id="ae77">Again, we’re not focusing on HTML here, I just copy-pasted the HTML we used previously.</p><p id="6491">Now, save your file if it’s not already done, and go to your app, you should see this (or any content you’ve put in the HTML’s body):</p><div id="fdff"><pre>I'm alive <span class="hljs-keyword">as</span> a <span class="hljs-keyword">template</span>!</pre></div><h2 id="191f">Extended Functionality</h2><p id="5d12"><i>Flask</i> uses the <a href="https://jinja.palletsprojects.com/en/3.0.x/">Jinja template</a>, let’s see how to use this tool to your advantage.</p><p id="5a47">First, it allows you to <b>create one “base” HTML template</b>, and then to be able to write quickly new pages to your web app. Here is how it works:</p><p id="072b">In your base template, you have to include <b>blocks</b>. Don’t worry, it’s not complicated.</p><p id="9bb1">Imagine you want your base template to be changeable in two ways, you want to be able to change the title for each page, and the content of the body. Your <code>base-template.html</code> should look like this:</p><div id="116a"><pre><span class="language-xml"><span class="hljs-meta"><!doctype <span class="hljs-keyword">html</span>></span> <span class="hljs-tag"><<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>></span> <span class="hljs-tag"><<span class="hljs-name">head</span>></span> <span class="hljs-tag"><<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"utf-8"</span>></span> <span class="hljs-tag"><<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1"</span>></span> <span class="hljs-tag"><<span class="hljs-name">title</span>></span></span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">block</span></span> title %}</span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">endblock</span></span> %}</span><span class="language-xml"><span class="hljs-tag"></<span class="hljs-name">title</span>></span> <span class="hljs-tag"></<span class="hljs-name">head</span>></span> <span class="hljs-tag"><<span class="hljs-name">body</span>></span> </span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">block</span></span> content %}</span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">endblock</span></span> %}</span><span class="language-xml"> <span class="hljs-tag"></<span class="hljs-name">body</span>></span> <span class="hljs-tag"></<span class="hljs-name">html</span>></span></span></pre></div><p id="b8ee">You can see these weird <code>{% ... %}</code> statements, well, these are the so-called blocks. It just means that when you will "extend" (we'll see that in a minute) this template, <b>you will overwrite this block</b>, that is to say, give it a new value.</p><h2 id="b4f0">Extend the Template</h2><p id="da57">Now let’s see how to extend a template. You need a second file, let’s call it, <code>extended-template.html</code> .</p><p id="985e">The first thing to write is what template are we extending:</p><div id="3d9a"><pre><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">extends</span></span> 'first-template.html' %}</span></pre></div><p id="24b3">Then we can give a value to each block. The syntax is the same as in the base.</p><p id="d8b2">For the title block:</p><div id="4528"><pre><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">block</span></span> title %}</span><span class="language-xml"> An extended template </span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">endblock</span></span> %}</span></pre></div><p id="8b03">And for the content:</p><div id="f8d2"><pre><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">block</span></span> content %}</span><span class="language-xml"> <span class="hljs-tag"><<span class="hljs-name">p</span>></span>I'm alive as an <span class="hljs-tag"><<span class="hljs-name">strong</span>></span>extended<span class="hljs-tag"></<span class="hljs-name">strong</span>></span> template!<span class="hljs-tag"></<span class="hljs-name">p</span>></span> </span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">endblock</span></span> %}</span></pre></div><p id="005d">At this point, your extended file should look like that:</p><div id="51c5"><pre><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">extends</span></span> 'first-template.html' %}</span></pre></div><div id="413c"><pre><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">block</span></span> title %}</span><span class="language-xml"> An extended template </span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">endblock</span></span> %}</span></pre></div><div id="808f"><pre><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">block</span></span> content %}</span><span class="language-xml"> <span class="hljs-tag"><<span class="hljs-name">p</span>></span>I'm alive as an <span class="hljs-tag"><<span class="hljs-name">strong</span>></span>extended<span class="hljs-tag"></<span class="hljs-name">strong</span>></span> template!<span class="hljs-tag"></<span class="hljs-name">p</span>></span> </span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">endblock</span></span> %}</span></pre></div><p id="7ab9">The last thing we have to do is change which template we load in our Python file. Instead of loading <code>first-template.html</code>, we want to load <code>extended-template.html</code> :</p><div id="ad0f"><pre><span class="hljs-variable">return</span> <span class="hljs-function"><span class="hljs-title">render_template</span>(<span class="hljs-string">"extended-template.html"</span>)</span></pre></div><p id="ca90">You can now reload your web app (by saving the Python file).</p><p id="6dc4">And you should see something similar to this:</p><div id="91f8"><pre>I'm alive <span class="hljs-keyword">as</span> an extended <span class="hljs-keyword">template</span>!</pre></div><p id="d7ed">And I think I’ll just wrap things up there.</p><p id="624c">Thanks for reading, and see you soon!</p><p id="49ee"><a href="https://medium.com/@maxence.lq/membership"><i>Become a medium member</i></a><i> to read all my next stories as well as others’!</i></p><p id="0c03"><i>See you in the next story 👋</i></p><p id="a37c"><i>More content at <a href="http://plainenglish.io/">plainenglish.io</a></i></p></article></body>

How to Build Your First Web App in Less Than 10 minutes

The basics of the Flask framework with Python.

Python is a trending language for building web apps thanks to frameworks like Django and Flask that are widely used across the web dev community.

For today’s story, I chose Flask over Django since it’s a more beginner-friendly framework, it’s lightweight, and will require less setup time.

Flask is a more lightweight and beginner-friendly framework.

But without further talk let’s jump into it.

Setup the framework

Install Flask

The first thing you wanna do is install Flask on your local machine or your server.

To do that, nothing complicated thanks to the PIP tool :

For Linux :

pip3 install flask

Or for windows :

pip install flask

Create the App Object

Once this is installed, create a Python file.

Name the files mindfully since programming projects tend to just become a huge ununderstandable mess over time.

Then, import the Flask class from the flask module.

from flask import Flask

The Flask class is the main class of your application. You need to instantiate it to have your web app.

web_app = Flask("a-super-name")

You can give any name you want to your web app, it won’t affect today’s tutorial.

Your First Endpoint

Once the app is created, you need to define what we call endpoints. An endpoint is just an URL that will be accessible from your app.

In Flask, endpoints are just defined as functions (with a decorator).

Let’s create our first endpoint, something like a HelloWorld endpoint. The first thing to do is to create a function:

def helloworld():
	pass

To turn our function into an endpoint, we need to decorate it (decorators are just a way to “upgrade” functions):

@web_app.route("/")
def helloworld():
	pass

As you can see, you have to pass arguments to the decorator to define your endpoint, the only mandatory parameter is the endpoint’s URL, here a slash (alone) just means no specific address.

Okay, we have our endpoint, but for now, it does absolutely nothing. Let’s give it life, by adding a return value:

@web_app.route("/")
def helloworld():
	return "I'm alive!"

And there you have, a complete working endpoint.

The last step is to run the web app:

web_app.run()

At this point, your file should look something like that:

from flask import Flask
web_app = Flask("a-super-name")
@web_app.route("/")
def helloworld():
	return "I'm alive!"
web_app.run()

You can now run your Python file:

python3 webapp.py

And you should see a message that looks like that:

* Serving Flask app 'a-super-name' (lazy loading)
* Environment: production
  WARNING: This is a development server. Do not use it in a production deployment.
  Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

As you can see at the bottom line, the web app is running on http://127.0.0.1:5000 . You might see a different address, but that doesn't matter, just copy and paste this URL in a web browser, and you should see something like that:

I'm alive!

And that’s it, you have your web app ready for production… Well, no, not exactly.

Yes Python is awesome, and yes Flask is a very well-made framework, but don’t you believe you can have a production-ready web app in 6 lines of code!

Let’s go a bit further into our exploration of Flask.

Return HTML

So far we just sent a text (string) as a response, but did you ever see a web page composed of text?

No, of course not, web pages are HTML most of the time (if not always).

I won’t explain to you how does HTML work here, and I will assume you got some basic knowledge.

Your web browser (the one that requests the webpage) expects HTML, because of that, if you send HTML as text, the browser will understand it.

Let’s improve our endpoint to send back a simple HTML message:

@web_app.route("/")
def helloworld():
	return "<p>I'm <strong>alive</strong>!</p>"

Now you can restart your program and reload the page, and you should see the word “alive” in bold.

That’s cool, our web app now returns HTML!

Debug Mode

Something quite annoying when working on your app is to have to restart the program each time you make any change. Luckily, as always with Python, things are well made. Flask has a debug mode, that allows changes to happen without restarting your program. Let’s enable it:

It’s not complicated, just add a keyword argument to the run method:

web_app.run(debug=True)

And now, you can restart your app (one last time):

* Serving Flask app 'a-super-name' (lazy loading)
* Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 775-216-152

And as you can see, the app is now in debug mode.

Now, let’s see what happens if you make a change to the file:

* Detected change in '/path/app.py', reloading
* Restarting with stat
* Debugger is active!
* Debugger PIN: 775-216-152

As you can see, the app reloads by itself, which is frankly really useful.

HTML Templates

The last thing I want to show you today, as it’s really practical, is templates. HTML templates are Flask must-knows.

HTML in a Separated File

We saw previously how to return HTML, just as string, but let’s be honest, it’s not practical at all, who would write HTML in a string inside of a Python file??

No, it’s a lot better to write your HTML in a .html file, and templates are made to do that, and actually, they can do more than that.

It’s always better to separate your code into different files, particularly to separate mark up from code.

We’ll focus on the Python part, that is to say, loading the template and returning it, then I will tell you more about templates.

Before everything, to load a template, you need to import render_template from Flask:

from flask import Flask, render_template

Now, in our endpoint, we can use that function to load an HTML template:

@web_app.route("/")
def helloworld():
    return render_template("first-template.html")

You can choose any other name for your HTML file.

Writing Templates

Before going any further, we need a file, so let’s create it (the name must match the one you placed in your function call).

This file must be placed in a templates/ folder. (Flask automatically looks for the template here. That can be changed, but that's for another article.)

If you’re familiar with HTML, you know every HTML file must start by specifying the doctype, here is a pattern you can copy-paste before continuing:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>A simple template</title>
</head>
<body>
    <!-- Content -->
</body>
</html>

As you can see, for now, it’s just pure HTML, we’ll see in a minute how to add more functionality to it.

Before that, let’s add some content to the file so that we can check everything is working well:

<body>
    <p>I'm alive as a <strong>template</strong>!</p>
</body>

Again, we’re not focusing on HTML here, I just copy-pasted the HTML we used previously.

Now, save your file if it’s not already done, and go to your app, you should see this (or any content you’ve put in the HTML’s body):

I'm alive as a template!

Extended Functionality

Flask uses the Jinja template, let’s see how to use this tool to your advantage.

First, it allows you to create one “base” HTML template, and then to be able to write quickly new pages to your web app. Here is how it works:

In your base template, you have to include blocks. Don’t worry, it’s not complicated.

Imagine you want your base template to be changeable in two ways, you want to be able to change the title for each page, and the content of the body. Your base-template.html should look like this:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{% block title %}{% endblock %}</title>
</head>
<body>
    {% block content %}{% endblock %}
</body>
</html>

You can see these weird {% ... %} statements, well, these are the so-called blocks. It just means that when you will "extend" (we'll see that in a minute) this template, you will overwrite this block, that is to say, give it a new value.

Extend the Template

Now let’s see how to extend a template. You need a second file, let’s call it, extended-template.html .

The first thing to write is what template are we extending:

{% extends 'first-template.html' %}

Then we can give a value to each block. The syntax is the same as in the base.

For the title block:

{% block title %} An extended template {% endblock %}

And for the content:

{% block content %}
	<p>I'm alive as an <strong>extended</strong> template!</p>
{% endblock %}

At this point, your extended file should look like that:

{% extends 'first-template.html' %}
{% block title %} An extended template {% endblock %}
{% block content %}
	<p>I'm alive as an <strong>extended</strong> template!</p>
{% endblock %}

The last thing we have to do is change which template we load in our Python file. Instead of loading first-template.html, we want to load extended-template.html :

return render_template("extended-template.html")

You can now reload your web app (by saving the Python file).

And you should see something similar to this:

I'm alive as an extended template!

And I think I’ll just wrap things up there.

Thanks for reading, and see you soon!

Become a medium member to read all my next stories as well as others’!

See you in the next story 👋

More content at plainenglish.io

Programming
Web Development
Software Development
Python
Python3
Recommended from ReadMedium