首頁 > 後端開發 > Python教學 > Python Web 框架綜合比較 Flask vs Django

Python Web 框架綜合比較 Flask vs Django

WBOY
發布: 2024-08-29 10:37:20
原創
438 人瀏覽過

Flask 和 Django 是兩個領先的 Python Web 框架,雖然它們都可以幫助開發人員快速建立網站,但它們的方法卻截然不同。在本文中,我們將了解每個框架的用途、工作原理以及開發人員選擇其中一個框架的原因。為了展示這些差異,我們將從頭開始建立三個不同的項目- Hello World 應用程式、個人網站和待辦事項項目- 這樣您就可以親眼看看它們是如何工作的,並根據您的需求做出最佳決策。

什麼是網路框架?

資料庫驅動的網站有非常相似的需求:URL 路由、邏輯、連接到資料庫、呈現 HTML 範本、使用者驗證等。在萬維網的早期,開發人員必須自己建立所有這些部分,然後才能開始開發網站本身。

開源 Web 框架很快出現,允許開發人員小組協作應對這一挑戰,分享最佳實踐,審查程式碼,並且通常不會在每次有人想要建立新網站時重新發明輪子。每種主要程式語言都有 Web 框架,其中著名的範例包括用 Ruby 編寫的 Ruby on Rails、用 PHP 編寫的 Laravel、用 Java 編寫的 Spring,以及我們在 Python 中介紹的兩個框架:Flask 和 Django。

如果您是程式設計新手,聽到 Python「框架」與「函式庫」這個術語可能會感到困惑。兩者都指的是軟體,但區別在於複雜性:庫專注於特定問題,而框架則解決更大的挑戰,並且通常會合併許多較小的庫來實現這一目標。正如我們將看到的,Flask 和 Django 都依賴相當多的 Python 庫。

哪個更受歡迎?

如果我們看一下 GitHub 的 star 數,Flask 和 Django 相對並駕齊驅,但我們可以看到 FastAPI 的爆炸性增長,它現在已經明確躋身 Python Web 框架前 3 名。

Flask vs Django in A Comprehensive Comparison of Python Web Frameworks

2023 年 Python 開發者調查顯示 Django 在 2023 年領先 Flask,但 FastAPI 也獲得了發展勢頭。

Flask vs Django in A Comprehensive Comparison of Python Web Frameworks

Stack Overflow 對所有程式語言的開發人員進行的 2023 年調查 Flask 稍稍領先,但緊隨其後的是 Django,FastAPI 稍稍落後。

Flask vs Django in A Comprehensive Comparison of Python Web Frameworks

這些比較對於趨勢的觀察很有趣,但並不能解釋很多事情。例如,一個Web框架很流行,是否意味著真正的公司和專業開發人員正在使用它,或者它只是初學者喜歡玩的東西?

無論比較指標如何,很明顯 Flask 和 Django 是目前排名前兩位的 Python Web 框架。

工作機會

如果您正在尋找 Python Web 開發人員的工作,Django 是更好的選擇。在 Indeed.com 等主要招聘網站上,Django 開發人員的清單數量幾乎是 Flask 的兩倍。

但是,這種差異可能是因為 Django 是比 Flask 更具體的選擇。新創公司或公司可以僅在 Django 上運行幾乎所有的服務,而 Flask 由於其輕量級的佔用空間而經常與其他技術一起使用。

最實用的方法是先真正掌握 Python,然後使用 Django 或 Flask(最好兩者都!)添加 Web 開發知識。

社群

Django 擁有兩者中規模更大、更有組織的社區。 Django 程式碼庫有超過 1,800 名提交者,而 Flask 的提交者約為 550 名。 StackOverflow 上有大約 212,500 個 Django 問題,而 Flask 問題有大約 31,500 個。

Django還在美國、歐洲和澳洲舉辦年會。儘管 PyCon 活動中對這兩個框架都有積極的討論,但 Flask 沒有類似級別的會議。

什麼是燒瓶?

Flask 是一個微框架,其設計有意做到最小化和靈活,這顯然並沒有限制它的實用性。正如我們將看到的,這個設計決策既有優點也有缺點。

Flask 最初是 Armin Ronacher 於 2010 年開的愚人節玩笑,靈感來自於 Sinatra Ruby 框架。 FLask 的設計初衷是足夠簡單,適合單一 Python 文件,儘管它的起源很幽默,但 Flask 由於其簡單性和靈活性很快就受到了歡迎。

Flask 本身的程式碼庫相當小,並且嚴重依賴兩個主要依賴項:Werkzeug 和 Jinja,這兩個依賴項最初都是由 Armin Ronacher 創建的。

Werkzeug 是一個 WSGI(Web 伺服器閘道介面)工具包,為 Flask 提供核心功能。它處理 HTTP 請求和回應、URL 路由系統、內建開發伺服器、互動式偵錯器、測試客戶端和中間件。 Jinja 是一個模板引擎,用於產生動態 HTML 文檔,它具有自己的基本邏輯、變數、if/else 循環、模板繼承等語法。

雖然 Flask 沒有指定特定的結構,但它經常用於其他 Web 框架(例如 Ruby on Rails)常見的模型-視圖-控制器 (MVC) 模式。

  • 模型:與資料庫交互,處理資料邏輯。
  • 視圖:(通常)為使用者呈現帶有資料的 HTML 模板。
  • 控制器:處理使用者輸入,與模型交互,並選擇要渲染的視圖。

Flask 的微框架架構意味著它可以非常好地執行一些任務,並依賴第三方程式庫(和開發人員)來實現其餘任務。這種方法非常適合不需要 Django 內建的所有功能的小型 Web 應用程式。在另一個極端,需要完全控制應用程式的經驗豐富的程式設計師通常更喜歡 Flask,儘管這意味著比使用 Django 這樣的完整框架要做出更多的設計決策。

姜戈是什麼?

Django 是一個高階 Python Web 框架,鼓勵快速開發和簡潔、務實的設計。它是由《勞倫斯世界日報》創建,並於 2005 年公開發布。 「進階」意味著Django 旨在透過為大多數用例提供內建「電池」來最大限度地減少Web 應用程式過程中所需的實際編碼,包括ORM(物件關聯映射器)、URL 路由、模板引擎、表單處理、身份驗證系統、管理介面和強大的安全功能。在 Flask 中,開發人員必須選擇並實作這些不同的功能,但在 Django 中,它們是開箱即用的。

Django 由非營利 Django 軟體基金會管理,背​​後有一個龐大而專注的社區,致力於新版本、廣泛的文檔、活躍的線上社群和定期的社區運作會議。

Django 遵循 MVC 架構的一種變體,稱為模型-視圖-模板 (MVT) 模式,強調關注點分離:

  • 模型:處理資料和業務邏輯,包括與資料互動的方法
  • View:處理業務邏輯並與模型和範本互動。它還處理用戶請求。
  • 模板:渲染使用者介面,通常使用 Django 模板語言作為 HTML

還包含第四個元件 URLs,用於處理 URL 路由,將使用者請求與特定視圖相匹配,然後產生回應。

燒瓶:你好,世界

Python 應該已經安裝在你的電腦上,所以我們需要做的就是創建一個虛擬環境並安裝 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
登入後複製

使用文字編輯器建立一個名為 hello.py 的新檔案。 Flask 眾所周知,Hello World 網頁只需要五行。

# app.py
from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "<p>Hello, World!</p>"
登入後複製

此程式碼在頂部導入 Flask 類,並在下一行建立一個名為 app 的實例。 Route() 裝飾器告訴 Flask 哪個 URL 應該觸發該函數;此處設定為首頁 /。然後函數 hello_world 傳回段落

和段落之間的 HTML 字串。帶有我們的訊息的標籤。

要執行程式碼,請使用flask run 指令。

(.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
登入後複製

如果您在網頁瀏覽器中導航至 127.0.0.1:5000,則該訊息可見。 Flask 預設使用連接埠 5000。

Flask vs Django in A Comprehensive Comparison of Python Web Frameworks

這幾乎是最簡單的,並且說明了 Flask 的根源是嘗試用單文件方式創建 Web 應用程序,也是其固有靈活性的一個示例。

姜戈:你好,世界

Django 文件沒有提供類似的快速入門指南,但我們只需多寫幾行程式碼就可以完成類似的任務。事實上,這樣做已經成為經驗豐富的 Django 開發人員之間的一種遊戲,並且有一個完整的儲存庫 django-microframework 致力於這些工作。我們會選擇選項2,它不是最簡潔的,但比其他一些方法更容易理解。

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/:
<!-- templates/home.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Personal Website</title>
</head>
<body>
    <h1>Welcome to My Website</h1>
    <a href="{{ url_for('about') }}">About Me</a>
</body>
</html>
登入後複製
<!-- templates/about.html -->
<!DOCTYPE html>
<html>
<head>
    <title>About Me</title>
</head>
<body>
    <h1>About Me</h1>
    <p>This is my personal website.</p>
    <a href="{{ url_for('home') }}">Home</a>
</body>
</html>
登入後複製

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.

<!-- pages/templates/pages/home.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Personal Website</title>
</head>
<body>
    <h1>Welcome to My Website</h1>
    <a href="{% url 'about' %}">About Me</a>
</body>
</html>
登入後複製
<!-- pages/templates/pages/about.html -->
<!DOCTYPE html>
<html>
<head>
    <title>About Me</title>
</head>
<body>
    <h1>About Me</h1>
    <p>This is my personal website.</p>
    <a href="{% url 'home' %}">Home</a>
</body>
</html>
登入後複製

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.

以上是Python Web 框架綜合比較 Flask vs Django的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板