On this article, we’ll introduce Flask, a well-liked microframework for Python that gives an alternative choice to the large that’s Django.
Flask is designed to be light-weight and versatile, permitting builders to create net apps shortly and simply. On this article, we’ll cowl what Flask is, its key options, the advantages of its easy API, its flexibility in supporting third-party extensions, the most typical Flask extensions, and when is and isn’t an excellent time to make use of Flask.
What Is Flask?
Flask is a micro net framework written in Python that’s used for growing net purposes. It’s constructed on a easy philosophy of conserving issues easy and light-weight, giving builders solely an important instruments wanted to construct net apps with out pointless complexity.
It’s constructed on high of the Werkzeug WSGI toolkit, which supplies net server performance wanted for dealing with requests and responses, and the Jinja2 templating engine, which provides Flask the power to deal with HTML templates, permitting builders to create dynamic net purposes.
Listed here are a number of the key options of Flask that make it such a terrific framework to work with:
- It has a easy API for creating net routes and dealing with requests.
- The Jinja templating engine affords help for HTML templates, permitting builders to create net pages simply.
- It’s extremely extendable, as a result of its help for third-party extensions, so a developer can set up extensions relying on their undertaking wants.
- It comes bundled with a improvement server that makes it simple to check and debug apps.
Total, Flask supplies a robust, versatile, but easy framework for constructing net purposes. It’s a good selection for each new and skilled net builders, and is without doubt one of the hottest net frameworks within the Python net improvement ecosystem.
Benefits of Flask
Let’s now take a extra detailed have a look at a number of the benefits of utilizing Flask in improvement.
Simplicity. Flask’s design philosophy emphasizes simplicity, which makes it simple for builders at any stage to know and use. This additionally implies that builders have a really minimal studying curve, since they solely must study a couple of ideas and APIs to get began constructing net purposes.
Flexibility. The micro nature of Flask — offering solely the core options of an internet framework — provides builders the ability to customise and lengthen it to go well with their necessities utilizing Flask extensions or third-party libraries.
Documentation. The Flask documentation could be very complete, with good protection of primary to superior matters, making it very simple for builders to learn to use the framework.
Compatibility. Flask is appropriate with a variety of Python variations, which makes it simple to make use of with current Python codebases. It additionally has help for a number of net servers, which makes it simple to deploy it on quite a lot of internet hosting platforms.
Fast improvement. Flask’s simplicity and adaptability scale back the boilerplate wanted to arrange an software, permitting builders to get began shortly.
Across the Internet, Flask is utilized in a number of fascinating methods. A couple of notable examples are:
- PgAdmin. The Postgres admin interface runs on a Flask occasion, giving builders an interface the place they’ll handle their Postgres databases.
- Twilio. It is a communication platform that makes use of Flask in a number of of its APIs.
- Pinterest. This photo-sharing app makes use of Flask within the net improvement stack, permitting its staff to create some customized options and integrations simply.
When to Use Flask
Flask’s simplicity and ease of use make it a wonderful selection for a variety of net initiatives:
- Prototyping. Its ease of use and adaptability make it a wonderful selection for shortly creating prototypes permitting builders to construct and take a look at new options quick.
- Creating RESTful APIs. Its personal easy API makes it simple to create and deal with HTTP requests.
- Ecommerce apps. It really works nicely for constructing on-line marketplaces and ecommerce platforms.
- Finance. It’s helpful for constructing monetary purposes, with account administration, transaction processing, and funding monitoring.
- AI. It affords a helpful and easy technique to construct and deploy AI coaching fashions.
When Not To Use Flask
Whereas Flask is a good framework and has an a variety of benefits and nice options, there are conditions these options work towards it. Let’s discover a number of the initiatives that go well with different forms of frameworks higher.
Initiatives that require built-in performance. Being a microframework, Flask solely supplies the core bits wanted to create an internet software. If a undertaking requires, say, an admin interface, authentication, or an ORM, then Django is a greater possibility.
Initiatives with strict safety necessities. As Flask is a versatile framework, now we have to depend on third-party extensions to implement some stage of safety in our apps. Whereas this definitely works, it’s higher to depend on a extra battle-tested framework that takes a safer method, similar to Twister or Twisted.
Initiatives that implement some coding customary. Attributable to Flask’s flexibility, growing purposes on it leaves builders to make apps in any means they see match. Nonetheless, frameworks like Django be certain that builders observe a specific conference, which means that builders can transfer from one undertaking to different simply.
Setting Up a Flask Improvement Setting
Let’s now have a look at the right way to get began with Flask, from establishing the event atmosphere, to set up, and at last spinning up a minimal software.
Conditions
Python must be put in on the event machine. Listed here are instructions for that (though we may already have it installed).
Create a Digital Setting
A digital atmosphere is an remoted Python atmosphere the place we are able to set up packages for a given undertaking with out affecting the worldwide Python set up. (Right here’s additional dialogue about why virtual environments are useful.) There are totally different packages for creating digital environments in Python, similar to virtualenv, venv, or Conda.
On this article, we’ll use virtualenv
. We are able to set up it with the next command:
pip set up virtualenv
As soon as virtualenv
has been put in, we are able to create a listing the place our Flask software will reside. We are able to name the listing no matter we would like — apart from Flask
, as that may trigger conflicts. We’ll name ours flask_intro
:
mkdir flask_intro
Subsequent, become that listing in order that we are able to begin utilizing it:
cd flask_intro
In that listing, let’s now create our digital atmosphere, utilizing the next command:
virtualenv myenv
The command above creates a digital atmosphere and calls it myenv
. Let’s activate it in order that we are able to set up Flask in it. To activate the digital atmosphere on Linux or macOS, use the next command:
. myenv/bin/activate
On Home windows, use this command:
. myenvScriptsactivate
As soon as our digital atmosphere has been activated, it’ll present the title of the digital atmosphere on the shell immediate, just like the output under:
(myenv)/~(path to your undertaking listing)$
Inside our activated digital atmosphere, we are able to go forward and set up Flask, utilizing the next command:
pip set up Flask
As soon as Flask finishes putting in, let’s go forward and create a minimal software. We’ll create a module that may maintain our Flask software. For simplicity’s sake, let’s name it howdy.py
. On Linux or macOS we are able to use the next command to create the file in our flask_intro
listing:
contact howdy.py
The command above creates a file named howdy.py
. We may additionally use a improvement atmosphere to create the file. As soon as the file has been created, put the under code in it and reserve it:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Whats up, World!'
Within the code above, we import the Flask
class from the flask
module, then create an occasion of Flask
that we name app
and move the __name__
variable.
Then now we have the route decorator @app.route(“”)
, which implies that the hello_world()
perform can be triggered when somebody visits the basis route of our software as soon as it’s run.
There are numerous ways in which we may run the appliance, so let’s have a look at a few of them. The primary means is to provide the flask
command with numerous arguments: --app
, then the title of the module that holds, our Flask software, after which run
. See under:
flask –app <the title of your module> run
Utilizing the instance above to run our pattern software:
flask –app howdy run
That may run our software on the default port 5000
so the appliance can be accessible on http://localhost:5000/
or at http://127.0.0.1:5000/
. If we would like the appliance to be accessible on a distinct port, we are able to specify the port utilizing -p
or --port
possibility. For instance:
flask --app howdy run --port=8080
That may run the server on port 8080. The opposite means we are able to run the appliance is by simply utilizing the flask run
instructions. Nonetheless, for us to have the ability to do this, we have to inform Flask the title of the module that may maintain the Flask occasion, and we do this by setting the FLASK_APP
atmosphere variable. So in our case, the Flask software is contained in a file named howdy.py
. So we are able to set it this manner:
export FLASK_APP=howdy
Now that we’ve set the FLASK_APP
atmosphere variable, we are able to run the event server like so:
flask run
With that code, we now have an internet software operating. This demonstrates the core philosophy of Flask: we don’t want a number of boilerplate code to get issues going. Nonetheless, the appliance we’ve arrange above isn’t very purposeful or helpful, because it solely renders the string “Whats up World!” on our net web page. To do something extra helpful, we are able to flip to templates. We’ll have a look at the right way to deal with them subsequent.
Flask Templates
Flask templates are a technique to create dynamic net pages that may show totally different content material based mostly on varied elements, similar to knowledge from a database, or consumer enter. Templates in Flask are a mix of HTML and particular placeholders known as template variables which can be changed with precise values at runtime.
Templates are saved within the templates
listing. So to make use of templates, we have to import the render_template()
technique from flask
. The render_template()
technique takes a template title and any elective knowledge that must be handed to the template.
Let’s see an instance of a perform that makes use of a template to render an internet web page:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
title = 'Welcome to my web site!'
message = 'That is an instance of utilizing Flask templates.'
return render_template('index.html', title=title, message=message)
Within the instance above, now we have a view perform — index()
— that’s sure to the basis URL (“/”) by the @app.route()
decorator. The perform has two variables, title
and message
. Lastly, we move the template index.html
to the render_template()
, along with the title
and message
variables.
For the code above to work, we have to have an index.html
template residing in a templates listing. So the template will look one thing like this:
# index.html
<!doctype html>
<html>
<head>
<title>{{ title }}</title>
</head>
<physique>
<h1>{{ title }}</h1>
<p>{{ message }}</p>
</physique>
</html>
Within the index.html
file, the placeholders {{title}}
and {{ message }}
are changed with the values handed to the template within the render_template()
technique.
Templates may embody extra advanced logic similar to if
statements and for
loops, which permit for extra dynamic pages to be generated.
So templates in Flask present builders with a really highly effective possibility for creating dynamic net pages wealthy with user-generate data.
Flask Routing
Most net purposes can have a couple of URL, so we have to have a means of figuring out which perform handles which URL. In Flask, this mapping is named routing — the method of binding or mapping URLs to view capabilities. Binding URLs to view capabilities permits the appliance to deal with several types of requests, similar to GET
, POST
, PUT
, DELETE
, and extra. It additionally allows the appliance to deal with a number of requests from totally different shoppers.
To arrange routes in Flask, we use the route()
decorator. The decorator binds a URL to a view perform — so when a consumer visits a URL that exists on our software, Flask triggers the related view perform to deal with the request.
Let’s see an instance:
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/about")
def about():
return "That is the about web page"
Within the instance above, we outline an about URL (/about
). When the appliance receives a request for the about
URL, Flask calls the about()
perform, which returns the string “That is the about web page”.
Thus far, although these examples return totally different pages, all of them simply use the GET
HTTP request. So as to have the ability to deal with any particular request, we are able to specify the HTTP technique as an elective argument to the route()
decorator.
Let’s see an instance of a PUT
request:
from flask import Flask, request
app = Flask(__name__)
@app.route('/customers/<int:user_id>', strategies=['PUT'])
def update_user(user_id):
knowledge = request.get_json()
return {'message': f'Person {user_id} up to date efficiently'}, 200
On this instance, we outline a route that handles a PUT
request to replace consumer particulars given their user_id
. We use <int:user_id>
within the route to point that the consumer ID needs to be an integer.
Within the update_user()
perform, we get the consumer knowledge from the request physique utilizing the request.get_json()
technique. We do one thing with the consumer knowledge, similar to updating the consumer within the database, after which return a response indicating success or failure together with an HTTP standing code (a 200
on this case to point out success).
Total, routing permits Flask to have the ability to deal with several types of requests and permits our software to deal with and act on knowledge in a different way, relying on the URL {that a} consumer visits.
Flask Kinds and Validation
Aside from displaying knowledge for customers, Flask templates may take enter from customers for additional processing or storage. For that, Flask supplies built-in help for processing HTML varieties and dealing with consumer enter. Flask varieties are based mostly on the WTForms library, which supplies a versatile and highly effective technique to deal with type knowledge and carry out validations. Nonetheless, the library isn’t part of the usual Flask set up, so we have to set up it utilizing the next command:
pip set up WTForms
As soon as we’ve put in WTForms, to make use of varieties in Flask we have to outline a type class that may inherit from flask_wtf.FlaskForm
. The category will include the fields which can be going to be on the shape and any validation guidelines that needs to be utilized to them.
Let’s see an instance of a login type:
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Electronic mail, Size
class LoginForm(FlaskForm):
e mail = StringField('Electronic mail', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired(), Length(min=6)])
submit = SubmitField('Log In')
Within the instance above, we outline a login type with two fields — e mail
and password
— and a submit button. We even have a validators
argument that’s used to specify validation guidelines for every area. For instance, on this case we require the e mail
area to include a sound e mail deal with and the password
area to include a password of no fewer than six characters.
As soon as we’ve outlined the shape class, we are able to use it within the login view perform to render the shape and course of the shape knowledge submitted by the consumer. Let’s see an instance of the view perform:
from flask import render_template, request
from .varieties import LoginForm
@app.route('/login', strategies=['GET', 'POST'])
def login():
type = LoginForm()
if type.validate_on_submit():
e mail = type.e mail.knowledge
password = type.password.knowledge
return render_template('login.html', type=type)
Within the instance above, now we have a login
view that accepts two HTTP strategies (GET
and POST
), so when customers entry the URL from a browser the LoginForm
is rendered as an HTML type utilizing the render_template
technique, and when a consumer submits the shape we verify if the shape is legitimate utilizing the validate_on_submit
technique. If the shape is legitimate, we entry the e-mail and password.
The login.html
type may look one thing like this:
# login.html
<h1>Login</h1>
<type technique="POST">
{{ type.csrf_token }}
<div>
{{ type.e mail.label }} {{ type.e mail() }}
{% for error in type.e mail.errors %}
<span fashion="shade: purple;">[{{ error }}]</span>
{% endfor %}
</div>
<div>
{{ type.password.label }} {{ type.password() }}
{% for error in type.password.errors %}
<span fashion="shade: purple;">[{{ error }}]</span>
{% endfor %}
</div>
{{ type.submit() }}
</type>
The above template will render the e mail
and password
fields, together with their labels, and a submit button with the textual content “Login”. The type.csrf_token
area is included to stop cross-site request forgery (CSRF) assaults. The {% for %}
loops are used to show any validation errors that will happen.
Through the use of Flask varieties, now we have a robust means of dealing with consumer enter, and we’ll be capable of validate the information they enter.
Flask Extensions
As we’ve seen, Flask is a microframework that solely contains an important elements wanted to create an internet software. Nonetheless, if we have to add performance that isn’t supplied out of the field by Flask, we have to add packages to the set up. Flask extensions are the way in which we offer this extra performance. We are able to merely set up the package deal we’d like. There are lots of extensions made by the Flask group.
Listed here are a number of the hottest ones:
- Flask-SQLAlchemy: supplies integration with the SQLAlchemy toolkit that makes it simple to work together with databases.
- Flask-Login: supplies consumer authentication and session administration to Flask.
- Flask-Mail: supplies a easy interface to ship emails from Flask.
There are tons of of extensions made by the Flask group to deal with totally different performance. Utilizing the extensions is usually simple. First, we have to set up the extension we would like utilizing pip.
Let’s see an instance of utilizing Flask-SQLAlchemy. First, we have to set up it:
pip set up flask-sqlalchemy
Subsequent, we have to configure it. For instance:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///instance.db'
db = SQLAlchemy(app)
class Person(db.Mannequin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), distinctive=True, nullable=False)
e mail = db.Column(db.String(120), distinctive=True, nullable=False)
def __repr__(self):
return '<Person %r>' % self.username
Within the instance above, now we have a Person
mannequin with a username
and e mail
area. We additionally configure SQLALCHEMY_DATABASE_URI
, indicating that we’re utilizing an SQLite database situated at instance.db
. With that set, we now have entry to the db
object that enables us to work together with the database. For instance, we may create a brand new consumer and add it to the database, like so:
from app import db, Person
consumer = Person(username='john', e mail='[email protected]')
db.session.add(consumer)
db.session.commit()
With Flask extensions, our software is ready to have extra performance than it might usually have with the core Flask implementation.
Conclusion
On this article, we launched Flask, a light-weight and versatile net framework for Python. We mentioned some great benefits of utilizing Flask for net improvement, together with its simplicity, flexibility, and ease of use. We additionally coated the right way to arrange a improvement atmosphere, create routes, use templates, deal with varieties, and use extensions like Flask-SQLAlchemy.
To summarize, Flask is a good selection for constructing net purposes of any measurement, from small private initiatives to large-scale industrial purposes. It’s simple to study and use, but in addition affords superior options by means of its many extensions.
In the event you’re excited by studying extra about Flask, listed here are some further sources:
In the event you’d prefer to study extra about Django and Flask and their greatest use instances, take a look at Python Web Development with Django and Flask.