Python 웹 프레임워크를 종합적으로 비교한 Flask와 Django

WBOY
풀어 주다: 2024-08-29 10:37:20
원래의
296명이 탐색했습니다.

Flask와 Django는 두 가지 주요 Python 웹 프레임워크이며 둘 다 개발자가 웹 사이트를 빠르게 구축하는 데 도움이 되지만 매우 다른 접근 방식을 사용합니다. 이 기사에서는 각 프레임워크의 기능, 작동 방식, 개발자가 다른 프레임워크 중 하나를 선택하는 이유를 살펴보겠습니다. 이러한 차이점을 보여주기 위해 Hello World 앱, 개인 웹사이트, To Do 프로젝트 등 세 가지 개별 프로젝트를 처음부터 구축하여 작동 방식을 직접 확인하고 요구 사항에 가장 적합한 결정을 내릴 수 있습니다.

웹 프레임워크란 무엇입니까?

데이터베이스 기반 웹사이트에는 URL 라우팅, 논리, 데이터베이스 연결, HTML 템플릿 렌더링, 사용자 인증 등의 요구 사항이 매우 유사합니다. World Wide Web 초기에는 개발자가 웹사이트 자체 작업을 시작하기도 전에 이러한 모든 부분을 직접 구성해야 했습니다.

개발자 그룹이 이 과제에 대해 협력하고, 모범 사례를 공유하고, 코드를 검토하고, 일반적으로 누군가가 새 웹 사이트를 구축하려고 할 때마다 처음부터 다시 시작하지 않아도 되는 오픈 소스 웹 프레임워크가 곧 등장했습니다. 모든 주요 프로그래밍 언어에는 Ruby로 작성된 Ruby on Rails, PHP로 작성된 Laravel, Java로 작성된 Spring, 그리고 여기에서 다루는 두 가지 프레임워크인 Python인 Flask와 Django를 비롯한 주목할만한 예가 포함된 웹 프레임워크가 있습니다.

프로그래밍이 처음이라면 Python "프레임워크"와 "라이브러리"라는 용어를 들으면 혼란스러울 수 있습니다. 둘 다 소프트웨어를 참조하지만 차이점은 복잡성입니다. 라이브러리는 특정 문제에 초점을 맞추는 반면 프레임워크는 더 큰 문제를 해결하고 이를 위해 더 작은 라이브러리를 많이 통합하는 경우가 많습니다. 앞으로 살펴보겠지만 Flask와 Django는 모두 꽤 많은 Python 라이브러리에 의존합니다.

어느 것이 더 인기가 있나요?

GitHub 스타를 보면 Flask와 Django가 상대적으로 열세지만 FastAPI의 폭발적인 성장을 볼 수 있으며, 이제 Python 웹 프레임워크 상위 3위 안에 확실히 자리 잡았습니다.

Flask vs Django in A Comprehensive Comparison of Python Web Frameworks

2023년 Python 개발자 설문조사에 따르면 2023년에는 Django가 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

이러한 비교는 추세를 살펴보는 데 흥미롭지만 많은 사항을 설명하지는 않습니다. 예를 들어, 웹 프레임워크가 인기가 있다고 해서 실제 기업이나 전문 개발자가 사용한다는 의미일까요, 아니면 단지 초보자가 가지고 놀기 좋아하는 것일까요?

비교 지표에 관계없이 Flask와 Django가 현재 Python 웹 프레임워크 중 상위 2개라는 것은 분명합니다.

채용 정보

Python 웹 개발자로 일자리를 찾고 있다면 Django가 더 나은 선택입니다. 인디드닷컴(Indeed.com)과 같은 주요 채용 게시판에는 Django 개발자 목록이 Flask 목록보다 거의 두 배나 많습니다.

그러나 Django가 Flask보다 훨씬 더 구체적인 선택이기 때문에 이러한 차이가 발생할 가능성이 높습니다. 스타트업이나 회사는 거의 모든 서비스를 Django에서만 실행할 수 있는 반면 Flask는 설치 공간이 가볍기 때문에 다른 기술과 함께 사용되는 경우가 많습니다.

가장 적합한 접근 방식은 먼저 Python을 완전히 마스터한 다음 Django나 Flask(이상적으로는 둘 다!)를 사용하여 웹 개발 지식을 추가하는 것입니다.

지역 사회

Django는 둘 중 더 크고 조직화된 커뮤니티를 가지고 있습니다. Django 코드베이스에는 1,800명이 넘는 커미터가 있는데 비해 Flask에는 약 550명이 있습니다. StackOverflow에는 ~212,500개의 Django 질문이 있는 반면 Flask 질문은 ~31,500개 있습니다.

Django는 미국, 유럽, 호주에서도 연례 컨퍼런스를 개최하고 있습니다. Flask에는 비슷한 수준의 컨퍼런스가 없지만 PyCon 이벤트에서는 두 프레임워크에 대한 활발한 토론이 있습니다.

플라스크란 무엇입니까?

Flask는 의도적으로 최소화되고 유연하게 설계되어 유용성을 분명히 제한하지 않는 마이크로 프레임워크입니다. 앞으로 살펴보겠지만 이 디자인 결정에는 장점과 단점이 모두 있습니다.

Flask는 2010년 Armin Ronacher의 만우절 농담으로 시작되었으며 Sinatra Ruby 프레임워크에서 영감을 받았습니다. FLask는 단일 Python 파일에 들어갈 수 있을 만큼 단순하도록 만들어졌으며, 그 기원이 유머러스함에도 불구하고 Flask는 단순성과 유연성으로 인해 빠르게 인기를 얻었습니다.

Flask 자체는 상당히 작은 코드베이스를 갖고 있으며 처음에 Armin Ronacher가 만든 Werkzeug와 Jinja라는 두 가지 주요 종속성에 크게 의존합니다.

Werkzeug는 Flask의 핵심 기능을 제공하는 WSGI(Web Server Gateway Interface) 툴킷입니다. HTTP 요청 및 응답, URL 라우팅 시스템, 내장 개발 서버, 대화형 디버거, 테스트 클라이언트 및 미들웨어를 처리합니다. Jinja는 기본 논리, 변수, if/else 루프, 템플릿 상속 등에 대한 자체 구문이 포함된 동적 HTML 문서를 생성하는 데 사용되는 템플릿 엔진입니다.

Flask는 특정 구조를 지정하지 않지만 Ruby on Rails와 같은 다른 웹 프레임워크에 공통적인 MVC(Model-View-Controller) 패턴에서 사용되는 경우가 많습니다.

  • 모델: 데이터베이스와 상호작용하고 데이터 로직을 처리합니다.
  • 보기: 사용자를 위한 데이터와 함께 HTML 템플릿(일반적으로)을 렌더링합니다.
  • 컨트롤러: 사용자 입력을 처리하고 모델과 상호작용하며 렌더링할 뷰를 선택합니다.

Flask의 마이크로 프레임워크 아키텍처는 몇 가지 작업을 매우 잘 수행하고 타사 라이브러리(및 개발자)에 의존하여 나머지를 구현한다는 것을 의미합니다. 이 접근 방식은 Django에 내장된 모든 추가 기능이 필요하지 않은 소규모 웹 애플리케이션에 적합합니다. 반면에 애플리케이션에 대한 완전한 제어를 요구하는 숙련된 프로그래머는 Flask를 선호하는 경우가 많지만 이는 Django와 같은 전체 프레임워크를 사용할 때보다 더 많은 디자인 결정을 내려야 함을 의미합니다.

장고란 무엇인가요?

Django는 신속한 개발과 깔끔하고 실용적인 디자인을 장려하는 고급 Python 웹 프레임워크입니다. Lawrence Journal-World 신문에서 작성되었으며 2005년에 공개되었습니다. "높은 수준"은 Django가 대부분의 사용 사례에 내장된 "배터리"를 제공하여 웹 응용 프로그램 프로세스 중에 필요한 실제 코딩을 최소화하도록 설계되었음을 의미합니다. , ORM(Object-Relational Mapper), URL 라우팅, 템플릿 엔진, 양식 처리, 인증 시스템, 관리 인터페이스 및 강력한 보안 기능을 포함합니다. Flask에서는 개발자가 이러한 다양한 기능을 선택하고 구현해야 하지만 Django에서는 이러한 기능이 기본적으로 포함되어 있습니다.

Django는 비영리 Django Software Foundation에서 관리하며 새 릴리스, 광범위한 문서, 활발한 온라인 커뮤니티 및 정기적인 커뮤니티 운영 컨퍼런스를 작업하는 대규모 헌신적인 커뮤니티를 보유하고 있습니다.

Django는 관심사 분리를 강조하는 MVT(Model-View-Template) 패턴이라는 MVC 아키텍처의 변형을 따릅니다.

  • 모델: 데이터와 상호 작용하는 방법을 포함하여 데이터 및 비즈니스 로직을 처리합니다
  • 보기: 비즈니스 로직을 처리하고 모델 및 템플릿과 상호 작용합니다. 사용자 요청도 처리합니다.
  • 템플릿: 일반적으로 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 웹 페이지에 단 5줄만 요구하는 것으로 유명합니다.

# 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 문자열을 반환합니다. 메시지에 태그를 추가하세요.

코드를 실행하려면 플라스크 실행 명령을 사용하세요.

(.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의 뿌리와 고유한 유연성의 예를 모두 보여줍니다.

장고: 안녕하세요, 세계

Django 문서는 유사한 빠른 시작 가이드를 제공하지 않지만 코드 몇 줄만 더 사용하면 비슷한 작업을 수행할 수 있습니다. 사실, 그렇게 하는 것은 숙련된 Django 개발자들 사이에서 일종의 게임이 되었으며 이러한 노력에 전념하는 전체 저장소인 django-microframework가 있습니다. 가장 간결하지는 않지만 다른 접근 방식보다 이해하기 쉬운 Option2를 선택하겠습니다.

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 웹 프레임워크를 종합적으로 비교한 Flask와 Django의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!