Flask is an extensible microframework, meaning it comes with a small set of core features needed to create a web application, supporting extensions to extend Flask when required. For example, Flask doesn’t have a database layer, making a database decision for you. Instead, if you need a database for your project, you can choose a database extension.
This lean, minimalist approach is well suited for smaller projects where a large “batteries included” framework like Django might be overkill. That said, developers have used Flask to build large projects, including LinkedIn and Pinterest.
Though a micro framework, Flask became the most popular Python web framework in 2016.
Route – the act of binding a URL to a view function
View function – a function that’s invoked by the URL specified by the route. Flask places no limit on the number of routes you can define. You can have routes for /about, /contact, /services, and so on.
Static route – A route returning static content such as an HTML file..
Dynamic route – A route comprised of one or more variables that change the content returned. For example, a user profile route would serve dynamic content, depending on the unique id of each user (the variable in this case).
Before you start
Flask works with both Python 2.x or 3.x but its best to start using Python 3.x for new projects. If you haven’t installed Python yet, see this <installing Python> article, and learn how to create virtual environments on your operating system. Virtual environments enable you to have a space to install packages and make other changes without affecting anything else.
You’ll want to know some Python basics before learning Flask. This <introduction to Python> will help.
Set up a virtual environment project
For Mac and Linux, you can use the pip package manager:
$ sudo pip install virtualenv
On Ubuntu Linux, you’ll likely use apt-get
$ sudo apt-get install python-virtualenv
On Windows install easy_install. Once you’ve installed easy_install, the process is the same as the Mac though there’s no need for “sudo”.
$ pip install virtualenv
Start the virtual environment for your project. Name your project whatever you want.
$ mkdir flask_project1 $ cd flask_project1 $ virtualenv venv
In your projects directory, flask_project1 in this case, start a virtual environment.
$ . venv/bin/activate
And to deactivate:
Now it’s time to install Flask and get going with your first Flask project.
$ pip install Flask
Create your Flask “Hello World” program
Create and open a file called hello.py using your favorite text editor.
#!/usr/bin/env python3 # the "shebang" at the top tells the script where to find python3 #import the Flask class from flask import Flask # Create an instance of the flask class by assigning it to a variable app = Flask(__name__) # Use a route decorator that tells flask that the URL should trigger this function. # You can use different route decorators to trigger other functions. @app.route('/') # Define the hello_world function, which returns the string whenever the function's triggered def hello_world(): return 'Hello World!'
Export your app.
$ export FLASK_APP=hello.py
Then run the app with Flask!
$ flask run
Unless there’s an error (it’s easy to make typos in scripts), you’ll get output that looks something like this:
* Serving Flask app “hello”
* Running on
http://127.0.0.1:5000/ (Press CTRL+C to quit)
Now, open a browser and enter
Congratulations, you’ve written your first Flask script! You can learn more and build on that as much as you want.
Running scripts on your virtual server with a public IP address.
Your local Mac or Windows machine probably isn’t set up as a web server to the outside world. A good next step would be to recreate the Hello World script on your VPS. Follow the same instructions above on your virtual server with a public IP address.
Except when you run the script make the server available through your public IP address by setting
flask run --host=0.0.0.0
Debug and automatic restart
To do this import the DEBUG module, setting debug mode to 1 (meaning true in the true/false boolean logic). This makes modifying and debugging your programs much easier.
$ export FLASK_DEBUG=1 $ flask run
Now your script will run in debug mode, providing you more helpful information if something goes wrong, and when you change your program, it will automatically restart, executing your changes with little to no downtime for your application.
Try running your app confirming that it’s returning Hello World in a browser. Then open another terminal, edit hello.py replacing “Hello World!” with “Hello Flask!” or whatever you want. Save the file. Then refresh your browser. The browser should seamlessly return “Hello Flask!”
Next, let’s see how debug mode helps you identify errors. Open your script, then intentionally introducing a syntax error. Remove the “e” from route so that it’s @app.rout(‘/’)
Then run your script.
If you’ve ever been baffled by an error returned by a computer or a program, you’re in for a pleasant surprise. An error page loads with a calming color scheme, a descriptive error message, and the ability to click on and interact with the error page. The error page will prompt you for a pin, which you can find in the console output returned when you flask run. The error page does everything but fix the syntax error for you!
#!/usr/bin/env python3 from flask import Flask sapp = Flask(__name__)
@app.route("/") def index(): return "Welcome home!" @app.route("/names/<string:name>/") def getNames(name): return ("Hi " + name) if __name__ == "__main__": app.run()
Then run the modified program.
$ flask run
Now enter your first name after
It should return Hi followed by your name!
You now know the basics of serving dynamic content with Flask, enabling you to create applications that serve personalized, interactive content that respond to user input.
This introduction was meant to show you how easy it is to get started using Flask and give you a glimpse of its potential. To create web apps with Flask, you’ll want to delve deeper with more in-depth tutorials and practice building your apps.
A good next step would be to explore Flask’s Github page, which includes links to documentation, tutorials, and other excellent resources.
You’ll also get a sense of how Flask works with other packages such as the Jinja template engine and the Werkzeug (Web Server Gateway Interface) WSGI utility library. The great thing about Flask is the core of it is small enough that you’ll be able to learn it relatively fast and get started creating web applications quickly.
Check out the top 3 Python hosting services:
- You can discover new info about Best website hosting by clicking this link.