Flask is one of many web frameworks available for Python. It is considered a micro-framework, based on doing one thing at a time and doing it well.
As described in its documentation, the micro in micro-framework implies that Flask aims to maintain its lightweight simplicity. The true power of Flask is its ability to be flexible.
Flask uses its extensible web framework to enable the flexible development of web applications using various web development libraries and tools. This allows more experienced developers the freedom to plug and play with the libraries and databases they are comfortable with.
Unlike other web-frameworks like Django, you’re not stuck with what the framework forces you to use. Instead, you can pivot into technical components you’re comfortable with.
In this piece, we delve into developing your first Flask web pages.
We will create:
- Your first Flask program: Hello World!
- How to get user input in your website with Flask.
- Using HTML to modify the web page.
Just to quickly get our feet wet, we are going to create the classic “Hello World” web page. This program will also help you check that you have properly installed Flask.
It’s pretty amazing but the Hello World! program in Flask is seven code lines long. Those seven lines of code are sufficient to create a simple web page.
So, let’s get started.
The code, once all written out, will look like this:
# helloTest.py # at the end point / call method hello which returns "hello world" from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return 'Hello World!' if __name__ == '__main__': app.run(host='0.0.0.0')
Going over the important lines, let’s discuss what each one does.
app = Flask(__name__)
This line creates a new app, which we need for the running process. It also handles all the various task required for the website. name is an automatically defined Python variable, required for making Flask apps.
@app.route(“/”) # at the endpoint /
The syntax above is known as a “decorator”. In Flask, the line added on top of a function description converts it to a “route”. We will go into more detail about what this means shortly.
def hello(): # call method hello return “Hello World!”
These lines define a function that takes zero parameters and returns the Hello World! string.
if __name__ == “__main__”: # on running python app.py app.run() # run the flask app
Line 9 is an if command in Python that implies “run only if the whole code is executed”.
The other Python variable, name, remains as explained above. app.run() mostly runs the variables in line 3 and also on the localhost.
Once you have finished developing the code you can test it by running it on the command line. You can run the command based on your file name.
For example, if your file name is helloTest.py, you can run this by typing:
This will then kick off your “Server” and set your website running. You can see this page by going to http://0.0.0.0:5000/ or just localhost:5000.
The output on the webpage will look like this:
Congrats! You have completed your first web page.
Defining what the route (line 6) requires is important to understand as you start to build your app. You are allowed to establish new routes (like the example below) to represent different URLs for your websites.
Before moving on to discussing how to pass inputs to your code, let’s first discuss how you could add a new route.
In the code below, you will notice we have added a new function with the app.route(“/John”). This has now added a new endpoint that can be located at localhost:5000/John.
Try running it and see what happens.
#Using More Routes from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" @app.route("/John") def John(): return "Hello John!" if __name__ == "__main__": app.run(debug=True)
Your web page should look like this:
You have now created the Hello World! page on Flask. You have successfully achieved an important step — creating a static website page.
But after creating a static page, what’s next?
The next stage is getting dynamic data (eventually, we will turn this into user inputs). In this case, this is making the routes take in arguments so that you can have a more dynamic website.
The user inputs we would consider here is accepting a variety of names. To achieve this, the routes are defined with a variable below:
@app.route("/Welcome/<name>") # at the endpoint /<name> def Welcome_name(name): # call method Welcome_name return "Welcome" + name + "!" # which returns "Welcome + name + !
For the code above, the serves as a placeholder for the URL route. It merely implies that any name added to the URL will automatically be placed into the Welcome name function.
Here is one way you could use to combine this new concept with your old Hello World file:
from flask import Flask app = Flask(__name__) @app.route("/") def hello (): return 'Open a new tab and enter /Welcome/name for URL' @app.route('/Welcome/<name>') def Welcome_name(name): return 'Welcome ' + name + '!' if __name__ == '__main__': app.run(host='0.0.0.0')
Using the new route, entering localhost:5000/Welcome/Benny into your browser would lead to:
The browser asks the server (your computer in this scenario) for a suitable response to the inputted URL.
The server recognizes the request alongside the URL.
The server responds with the corresponding function.
The server calls and provides the correct variables and output. (The function Welcome_name(), with value Benny replacing the name variable)
The server proceeds and displays the “Welcome Benny!” string, which is the correct output from Welcome_name(“Benny”).
Now you are passing dynamic information to your site.
If you have made it to this point, everything looks good! You have learned how to use Python functions for creating a website interface.
Now, to improve the overall appeal of your website page(s), HTML is employed.
One crucial detail to note about HTML is that it can serve as a markup language that permits the specific alteration (in terms of appearance) to a selected website page.
Getting Started With HTML in Flask
To get started, let’s make a page with HTML for the factors of 5. The code would look similar to what we have below.
<h1>The factors of 5 are:</h1> <ul> <li>1</li> <li>5</li> </ul>
This example is simple but it will help you get an understanding of how to manipulate HTML with Flask.
The next step in using HTML is how to process the data from static to something dynamic. To make the page return factors for any number is doable.
With the use of a function, we can create the HTML string that accepts numbers and provides output. The necessary code is provided below.
from flask import Flask app = Flask(__name__) def factors(num): return [x for x in range (1, num+1) if num%x==0] @app.route('/') def home(): return '<a href="/factor_raw/100"> click here for an example</a>' @app.route('/factor_raw/<int:n>') def factors_display_raw_html(n): list_factor = factors(int(n)) # adding "n" and placed at the top html = "<h1> Factors of "+str(n)+" are</h1>"+"\n"+"<ul>" # make a <li> item for every output (factor) for f in list_factor: html += "<li>"+str(f)+"</li>"+"\n" html += "</ul> </body>" # closes tag at the end return html if __name__ == '__main__': app.run(host='0.0.0.0')
By running this code, we get an output that generates the factors of a selected number in HTML. But we could all agree; it is not so easy to understand.
Well, there is a better approach and it is done with HTML templates.
So, in the case below, we provided the variable of 50 and thus get the factors of 50.
Flask is a great, simple framework that can help you create a website. This intro worked you through the Hello World! program which is static, to a more dynamic web page that accepts user inputs.
As a popular web framework, Flask also allows for the integration of plenty of other libraries, databases, etc. There are lots of features and vast extensions available.
We will cover methods for using HTML templates and progress tracking in part 2, so get ready and keep practicing!
We hope you enjoyed this post and look forward to hearing about your experiences!
If you are interested in more videos and posts about data, software and tech, then read the below!
Passing The System Design Interview For Software Engineers
4 Simple Python Ideas to Automate Your Workflow
How Algorithms Can Become Unethical and Biased
Data Science Consulting; How To Get Clients
How To Develop Robust Algorithms
4 Must Have Skills For Data Scientists
SQL Best Practices — Designing An ETL Video