Thứ Bảy, 7 tháng 11, 2020

[Learning] Flask Framework - Python [#1] - Overview


Hello guys!

After SVATTT CTF competition with consolation prize, I decide to try hard and spend more time learning, seriously. 

Today I move on with Flask - an important and interesting framework in Python.

1. Definition

+ Distinguish Module, Library and Framwork

- Moduleabstract interface with explicit exports and imports, implementation and interface are separate, there may be multiple implementations and the implementation is hidden.

- Librarycollection of related functionality

- Framework: something abstracts some low-level computer science concepts, you so can focus on the high level details

- MicroframeworkA microframework is a term used to refer to minimalistic web application frameworks. It is contrasted with full-stack frameworks.

“Micro” does not mean that your whole web application has to fit into a single Python file (although it certainly can), nor does it mean that Flask is lacking in functionality. The “micro” in microframework means Flask aims to keep the core simple but extensible

+ What is Web framework

A Web Application Framework or a simply a Web Framework represents a collection of libraries and modules that enable web application developers to write applications without worrying about low-level details such as protocol, thread management, and so on.

+ What is Flask

Flask is a web application framework written in Python. Flask is based on the Werkzeg WSGI toolkit and the Jinja2 template engine.

- jinja2 :a popular template engine for Python.A web template system combines a template with a specific data source to render a dynamic web page.

Hello world in Flask

2. Installation

pip install Flask

pip install virtualenv 

3. Run a sample

- Create folder which contains file (

- Move to that folder.

- Create a virtual environment which will allow you to keep all the things you need for flask app into one project.

py -m venv <name>


Environment "Hello" has been created

- Activate it 



- Choose what file will be started

set FLASK_APP=<file_name>.py

- Run it

flask run

- Here is the result:

4. Features

It's hard to imagine a more critical feature of web frameworks than routing: the humble act of mapping URLs to actions, such as serving pages or data.

- Reserve a URL path, such as / or /home, associate this with a page template, and serve said template to the user, perhaps with added business logic.  That perspective works fine for small-scale applications, but meaningful applications (or APIs) aren't static one-to-one mappings. To build products larger than ourselves, we need to arm them with the ability to grow in ways we can't foresee, which means defining dynamic routing opportunities that can potentially grow endlessly. 

For demo, I make a .html file named about and write down something random. Next I will define it in our which already appeared above.  

Our result after browse to /about URI

render_template() accepts one positional argument, which is the name of the template found in our templates folder (in this case, about.html). In addition, we can pass values to our template as keyword arguments. For example, if we want to set the title and content of our template via our view into our template, we can do so:
def about():
    return render_template(
        body="we're talking about Academy of Cryptography techniques"

If we're building an endpoint intended to respond with information to be used programmatically, serving page templates isn't what we need. Instead, we should look to make_response().

make_response() allows us to serve up information while also providing a status code (such as 200 or 500), and also allows us to attach headers to the said response. 

def user():
    resp= make_response(
        'Test worked!',
    resp.headers["Content-Type"] = "application/json"
    return resp

Here is the result :

redirect() is the last of our big three route resolutions.

Redirect accepts a string, which will be the path to redirect the user to. This can be a relative path, absolute path, or even an external URL.its best practice to refer to routes by their names and not by their URL patterns.

url_for() : this built-in function takes the name of a view function as input, and will output the URL route of the provided view. 

from flask import Flask, redirect, url_for

def login():
    return redirect(url_for('dashboard'))
def dashboard():
    return render_template('dashboard.html')



By default, a route only answer to GET method. You can use the methods argument of the route() decorator to handle different HTTP methods.

from flask import request

def login():
    if request.methods=='POST'
        return redirect(url_for('dashboard'))
        return render_template('about.html')
def dashboard():
        return render_template('dashboard.html')

With GET:

With POST:

If GET is present, Flask automatically adds support for the HEAD method and handles HEAD requests according to the HTTP RFC. Likewise, OPTIONS is automatically implemented for you.

+ The REQUEST object

request() is one of the "global" objects we mentioned earlier. Take a look at what things are attached to request which we can access in a route:

request.method: Contains the method used to access a route, such as GET or POST. It is absolutely essential for building smart routes: we can use this logic to have one route serve multiple different responses depending on what method was used to call said route.

request.args: Contains the query-string parameters of a request that hit our route. If we're building an endpoint that accepts a url parameter, for example, we can get this from the request as request.args.get('url’). Returns the body of an object posted to a route.

request.form: If a user hits this route as a result of form submission, request.form is our way of accessing the information the form posted. For example, to fetch the provided username of a submitted form, request.form['username'] is used.

request.headers: Contains the HTTP response headers of a request.


What happens when a user of our app experiences a fatal error? Flask provides us a decorator called errorhandler() which serves as a catch-all route for a given HTTP error.

def server_error():
    return make_response(render_template('server-error.html'),500)

+ STATIC FILES        

Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called static in your package or next to your module and it will be available at /static on the application.

See the demo below

def robots():
    return url_for('static', filename='troll.jpg')

Continue ...

Link [#3] Flask Framework - Python [#3]

Happy Learning!


Không có nhận xét nào:

Đăng nhận xét

Phổ Biến