」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > Python Web 框架綜合比較 Flask vs Django

Python Web 框架綜合比較 Flask vs Django

發佈於2024-11-04
瀏覽:442

Flask and Django are the two leading Python web frameworks and while they both help developers build websites quickly, they do so with vastly different approaches. In this article, we will look at what each framework does, how they work, and why developers choose one over the other. To demonstrate these differences we will build out three distinct projects from scratch—Hello World app, Personal website, and a To Do project—so you can see for yourself how they work and make the best decision for your needs.

What's a Web Framework?

Database-driven websites have remarkably similar needs: URL routing, logic, connect to a database, render HTML templates, user authentication, and so on. In the early days of the World Wide Web, developers had to construct all these pieces themselves before they even started work on the website itself.

Open-source web frameworks soon emerged that allowed groups of developers to collaborate on this challenge, sharing best practices, reviewing code, and generally not reinventing the wheel every time someone wanted to build a new website. There are web frameworks in every major programming language with notable examples including Ruby on Rails written in Ruby, Laravel written in PHP, Spring written in Java, and in Python the two frameworks we cover here: Flask and Django.

If you're new to programming, it might be confusing to hear the term Python "framework" vs "library." Both refer to software but the difference is complexity: a library is focused on a specific problem, while a framework tackles a larger challenge and often incorporates many smaller libraries to do so. As we'll see, both Flask and Django rely on quite a few Python libraries.

Which is More Popular?

If we look at GitHub stars, Flask and Django are relatively neck and neck but we can see the explosive growth of FastAPI, which is now clearly established in the top 3 of Python web frameworks.

Flask vs Django in A Comprehensive Comparison of Python Web Frameworks

The 2023 Python Developers Survey shows Django just ahead of Flask in 2023 but with FastAPI also gaining momentum.

Flask vs Django in A Comprehensive Comparison of Python Web Frameworks

Stack Overflow's 2023 survey of developers across all programming languages Flask slightly ahead but followed almost immediately by Django and with FastAPI a little behind.

Flask vs Django in A Comprehensive Comparison of Python Web Frameworks

These comparisons are interesting to view for trends but don't account for many things. For example, just because a web framework is popular, does that mean that real companies and professional developers are using it, or is it just something that beginners like to play around with?

Regardless of the comparison metric, it is clear Flask and Django are currently the top two Python web frameworks.

Jobs

If you're looking for a job as a Python web developer, Django is the better choice. There are almost twice as many listings for Django developers as for Flask on major job boards such as Indeed.com.

However, this disparity is likely because Django is a much more specific choice than Flask. A startup or company can run almost all of their services just on Django whereas Flask is often used alongside other technologies given its lightweight footprint.

The most employable approach is to truly master Python first and then add web development knowledge with either Django or Flask (ideally both!) on top.

Community

Django has the larger, more organized community of the two. There are over 1,800 committers to the Django codebase vs around 550 for Flask. On StackOverflow there are ~212,500 Django questions compared to ~31,500 Flask questions.

Django also has annual conferences in the United States, Europe, and Australia. Flask does not have a similar level of conferences, although there are active discussions for both frameworks at PyCon events.

What is Flask?

Flask is a micro-framework that is intentionally minimal and flexible by design, which clearly doesn't limit its utility. As we will see, this design decision comes with both strengths and weaknesses.

Flask started out as an April Fool's joke in 2010 by Armin Ronacher and was inspired by the Sinatra Ruby framework. FLask was meant to be simple enough to fit in a single Python file and, despite its humorous origins, Flask quickly gained popularity due to its simplicity and flexibility.

Flask itself has a quite small codebase and relies heavily on two major dependencies: Werkzeug and Jinja, both of which were initially created by Armin Ronacher.

Werkzeug is a WSGI (Web Server Gateway Interface) toolkit that provides the core functionality for Flask. It handles HTTP requests, and responses, a URL routing system, a built-in development server, interactive debugger, test client, and middleware. Jinja is a templating engine used to generate dynamic HTML documents that comes with its own syntax for basic logic, variables, if/else loops, template inheritance, and more.

Although Flask doesn't specify a specific structure, it is often used in a Model-View-Controller (MVC) pattern common to other web frameworks such as Ruby on Rails.

  • Model: Interacts with the database and handles data logic.
  • View: Renders HTML templates (usually) with data for the user.
  • Controller: Processes user input, interacts with the Model, and selects the View to render.

Flask's micro-framework architecture means it performs a few tasks extremely well and relies on third-party libraries (and the developer) to implement the rest. This approach is well-suited to smaller web applications that don't require all the bells and whistles built into Django. On the other extreme, experienced programmers who demand complete control over their application often prefer Flask, though this means making more design decisions than they would with a full framework like Django.

What is Django?

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It was created in at the Lawrence Journal-World newspaper and publicly released in 2005. "High-level" means that Django is designed to minimize the actual coding required during the web application process by providing built-in "batteries" for most use cases, including an ORM (Object-Relational Mapper), URL routing, template engine, form handling, authentication system, admin interface, and robust security features. In Flask, the developer must choose and implement these various features but with Django they are included out-of-the-box.

Django is managed by the non-profit Django Software Foundation and has a large and dedicated community behind it working on new releases, extensive documentation, active online communities, and regular community-run conferences.

Django follows a variant of the MVC architecture called the Model-View-Template (MVT) pattern that emphasizes separation of concerns:

  • Model: Handles data and business logic, including methods to interact with the data
  • View: Handles business logic and interacts with the Model and Template. It also processes user requests.
  • Templates: Render the user interface, usually as HTML using the Django templating language

A fourth component, URLs, is also included and used to handle URL routing, matching a user request to a specific View that then generates a response.

Flask: Hello, World

Python should already be installed on your computer so all we need to do is create a virtual environment and install Flask.

# Windows
$ python -m venv .venv
$ .venv\Scripts\Activate.ps1
(.venv) $ python -m pip install flask

# macOS/Linux
$ python3 -m venv .venv
$ source .venv/bin/activate
(.venv) $ python -m pip install flask

With your text editor, create a new file called hello.py. Flask famously requires only five lines for a Hello World web page.

# app.py
from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "

Hello, World!

"

This code imports the Flask class at the top and creates an instance called app on the next line. The route() decorator tells Flask what URL should trigger the function; here it is set to the homepage at /. Then the function, hello_world, returns an HTML string between paragraph

tags with our message.

To run the code, use the flask run command.

(.venv)
$ flask run
 * Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL C to quit

If you navigate to 127.0.0.1:5000 in your web browser the message is visible. Flask uses port 5000 by default.

Flask vs Django in A Comprehensive Comparison of Python Web Frameworks

This is about as simple as can be and speaks to both Flask's roots as an attempt at a single-file way to create a web application and also an example of its inherent flexibility.

Django: Hello, World

The Django docs don't provide a similar quickstart guide but we can accomplish a similar feat with only a few more lines of code. In fact, doing so has become a bit of a game among seasoned Django developers and there is an entire repo, django-microframework, dedicated to these efforts. We will choose Option2, which is not the most concise, but is more easily understood than some of the other approaches.

Navigate to a new directory, perhaps called django on your Desktop, and create a virtual environment containing Django.

# Windows
> cd onedrive\desktop\code
> mkdir django
> cd django
> python -m venv .venv
> .venv\Scripts\Activate.ps1
(.venv) > python -m pip install django

# macOS
% cd ~/desktop/code
% mkdir django
% cd django
% python3 -m venv .venv
% source .venv/bin/activate
(.venv) % python3 -m pip install django

In your text editor create a hello_django.py file with the following code:

# hello_django.py
from django.conf import settings
from django.core.handlers.wsgi import WSGIHandler
from django.core.management import execute_from_command_line
from django.http import HttpResponse
from django.urls import path

settings.configure(
    ROOT_URLCONF=__name__,
    DEBUG=True,
)


def hello_world(request):
    return HttpResponse("Hello, Django!")


urlpatterns = [path("", hello_world)]

application = WSGIHandler()

if __name__ == "__main__":
    execute_from_command_line()

Django is designed for larger web application and typically relies on a global settings.py file for many configurations, however we can import what we need in a single file. The key points of reference are the hello_world function that returns the string, "Hello, Django!" and the urlpatterns defining our URL routes, namely at "", meaning the empty string, so the homepage.

Start up Django's built-in server using the runserver command

(.venv) > python hello_django.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
July 17, 2024 - 13:48:54
Django version 5.0, using settings None
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Navigate to Django's standard port of 8000, http://127.0.0.1:8000/, to see the "Hello, Django!" message.

Flask vs Django in A Comprehensive Comparison of Python Web Frameworks

Django required tweleve lines of code rather than Flask's five, but both these examples are intended as quickstart guides; they are not how you structure a real-world Flask or Django app.

Flask Personal Website

Now let's build a Personal Website with a home page and an about page. This will give a chance to introduce templates and repeat some of the patterns we saw around how routes are defined in Flask.

Update the app.py file as follows:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')

@app.route('/about')
def about():
    return render_template('about.html')

if __name__ == '__main__':
    app.run(debug=True)

Both the home and about View functions now return a template. We're also using the route() decorator again to define the URL path for each. We've also added debug=True at the bottom so that the development server runs now in debug mode.

The next step is creating our two templates. Flask will look for template files in a templates directory so create that now.

(.venv) $ mkdir templates

Within it add the two files with the following code:

  1. Create templates in templates/:




    Personal Website

Welcome to My Website

About Me




    About Me

About Me

This is my personal website.

Home

Each file use the method url_for to define links based on the view function name.

Run the server again with flask run and navigate to the homepage:

Flask vs Django in A Comprehensive Comparison of Python Web Frameworks

Then click the "About Me" link.

Flask vs Django in A Comprehensive Comparison of Python Web Frameworks

This is a rudimentary example but you can start to see how templates and views interact in Flask. We still have only one main Python file powering the whole thing, but once we have many more pages and start to introduce logic, the single-file approach stops making sense and it's time to start organizing the Flask app in different ways. There are some common patterns used in the Flask community, however, it is ultimately up to the developer.

Django: Personal Website

Django is designed for full-bodied web applications so building a Personal Website is a chance to see this in action. We'll start by creating a project, which is the central hub for our website, using the startproject command.

(.venv) $ django-admin startproject django_project .

We've named the project django_project here. Adding the period, ., means the new folder and files are installed in the current directory. If you don't have the period Django creates a new directory and then adds the project folder and files there.

This is what your directory should look like now. The hello_django.py file remains and can either be left there or removed entirely: we will no longer use it. There is an entirely new django_project folder containing several files and a manage.py file used for running Django commands.

├── django_project
│   ├── __init__.py
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── hello_django.py
└── manage.py

We want to create an app now using thes startapp command which will be called pages. A single Django project typically has multiple apps for different functionality. If we added user registration that code should be in its own app, same for payments, and so on. This is a way to help developers reason better about their code.

(.venv) $ python manage.py startapp pages.

This command creates a pages directory with the following files:

└── pages
    ├── __init__.py
    ├── admin.py
    ├── apps.py
    ├── migrations
    │   └── __init__.py
    ├── models.py
    ├── tests.py
    └── views.py

Our first step is updating the django_project/settings.py file to tell Django about our new app. This is a global settings file for the entire project.

# django_project/settings.py
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "pages",  # new
]

Second, update the django_project/urls.py file. When a URL request comes in it will hit this file first and then be either processed or redirected to a specific app. In this case, we want to send requests to the pages app. To do this we'll import include and set a new path at "", meaning the homepage. Django defaults to including the URL configuration for the built-in admin, a powerful visual way to interact with your database.

# django_project/urls.py
from django.contrib import admin
from django.urls import path, include  # new

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", include("pages.urls")),  # new
]

Within the pages app we need a view and a URLs file. Let's start with the view at pages/views.py.

# pages/views.py
from django.shortcuts import render


def home(request):
    return render(request, "home.html")


def about(request):
    return render(request, "about.html")

In Django, views receive web requests and return web responses. The request parameter is an object containing metadata about the request from the user. We'll define two function-based views here, home and about, that use the shortcut function render to combine a template with an HttpResponse object sent back to the user. The two templates are home.html and about.html.

For the templates, we can create a templates directory within pages, then another directory with the app name, and finally our template files. This approach removes any concerns about confusing the Django template loader in larger projects.

(.venv) $ mkdir pages/templates
(.venv) $ mkdir pages/templates/pages

Then in your text editor add two new files: pages/templates/pages/home.html and pages/templates/pages/about.html.





    Personal Website

Welcome to My Website

About Me




    About Me

About Me

This is my personal website.

Home

The final step is configuring the URLs for these two pages. To do this, create a urls.py file within the pages app with the following code.

# pages/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path("", views.home, name="home"),
    path("about/", views.about, name="about"),
]

At the top we import our views and then set a URL path for each. The syntax is defining the URL path, the view name, and optionally adding a URL name that allows us to link to each path in our templates.

Start up the Django local server with the runserver command.

(.venv) $ python manage.py runserver

You can see the homepage:

Flask vs Django in A Comprehensive Comparison of Python Web Frameworks

Click the "About Me" to be redirected to the about page:

Flask vs Django in A Comprehensive Comparison of Python Web Frameworks

As you can see Django required more scaffolding than Flask, however this approach provides a consistent structure that is quite scaleable.

Detailed Comparison

The true comparison of these web frameworks depends on your project's needs. Are you building a traditional web application that connects to a database, requires CRUD (Create-Read-Update-Delete) functionality, and user authentication? If yes, Django has built-in solutions for all of these needs. By comparison, Flask requires installing multiple third-party libraries: Flask-SQLAlchemy to connect to the database, Flask-Migrate to manage database migrations, Flask-WTF and WTForms for forms, Flask-Login for user authentication, FLask-Mail for email support, Flask-Security for security features, Flask-Admin for an admin interface to manage application data, Flask-Caching for caching support, Flask-BCrypt for password hashing and so on.

The power of Django is that you don't have to worry about any of these things. They are included, tested, and supported by the community. For Flask, the third-party libraries are not as tightly integrated and require more manual installation by the developer. This affords greater flexibility but also requires more programmer expertise.

Conclusion

Ultimately, you can't go wrong choosing Flask or Django for your web application needs. They both are mature, scaleable, and well-documented. This difference is in approach and the best way to determine what you prefer is to try each out by building more complex projects.

If you're interested in learning more about Django, check out Django for Beginners for a guide to building six progressively more complex web applications including testing and deployment. For Flask, the Flask Mega-Tutorial has a free online version. There are also two courses over at TestDriven.io worth recommending: TDD with Python, Flask and Docker and Authentication with Flask, React, and Docker. If you prefer video, there are many Flask courses on Udemy but the best video course I've seen is Build a SaaS App with Flask and Docker.

版本聲明 本文轉載於:https://dev.to/wsvincent/flask-vs-django-in-2024-a-comprehensive-comparison-of-python-web-frameworks-4mhh?1如有侵犯,請聯絡study_golang@163 .com刪除
最新教學 更多>
  • 為什麼 $_POST 中的 Axios POST 資料不可存取?
    為什麼 $_POST 中的 Axios POST 資料不可存取?
    Axios Post 參數未由$_POST 讀取您正在使用Axios 將資料發佈到PHP 端點,並希望在$ 中存取它_POST 或$_REQUEST。但是,您目前無法檢測到它。 最初,您使用了預設的 axios.post 方法,但由於懷疑標頭問題而切換到提供的程式碼片段。儘管發生了這種變化,數據仍然...
    程式設計 發佈於2024-11-08
  • ## JPQL 中的建構函數表達式:使用還是不使用?
    ## JPQL 中的建構函數表達式:使用還是不使用?
    JPQL 中的建構子表達式:有益或有問題的實踐? JPQL 提供了使用建構函式表達式在 select 語句中建立新物件的能力。雖然此功能提供了某些優勢,但它引發了關於其在軟體開發實踐中是否適用的問題。 建構函數表達式的優點建構函數表達式允許開發人員從實體中提取特定資料並進行組裝,從而簡化了資料檢索將...
    程式設計 發佈於2024-11-08
  • 原型
    原型
    創意設計模式之一。 用於建立給定物件的重複/淺副本。 當直接建立物件成本高昂時,此模式很有用,例如:如果在查詢大型資料庫後建立對象,則一次又一次地建立該物件在效能方面並不經濟。 因此,一旦創建了對象,我們就緩存該對象,並且在將來需要相同的對象時,我們從緩存中獲取它,而不是從數據庫中再次創建它,...
    程式設計 發佈於2024-11-08
  • Python 變數:命名規則和型別推斷解釋
    Python 變數:命名規則和型別推斷解釋
    Python 是一種廣泛使用的程式語言,以其簡單性和可讀性而聞名。了解變數的工作原理是編寫高效 Python 程式碼的基礎。在本文中,我們將介紹Python變數命名規則和類型推斷,確保您可以編寫乾淨、無錯誤的程式碼。 Python變數命名規則 在Python中命名變數時,必須遵循一...
    程式設計 發佈於2024-11-08
  • 如何同時有效率地將多個欄位新增至 Pandas DataFrame ?
    如何同時有效率地將多個欄位新增至 Pandas DataFrame ?
    同時向Pandas DataFrame 添加多個列在Pandas 資料操作中,有效地向DataFrame 添加多個新列可能是一項需要優雅解決方案的任務。雖然使用帶有等號的列列表語法的直覺方法可能看起來很簡單,但它可能會導致意外的結果。 挑戰如提供的範例所示,以下語法無法如預期建立新欄位:df[['c...
    程式設計 發佈於2024-11-08
  • 從開發人員到資深架構師:技術專長與奉獻精神的成功故事
    從開發人員到資深架構師:技術專長與奉獻精神的成功故事
    一個開發人員晉升為高級架構師的真實故事 一位熟練的Java EE開發人員,只有4年的經驗,加入了一家跨國IT公司,並晉升為高級架構師。憑藉著多樣化的技能和 Oracle 認證的 Java EE 企業架構師,該開發人員已經證明了他在架構領域的勇氣。 加入公司後,開發人員被分配到一個項目,該公司在為汽...
    程式設計 發佈於2024-11-08
  • 如何在 PHP 8.1 中有條件地將元素新增至關聯數組?
    如何在 PHP 8.1 中有條件地將元素新增至關聯數組?
    條件數組元素添加在 PHP 中,有條件地將元素添加到關聯數組的任務可能是一個挑戰。例如,考慮以下數組:$arr = ['a' => 'abc'];我們如何有條件地添加'b' => 'xyz'使用array() 語句對此陣列進行運算?在這種情況下,三元運算子不是一...
    程式設計 發佈於2024-11-08
  • 從打字機到像素:CMYK、RGB 和建立色彩視覺化工具的旅程
    從打字機到像素:CMYK、RGB 和建立色彩視覺化工具的旅程
    當我還是個孩子的時候,我出版了一本關於漫畫的粉絲雜誌。那是在我擁有計算機之前很久——它是用打字機、紙和剪刀創建的! 粉絲雜誌最初是黑白的,在我的學校複印的。隨著時間的推移,隨著它取得了更大的成功,我能夠負擔得起帶有彩色封面的膠印! 然而,管理這些顏色非常具有挑戰性。每個封面必須列印四次,每種顏色...
    程式設計 發佈於2024-11-08
  • 如何將 Boehm 的垃圾收集器與 C++ 標準函式庫整合?
    如何將 Boehm 的垃圾收集器與 C++ 標準函式庫整合?
    整合 Boehm 垃圾收集器和 C 標準庫要將 Boehm 保守垃圾收集器與 C標準庫集合無縫集成,有兩種主要方法:重新定義運算符::new此方法涉及重新定義運算符::new以使用Boehm的GC。但是,它可能與現有 C 程式碼衝突,並且可能無法在不同編譯器之間移植。 明確分配器參數您可以使用而不是...
    程式設計 發佈於2024-11-08
  • 如何優化子集驗證以獲得頂級效能?
    如何優化子集驗證以獲得頂級效能?
    優化子集驗證:確保每一位都很重要確定一個清單是否是另一個清單的子集的任務在程式設計中常遇到。雖然交叉列表和比較相等性是一種簡單的方法,但考慮效能至關重要,尤其是對於大型資料集。 考慮到這種情況,需要考慮的一個關鍵因素是任何清單在多個測試中是否保持不變。由於您的場景中的其中一個清單是靜態的,因此我們可...
    程式設計 發佈於2024-11-08
  • 如何處理超出 MySQL BIGINT 限制的大整數?
    如何處理超出 MySQL BIGINT 限制的大整數?
    超出MySQL BIGINT 限制的大整數處理超出MySQL BIGINT 限制的大整數處理MySQL 的BIGINT 資料型別可能看起來是最廣泛的整數表示形式,但在處理時會出現限制超過20 位的數字。 超出BIGINT 的選項邊界當儲存需求超出BIGINT的能力時,會出現兩個選項:儲存為VARCH...
    程式設計 發佈於2024-11-08
  • 如何確保 Python Selenium 中載入多個元素?
    如何確保 Python Selenium 中載入多個元素?
    Python Selenium:確保多個元素載入透過AJAX 處理動態載入的元素時,確認其外觀可能具有挑戰性。為了處理這種情況,我們將利用 Selenium 的 WebDriverWait 及其各種策略來確保多個元素的存在。 所有元素的可見性:驗證所有與特定選擇器匹配的元素,我們可以使用visibi...
    程式設計 發佈於2024-11-08
  • 了解 JavaScript 中的標記模板文字
    了解 JavaScript 中的標記模板文字
    什麼是標記模板文字? 帶有標籤的模板文字涉及以函數為前綴的模板文字,稱為標籤。此函數可以處理和操作文字的內容。這是一個簡單的例子: function tag(strings, ...values) { console.log(strings); console.lo...
    程式設計 發佈於2024-11-08
  • 二指針演算法解釋
    二指針演算法解釋
    我想解釋一個簡單有效的技巧,你可以在面試中處理數組、字串、鍊錶等時使用它。這也將提高你對這些數據的基礎知識結構。 讓我們從理論開始。該演算法有兩個常見用例: left/right 這個演算法的中心概念是有兩個整數變量,它們將從字串或數組的兩側移動。通常,人們稱之為左和右。左邊將從0索引移動到長度-...
    程式設計 發佈於2024-11-08
  • 如何消除Python列印語句中的空格?
    如何消除Python列印語句中的空格?
    在 Python 列印語句中刪除空格在 Python 中,列印多個項目通常會導致出現意外的空格。可以使用 sep 參數消除這些空格來解決此問題。例如,考慮這個:print("a", "b", "c")此輸出將包含空格:a b c要消除它們:...
    程式設計 發佈於2024-11-08

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3