Review of Flask, From a Django Developer

Review of Flask, From a Django Developer

原文链接:https://www.giulianopertile.com/blog/review-of-flask-from-a-django-developer/

Are you familiar with Django, but you want to give Flask a try? or maybe you have no idea what a microframework is?
Well today I am going to share my experience with Flask, comparing different aspects of both frameworks, so you can decide which one suits your needs.

你对 Django 很熟悉,但想尝试一下 Flask 吗? 或者你不知道什么是微框架?
今天我将分享我使用 Flask 的经验,比较一下两个框架的不同方面,帮助你决定哪一个符合你的需求。

Why I chose Flask?

为什么我选择 Flask?

After working with Django for a few years, I felt the need to explore another popular Python web framework, which is Flask. I always knew that Flask was a microframework (more on that below), but I never built anything with it. So I took the opportunity at work to experiment with a new framework for a certain web application, and my team and I decided to try Flask. So in this post I want to comment my opinions about Flask, after working with Django.

在使用 Django 工作几年之后,我感到有必要探索一下另一个流行的 Python Web 框架,那就是 Flask。我一直知道 Flask 是一个微框架(下面会讲到),但是我从来没有用它建立过任何东西。因此在我有机会在工作中尝试实验新框架创建一个 Web 应用时,我和我的团队决定尝试 Flask。因为在这篇文章里我想评论一下对 Flask 的看法,特别是在使用了 Django 工作之后。

What is Flask?

Flask 是什么?

Flask is a micro web framework written in Python. It is classified as a microframework because it does not require particular tools or libraries. It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions.

Flask 是一个用 Python 编写的微型 Web 框架。它被分类为微框架式因为它不需要特定的工具或库。它没有数据库抽象层,表单验证或其他现有的第三方提供的常用功能组件。

By contrast, Django is a web framework with a batteries-included philosophy. This means that the common functionality for building web applications should come with the framework instead of as separate libraries, like an ORM, template engine, user authentication and so on.

Application Structure

应用结构

In your a typical django project with one application, you would have a folder structure as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
django-project
├── config
│ ├── __init__.py
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.js
└─── app
├── __init.py
├── admin.py
├── apps.py
├── models.py
├── tests.py
├── urls.py
└── views.py

Whereas in a Flask application, you could start with just one file.

1
2
flask-project
└── app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
# app.py
from flask import Flask
app = Flask(__name__)


@app.route('/')
def index():
return '<h1>Hello World!</h1>'


@app.route('/user/<name>')
def user(name):
return '<h1>Hello, {}!</h1>'.format(name)

I remember when I started learning Django, this could be overwhelming, you have to learn why are those files there and adapt yourself to the default structure. In Flask you start with just a file, and you add more files as your project grows, this makes it easy to get started. When you add a file in your Flask app, you now why is there.

While in contrast to Flask, it’s easy to get started, but then you have to figure out how to organize your project as it grows, and this can be overwhelming if you don’t have much experience with Flask

Templates

模版

Flask doesn’t come with a template engine like Django does, but when you pip install flask, this comes with a dependency with Jinja2, which is a template engine, but don’t worry you don’t have to learn a new syntax, since it is similar to Django’s, as you can see in the code below, which is a typical template that you’d create in Django

1
2
3
4
5
6
7
8
9
10
{% extends "base.html" %}

{% block title %}Home{% endblock %}

{% block page_content %}
<div class="page-header">
<h1>Hello, {{ name }}!</h1>
<a href="{{ url_for('index') }}">Home<a>
</div>
{% endblock %}

There are differences of course like <a href="{{ url_for('index') }}">Home<a>, where in Django that would be <a href="{% url 'home' %}">Portada</a>, honestly, I didn’t find this tedious to learn, since, from my point of view, I think 90% of my knowledge of the Django template is transferable to Jinja2.

Forms

表单

Being a microframework, Flask relies on WTForms for its forms, that we need to install it, using:
pip install flask-wtf.
When using Flask-WTF, each web form is represented in the server by a class that inherits from the class FlaskForm. The class defines the list of fields in the form, each represented by an object. Each field object can have one or more validators attached.

An example is presented below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from flask import Flask, render_template
# WTForms
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired

app = Flask(__name__)
# against cross-site request forgery (CSRF) attacks
app.config['SECRET_KEY'] = 'my secret'

class NameForm(FlaskForm):
name = StringField('Enter your name', validators=[DataRequired()])
submit = SubmitField('Submit')

@app.route('/', methods=['GET', 'POST'])
def index():
name = None
form = NameForm()
if form.validate_on_submit():
name = form.name.data
form.name.data = ''
return render_template('index.html', form=form, name=name)
1
2
3
4
5
6
7
8
9
10
11
{% extends "base.html" %}
{% block title %}Hello there!{% endblock %}

{% block page_content %}
<div class="">
<h1>
Hello, {% if name %}{{ name }}
{% else %}there!{% endif %}!</h1>
</div>
{{ wtf.quick_form(form) }}
{% endblock %}

Personally, I find WTForms more straightforward than Django’s forms. But they have the disadvantage that you have to know how to organize them within the folder structure of your project. So if it’s for a small project, I prefer WTForms.

Databases

数据库

Authentication

身份验证

What I like about Flask

我喜欢 Flask 的哪些地方

Control of your project - Don’t fight your framework!

对项目的控制 - 不要和框架对着干!

Ecosystem

生态

No Magic

没有魔法

What I don’t like about Flask

我不喜欢 Flask 的哪些地方

Set up your application for the first time

第一次设置应用

Conclusion

结论

Review of Flask, From a Django Developer

https://pangwu86.com/posts/3737434686/

作者

胖五

发布于

2022-12-20

更新于

2023-01-08

许可协议

评论