Getting Began with Flask, a Python Microframework — SitePoint

0
1


On this article, we’ll introduce Flask, a preferred microframework for Python that gives an alternative choice to the enormous that’s Django.

Flask is designed to be light-weight and versatile, permitting builders to create internet 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 commonest Flask extensions, and when is and isn’t a very good time to make use of Flask.

What Is Flask?

Flask is a micro internet framework written in Python that’s used for creating internet purposes. It’s constructed on a easy philosophy of holding issues easy and light-weight, giving builders solely an important instruments wanted to construct internet apps with out pointless complexity.

It’s constructed on prime of the Werkzeug WSGI toolkit, which offers internet 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 internet purposes.

Listed below are among the key options of Flask that make it such an ideal framework to work with:

  • It has a easy API for creating internet routes and dealing with requests.
  • The Jinja templating engine gives assist for HTML templates, permitting builders to create internet pages simply.
  • It’s extremely extendable, because of its assist for third-party extensions, so a developer can set up extensions relying on their challenge wants.
  • It comes bundled with a improvement server that makes it simple to check and debug apps.

Total, Flask offers a robust, versatile, but easy framework for constructing internet purposes. It’s a sensible choice for each new and skilled internet builders, and is among the hottest internet frameworks within the Python internet improvement ecosystem.

Benefits of Flask

Let’s now take a extra detailed take a look at among the benefits of utilizing Flask in improvement.

Simplicity. Flask’s design philosophy emphasizes simplicity, which makes it simple for builders at any stage to grasp and use. This additionally signifies that builders have a really minimal studying curve, since they solely have to be taught a couple of ideas and APIs to get began constructing internet purposes.

Flexibility. The micro nature of Flask — offering solely the core options of an internet framework — provides builders the facility 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 fundamental to superior subjects, making it very simple for builders to discover ways to use the framework.

Compatibility. Flask is suitable with a variety of Python variations, which makes it simple to make use of with present Python codebases. It additionally has assist for a number of internet servers, which makes it simple to deploy it on a wide range of internet hosting platforms.

Fast improvement. Flask’s simplicity and suppleness cut back the boilerplate wanted to arrange an utility, permitting builders to get began shortly.

Across the Net, Flask is utilized in a whole lot of fascinating methods. Just a few 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. This can be 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 internet improvement stack, permitting its crew 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 internet tasks:

  • Prototyping. Its ease of use and suppleness 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 effectively 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 gives a helpful and simple method to construct and deploy AI coaching fashions.

When Not To Use Flask

Whereas Flask is a superb framework and has an a variety of benefits and nice options, there are conditions these options work in opposition to it. Let’s discover among the tasks that go well with different forms of frameworks higher.

Initiatives that require built-in performance. Being a microframework, Flask solely offers the core bits wanted to create an internet utility. If a challenge 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, we’ve got 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, equivalent to Twister or Twisted.

Initiatives that implement some coding normal. Resulting from Flask’s flexibility, creating purposes on it leaves builders to make apps in any method they see match. Nevertheless, frameworks like Django be sure that builders comply with a specific conference, that means that builders can transfer from one challenge to different simply.

Setting Up a Flask Improvement Setting

Let’s now take a look at how you can get began with Flask, from establishing the event setting, to set up, and eventually spinning up a minimal utility.

Conditions

Python must be put in on the event machine. Listed below are directions for that (though we might have already got it put in).

Create a Digital Setting

A digital setting is an remoted Python setting the place we will set up packages for a given challenge with out affecting the worldwide Python set up. (Right here’s additional dialogue about why digital environments are helpful.) There are completely different packages for creating digital environments in Python, equivalent to virtualenv, venv, or Conda.

On this article, we’ll use virtualenv. We will set up it with the next command:

pip set up virtualenv

As soon as virtualenv has been put in, we will create a listing the place our Flask utility will reside. We will name the listing no matter we wish — 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 will begin utilizing it:

cd flask_intro

In that listing, let’s now create our digital setting, utilizing the next command:

virtualenv myenv

The command above creates a digital setting and calls it myenv. Let’s activate it in order that we will set up Flask in it. To activate the digital setting on Linux or macOS, use the next command:

. myenv/bin/activate

On Home windows, use this command:

. myenvScriptsactivate

As soon as our digital setting has been activated, it is going to present the title of the digital setting on the shell immediate, just like the output under:

(myenv)/~(path to your challenge listing)$

Inside our activated digital setting, we will 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 utility. We’ll create a module that may maintain our Flask utility. For simplicity’s sake, let’s name it whats up.py. On Linux or macOS we will use the next command to create the file in our flask_intro listing:

contact whats up.py

The command above creates a file named whats up.py. We may additionally use a improvement setting to create the file. As soon as the file has been created, put the under code in it and put it aside:


from flask import Flask
app = Flask(__name__)
@app.route("https://www.sitepoint.com/")
def hello_world():
    return 'Hiya, 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 cross the __name__ variable.

Then we’ve got the route decorator @app.route(“”), which signifies that the hello_world() operate can be triggered when somebody visits the foundation route of our utility as soon as it’s run.

There are numerous ways in which we may run the applying, so let’s take a look at a few of them. The primary method is to provide the flask command with plenty of arguments: --app, then the title of the module that holds, our Flask utility, after which run. See under:

flask –app <the title of your module> run

Utilizing the instance above to run our pattern utility:

flask –app whats up run

That can run our utility on the default port 5000 so the applying can be out there on http://localhost:5000/ or at http://127.0.0.1:5000/. If we wish the applying to be out there on a unique port, we will specify the port utilizing -p or --port possibility. For instance:

flask --app whats up run --port=8080

That can run the server on port 8080. The opposite method we will run the applying is by simply utilizing the flask run instructions. Nevertheless, for us to have the ability to try this, we have to inform Flask the title of the module that may maintain the Flask occasion, and we try this by setting the FLASK_APP setting variable. So in our case, the Flask utility is contained in a file named whats up.py. So we will set it this manner:

export FLASK_APP=whats up

Now that we’ve set the FLASK_APP setting variable, we will run the event server like so:

flask run

With that code, we now have an internet utility working. This demonstrates the core philosophy of Flask: we don’t want a whole lot of boilerplate code to get issues going. Nevertheless, the applying we’ve arrange above isn’t very practical or helpful, because it solely renders the string “Hiya World!” on our internet web page. To do something extra helpful, we will flip to templates. We’ll take a look at how you can deal with them subsequent.

Flask Templates

Flask templates are a method to create dynamic internet pages that may show completely different content material primarily based on numerous elements, equivalent to knowledge from a database, or consumer enter. Templates in Flask are a mix of HTML and particular placeholders referred to 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() methodology from flask. The render_template() methodology takes a template title and any non-obligatory knowledge that must be handed to the template.

Let’s see an instance of a operate that makes use of a template to render an internet web page:


from flask import Flask, render_template
app = Flask(__name__)
@app.route("https://www.sitepoint.com/")
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, we’ve got a view operate — index() — that’s sure to the foundation URL (“/”) by the @app.route() decorator. The operate has two variables, title and message. Lastly, we cross 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() methodology.

Templates may also embrace extra advanced logic equivalent 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 internet pages wealthy with user-generate info.

Flask Routing

Most internet purposes could have multiple URL, so we have to have a method of understanding which operate 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 applying to deal with several types of requests, equivalent to GET, POST, PUT, DELETE, and extra. It additionally permits the applying to deal with a number of requests from completely different purchasers.

To arrange routes in Flask, we use the route() decorator. The decorator binds a URL to a view operate — so when a consumer visits a URL that exists on our utility, Flask triggers the related view operate 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 applying receives a request for the about URL, Flask calls the about() operate, which returns the string “That is the about web page”.

Up to now, although these examples return completely different pages, all of them simply use the GET HTTP request. So as to have the ability to deal with any particular request, we will specify the HTTP methodology as an non-obligatory 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 ought to be an integer.

Within the update_user() operate, we get the consumer knowledge from the request physique utilizing the request.get_json() methodology. We do one thing with the consumer knowledge, equivalent 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 indicate success).

Total, routing permits Flask to have the ability to deal with several types of requests and permits our utility to deal with and act on knowledge in another way, relying on the URL {that a} consumer visits.

Flask Varieties and Validation

Aside from displaying knowledge for customers, Flask templates may also take enter from customers for additional processing or storage. For that, Flask offers built-in assist for processing HTML kinds and dealing with consumer enter. Flask kinds are primarily based on the WTForms library, which offers a versatile and highly effective method to deal with type knowledge and carry out validations. Nevertheless, 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 kinds 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 ought 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):
    electronic 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 — electronic 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 electronic mail area to include a legitimate electronic 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 will use it within the login view operate to render the shape and course of the shape knowledge submitted by the consumer. Let’s see an instance of the view operate:


from flask import render_template, request
from .kinds import LoginForm

@app.route('/login', strategies=['GET', 'POST'])
def login():
    type = LoginForm()
    if type.validate_on_submit():
        electronic mail = type.electronic mail.knowledge
        password = type.password.knowledge
        
    return render_template('login.html', type=type)

Within the instance above, we’ve got 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 methodology, and when a consumer submits the shape we examine if the shape is legitimate utilizing the validate_on_submit methodology. 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 methodology="POST">
  {{ type.csrf_token }}
  <div>
    {{ type.electronic mail.label }} {{ type.electronic mail() }}
    {% for error in type.electronic mail.errors %}
    <span type="coloration: purple;">[{{ error }}]</span>
    {% endfor %}
  </div>
  <div>
    {{ type.password.label }} {{ type.password() }}
    {% for error in type.password.errors %}
      <span type="coloration: purple;">[{{ error }}]</span>
    {% endfor %}
  </div>
  {{ type.submit() }}
</type>

The above template will render the electronic 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 which will happen.

Through the use of Flask kinds, we’ve got a robust method 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 utility. Nevertheless, 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 best way we offer this extra performance. We will merely set up the package deal we want. There are a lot of extensions made by the Flask group.

Listed below are among the hottest ones:

  • Flask-SQLAlchemy: offers integration with the SQLAlchemy toolkit that makes it simple to work together with databases.
  • Flask-Login: offers consumer authentication and session administration to Flask.
  • Flask-Mail: offers a easy interface to ship emails from Flask.

There are tons of of extensions made by the Flask group to deal with completely different performance. Utilizing the extensions is mostly simple. First, we have to set up the extension we wish 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)
    electronic mail = db.Column(db.String(120), distinctive=True, nullable=False)

    def __repr__(self):
        return '<Person %r>' % self.username

Within the instance above, we’ve got a Person mannequin with a username and electronic 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', electronic mail='john@instance.com')
db.session.add(consumer)
db.session.commit()

With Flask extensions, our utility is ready to have extra performance than it will usually have with the core Flask implementation.

Conclusion

On this article, we launched Flask, a light-weight and versatile internet framework for Python. We mentioned the benefits of utilizing Flask for internet improvement, together with its simplicity, flexibility, and ease of use. We additionally lined how you can arrange a improvement setting, create routes, use templates, deal with kinds, and use extensions like Flask-SQLAlchemy.

To summarize, Flask is a superb selection for constructing internet purposes of any measurement, from small private tasks to large-scale business purposes. It’s simple to be taught and use, but in addition gives superior options by way of its many extensions.

When you’re concerned with studying extra about Flask, listed here are some extra assets:

When you’d wish to be taught extra about Django and Flask and their finest use instances, try Python Net Improvement with Django and Flask.



LEAVE A REPLY

Please enter your comment!
Please enter your name here