Flask for Beginners
What is Flask?
We need good and easy frameworks to create web sites. Flask is one such web application development framework. It is written in Python. Flask is developed by “Armin Ronacher”, who leads an international group of Python enthusiasts named Pocco.
As Flask is developed in Python so it is important to learn Python before starting with Flask. To learn Python and to know commonly asked interview questions you can follow my blogs on Python. The links are as given below:
https://optimize-stage.sevenmentor.com/data-types-and-variables-in-python/
https://optimize-stage.sevenmentor.com/conditional-statements-in-python/
https://optimize-stage.sevenmentor.com/top-56-python-interview-questions-and-answers/
What is a Web Framework?
A Web Application Framework or Web Framework is nothing but a collection of libraries and modules that enables a web application developer to write applications without having to bother about low-level details such as protocols, thread management, etc.
You probably heard about Django when looking up for the Flask framework.
Both Django and Flask are web frameworks written in Python.
To create a full-stack web framework we can use Django, whereas Flask is a lightweight and extensible Python web framework.
The diagram above shows the difference between Flask and Django in a very simple way. Using Flask is like snorkeling but Django is scuba diving. Flask is light and easy to use whereas the Django framework is capable of preparing you to enter deeper waters.
Django’s tag is The web framework for a perfectionist with a deadline. In Django everything is built-in, you don’t need to bother yourself with creating the files and thinking about how you should structure your app. It’s all ready for you and you can immediately get started with building your app.
For Free, Demo classes Call: 7507414653
Registration Link:
Which framework to use for web development really depends on what you’re making. If you’re building a simple app, consider Flask.
For detail understanding of the Django framework along with a comparison with Ruby on Rails follow my blogs. The links are as given below:
https://optimize-stage.sevenmentor.com/django-vs-ruby-on-rails-which-is-a-better-framework/
You can also see Django interview questions on the link given below:
https://optimize-stage.sevenmentor.com/django-interview-questions-2019/
Why is Flask a good web framework choice?
Web development framework Flask is considered more Pythonic than the Django web framework because in common situations the equivalent Flask web application is more explicit. To get started as a beginner for web development Flask is the best framework as there is little boilerplate code for getting a simple app up and running.
Let’s see an example of this:
Here is a valid “Hello, world!” web application with Flask:
from flask import Flask
app = Flask(__name__)
@app.route(‘/’)
def hello_world():
return ‘Hello, World!’
if __name__ == ‘__main__’:
app.run()
The above code shows “Hello, World!” on a web browser. For this, we have to use localhost port 5000 and run it with the python app.py command. The Flask library will be installed.
To print “Hello, World!”, using the Django web development framework is possible. This Django framework involves significantly more boilerplate code.
Flask was written several years after Django and therefore learned from the Python community’s reactions as the framework evolved.
Flask Structure
Instead of placing all code required for the project in one place, Flask helps you organize your logic, design. Flask also keeps the database into separate files.
LOGIC: The file ‘main.py’ is responsible to import the Flask module, it creates a web server, an instance of the Flask class — your new web application. This is where you write all your “logical” code structuring your web app.
DESIGN: For HTML files The Flask Framework looks in a folder called templates. We should put all HTML files in the templates folder. This is done in a static folder, store CSS, JavaScript, images, and other files.
DATABASE: Flask does not support databases natively, but there are a number of Flask extensions such as Flask-SQLAlchemy.
In a flask, SQLAlchemy supports a long list of database engines, including the popular MySQL, PostgreSQL, and SQLite.
Preparation
Let’s say you have two different web projects, but one project uses Python 3.7.2 version whereas the other one uses version 2.7.2. Are you going to re-download the different Python versions every time you’re working on a different project? What will you do if you have not two but 50 or more web apps to review?
A virtual environment is a tool that helps us to keep dependencies required by different projects that are separated by creating isolated Python virtual environments for them.
The module which is used to create and manage virtual environments is known as venv. Make sure that when you’re creating a web app using Flask, you activate virtualenv accordingly.
For Free, Demo classes Call: 7507414653
Registration Link:
Deployment
After all of your hard work coding, you want to share it with the world: To share your web app, you need to deploy it.
Cloud hosting providers generally offer a managed platform on which applications can run. All you need to provide to have your application deployed on these platforms is the actual application, because the hardware, operating system, scripting language interpreters, database, etc. are all managed by the service (Grinberg).
Deploying Flask on Heroku
Deploying Flask on Google App Engine
Deploying Flask on AWS Elastic Beanstalk
Deploying on Azure (IIS)
Deploying on PythonAnywhere
Conclusion
I hope this helped you along your coding journey 🙂 If you have any exciting Flask apps made or just want to talk about Python in general, feel free to reach out anytime.
Why Flask?
Flask is very easy to use.
It has a built-in development server and debugger
Flask uses integrated unit testing support
For request dispatching Flask have RESTful request dispatching
It uses Jinja2 technique for templating
Flask has support for secure cookies (client-side sessions)
Flask is 100% WSGI 1.0 compliant
Flask framework is Unicode based
Flask is properly documented
Let’s see a small example of an app in Flask:
$ pip install Flask
Create a file called hello.py
from flask import Flask
app = Flask(__name__)
@app.route(“/”)
def hello():
return “Hello World!”
if __name__ == “__main__”:
app.run()
Finally, run the web app using this command:
$ python hello.py
* Running on http://localhost:5000/
Open http://localhost:5000/ in your web browser, and “Hello World!” should appear.
Creating URL routes:
URL Routing is used to makes URLs in your Web app easy to remember. We will now create some URL routes:
/hello
/members/
/members/name/
Save code given below app.py
from flask import Flask
app = Flask(__name__)
@app.route(“/”)
def index():
return “Index!”
@app.route(“/hello”)
def hello():
return “Hello World!”
@app.route(“/members”)
def members():
return “Members”
@app.route(“/members/<string:name>/”)
def getMember(name):
return name</string:name>
if __name__ == “__main__”:
app.run()
For Free, Demo classes Call: 7507414653
Registration Link:
Restart the application using:
$ python hello.py
* Running on http://localhost:5000/
Try the URLs in your browser:
http://127.0.0.1:5000/members/Jordan/
Style Flask Pages
To separate code and User Interface we will use a technique called Templates. For this we will make the directory called /templates/ and create the template:
<h1>Hello { {name}}</h1>
Given below is Python Flask app with a new URL route. We have changed the default port to 80, the default HTTP port:
from flask import *
app = Flask(__name__)
@app.route(“/”)
def index():
return “Flask App!”
@app.route(“/hello/<string:name>/”)
def hello(name):
return render_template(‘test.html’,name=name)</string:name>
if __name__ == “__main__”:
app.run(host=’0.0.0.0′, port=80)
You can then open: http://127.0.0.1/hello/Jackson/
Styling the template
Do you want some better looking template? We modify the file:
{% extends “layout.html” %}
{% block body %}
<div class=”block1″>
<h1>Hello { {name}}!</h1>
<h2>Here is an interesting quote for you:</h2>
“Once you choose hope, everything is possible”
<img src=”http://www.naturalprogramming.com/images/smilingpython.gif”>
</div>
{% endblock %}
We will create layout.html which defines the look of the page. (There may be need to split the stylesheet and layout.html file). Copy this as layout.html
<title>Website</title>
<style>
@import url(http://fonts.googleapis.com/css?family=Amatic+SC:700);</p>
<p>body{<br />
text-align: center;<br />
}<br />
h1{<br />
font-family: ‘Amatic SC’, cursive;<br />
font-weight: normal;<br />
color: #8ac640;<br />
font-size: 2.5em;<br />
}</p>
</style>{% block body %}{% endblock %}
Restart the App and open the URL. http://127.0.0.1/hello/Jackson/
We can specify any name other than Jackson.
Passing Variables
The program given below will display random quotes instead of always the same quote. In this we will pass both the name variable and the quote variable. In order to pass multiple variables to the function, we simply do this:
return render_template(
‘test.html’,**locals())
Our new test.html template will look like this:
{% extends “layout.html” %}
{% block body %}
<div class=”block1″>
<h1>Hello { {name}}!</h1>
<h2>Here is an interesting quote for you:</h2>
{ {quote}}
<img src=”http://www.naturalprogramming.com/images/smilingpython.gif”>
</div>
{% endblock %}
We will need to pick a random quote. To do so, we use this code:
quotes = [ “I have no special talent. I am only passionately curious. Albert Einstein”,
“‘To understand recursion you must first understand recursion..’ — Unknown”,
“‘Stay hungry, stay foolish. Steve Jobs”,
“‘When you prepare for future today, the future will belong to you.”,
“‘Not everyone will understand your journey. That’s fine. It’s not their journey to make sense of. It’s yours.’ — Unknown” ]
randomNumber = randint(0,len(quotes)-1)
quote = quotes[randomNumber]
For Free, Demo classes Call: 7507414653
Registration Link:
Firstly we can see that we have defined an array of multiples quotes. To access them we have to use indexes as quote[0], quote[1], quote[2] and so on. We need to use function randint() which returns a random number between 0 and the total number of quotes, one is subtracted because we start counting from zero. At the end, we will set the quote variable to the quote the computer has chosen. Copy the code below to app.py:
from flask import *
from random import randint
app = Flask(__name__)
@app.route(“/”)
def index():
return “Flask App!”
#@app.route(“/hello/<string:name>”)
@app.route(“/hello/<string:name>/”)
def hello(name):
# return name
quotes = [ “I have no special talent. I am only passionately curious. Albert Einstein”,
“‘To understand recursion you must first understand recursion..’ — Unknown”,
“‘Stay hungry, stay foolish. Steve Jobs”,
“‘When you prepare for future today, the future will belong to you.”,
“‘Not everyone will understand your journey. That’s fine. It’s not their journey to make sense of. Its yours.’ — Unknown” ]
randomNumber = randint(0,len(quotes)-1)
quote = quotes[randomNumber] </string:name></string:name>
return render_template(
‘test.html’,**locals())
if __name__ == “__main__”:
app.run(host=’0.0.0.0′, port=80)
To see the effect you must restart the application. After restart, it will return one of these quotes at random.
Author:
Jagtap, Nikita | SevenMentor Pvt Ltd.
Call the Trainer and Book your free demo Class for now!!!
© Copyright 2019 | Sevenmentor Pvt Ltd.