응용 프로그래밍 인터페이스

문서의 이 부분은 Flask의 모든 인터페이스를 다룹니다. Flask가 외부 라이브러리에 의존하는 부분에 대해서는 가장 중요한 내용을 여기에서 설명하고, 공식 문서로 연결되는 링크를 제공합니다.

애플리케이션 객체

class flask.Flask(import_name, static_url_path=None, static_folder='static', static_host=None, host_matching=False, subdomain_matching=False, template_folder='templates', instance_path=None, instance_relative_config=False, root_path=None)

Flask 객체는 WSGI 애플리케이션을 구현하며 중심 역할을 하는 객체입니다. 이 객체는 애플리케이션의 모듈 또는 패키지 이름을 전달받습니다. 생성된 이후에는 view 함수, URL 규칙, 템플릿 설정 등 다양한 요소를 위한 중앙 레지스트리로 작동합니다.

패키지 이름은 해당 패키지가 실제 파이썬 패키지인지(내부에 :file:__init__.py 파일이 있는 폴더) 아니면 일반 모듈인지(단순히 .py 파일인 경우)에 따라 패키지 내부 또는 모듈이 포함된 폴더에서 리소스를 확인하는 데 사용됩니다.

리소스 로드에 대한 자세한 내용은 :func: `open_resource`를 참조하세요.

일반적으로 다음과 같이 메인 모듈이나 패키지의 __init__.py 파일에서 Flask 인스턴스를 생성합니다:

from flask import Flask
app = Flask(__name__)

첫 번째 파라미터에 대하여

첫 번째 파라미터의 목적은 Flask에 애플리케이션에 속하는 요소가 무엇인지 알려주는 것입니다. 이 이름은 파일 시스템에서 리소스를 찾는 데 사용되며, 확장 프로그램에서 디버깅 정보를 개선하거나 다양한 다른 용도로 활용될 수 있습니다.

따라서 여기에 어떤 값을 제공하는지가 중요합니다. 단일 모듈을 사용하는 경우에는 `__name__`이 항상 올바른 값입니다. 하지만 패키지를 사용하는 경우에는 패키지 이름을 직접 명시하는 것이 일반적으로 권장됩니다.

예를 들어, 애플리케이션이 :file: `yourapplication/app.py`에 정의되어 있다면, 아래 두 가지 버전 중 하나로 생성해야 합니다:

app = Flask('yourapplication')
app = Flask(__name__.split('.')[0])

왜 그렇게 해야 할까요? 리소스를 조회하는 방식 덕분에 `__name__ `을 사용해도 애플리케이션은 동작합니다. 그러나 디버깅이 더 어려워질 수 있습니다. 일부 확장은 애플리케이션의 임포트 이름을 기반으로 동작을 가정합니다. 예를 들어, Flask-SQLAlchemy 확장은 디버그 모드에서 SQL 쿼리를 실행한 애플리케이션 코드를 찾으려고 합니다. 하지만 임포트 이름이 제대로 설정되지 않은 경우 해당 디버깅 정보가 손실됩니다. (예를들어, `yourapplication.app`에서는 SQL 쿼리를 추적할 수 있지만, `yourapplication.views.frontend`에서는 추적할 수 없습니다.)

Changelog

Added in version 1.0: host_matching``및 `` static_host 매개변수가 추가되었습니다.

Added in version 1.0: ` ` subdomain_matching `` 파라미터가 추가되었습니다. 이제 서브도메인 매칭은 수동으로 활성화해야 합니다. :data: ` SERVER_NAME `을 설정한다고 해서 자동으로 활성화되지는 않습니다.

Added in version 0.11: ` root_path ` 파라미터가 추가되었습니다.

Added in version 0.8: ` instance_path ` 및 ` instance_relative_config ` 파라미터가 추가되었습니다.

Added in version 0.7: ` static_url_path `, ` static_folder `, ` template_folder ` 파라미터가 추가되었습니다.

매개변수:
  • import_name (str) – 애플리케이션 패키지의 이름

  • static_url_path (str | None) – 웹에서 정적 파일의 경로를 다르게 지정하는 데 사용할 수 있습니다. 기본값은 static_folder 폴더의 이름입니다.

  • static_folder (str | os.PathLike[str] | None) – `` static_url_path ``에서 제공되는 정적 파일이 포함된 폴더입니다. 애플리케이션의 ``root_path ``를 기준으로 하거나 절대 경로를 사용할 수 있습니다. 기본값은 ``’static’``입니다.

  • static_host (str | None) – 정적 라우트를 추가할 때 사용할 호스트입니다. 기본값은 None입니다.``host_matching=True``와 ``static_folder ``를 함께 설정할 때 필수로 지정해야 합니다.

  • host_matching (bool) – url_map.host_matching 속성을 설정합니다. 기본값은 False입니다.

  • subdomain_matching (bool) – 라우트를 매칭할 때 :data:`SERVER_NAME`을 기준으로 서브도메인을 고려합니다. 기본값은 False입니다.

  • template_folder (str | os.PathLike[str] | None) – 애플리케이션에서 사용할 템플릿이 포함된 폴더입니다. 기본값은 애플리케이션의 루트 경로에 있는 'templates' 폴더입니다.

  • instance_path (str | None) – 애플리케이션의 대체 인스턴스 경로입니다. 기본값으로는 패키지나 모듈 옆에 위치한 'instance' 폴더가 인스턴스 경로로 간주됩니다.

  • instance_relative_config (bool) – ``True``로 설정하면 구성 파일을 로드할 때 상대 경로가 애플리케이션 루트가 아닌 인스턴스 경로를 기준으로 간주됩니다.

  • root_path (str | None) – 애플리케이션 파일의 루트 경로입니다. 네임스페이스 패키지와 같이 자동으로 감지할 수 없는 경우에만 수동으로 설정해야 합니다.

request_class

:py:class:`~flask.wrappers.Request`의 별칭

response_class

:py:class:`~flask.wrappers.Response`의 별칭

session_interface: SessionInterface = <flask.sessions.SecureCookieSessionInterface object>

사용할 세션 인터페이스입니다. 기본값으로는 :class:`~flask.sessions.SecureCookieSessionInterface`의 인스턴스가 사용됩니다.

Changelog

Added in version 0.8.

cli: Group

이 객체에 대한 CLI 명령을 등록하기 위한 Click 명령 그룹입니다. 애플리케이션이 발견되고 블루프린트가 등록된 후에는 flask 명령을 통해 해당 명령을 사용할 수 있습니다.

get_send_file_max_age(filename)

send_file`에서 주어진 파일 경로에 대해 ``max_age`() 캐시 값을 결정하는 데 사용됩니다. 해당 값이 전달되지 않은 경우 적용됩니다.

기본적으로, 이는 current_app`의 설정에서 :data:`SEND_FILE_MAX_AGE_DEFAULT 값을 반환합니다. 기본값은 ``None``이며, 이는 브라우저가 시간 기반 캐시 대신 조건부 요청을 사용하도록 지시합니다. 이는 일반적으로 더 바람직한 방식입니다.

이 메서드는 Flask 클래스에 있는 동일한 메서드의 중복임을 유의하세요.

Changelog

버전 2.0에서 변경: 기본 구성은 12시간 대신 ``None``입니다.

Added in version 0.9.

매개변수:

filename (str | None)

반환 형식:

int | None

send_static_file(filename)

:attr:`static_folder`에서 파일을 제공하는 데 사용되는 뷰 함수입니다. :attr:`static_folder`가 설정되어 있으면 이 뷰에 대해 :attr:`static_url_path`에 자동으로 라우트가 등록됩니다.

이 메서드는 Flask 클래스에 있는 동일한 메서드의 중복임을 유의하세요.

Changelog

Added in version 0.5.

매개변수:

filename (str)

반환 형식:

Response

open_resource(resource, mode='rb', encoding=None)

:attr:`root_path`를 기준으로 리소스 파일을 열어 읽습니다.

예를 들어, Flask 애플리케이션이 정의된 app.py 파일 옆에 schema.sql 파일이 있다면 다음과 같이 열 수 있습니다:

with app.open_resource("schema.sql") as f:
    conn.executescript(f.read())
매개변수:
  • resource (str) – :attr:`root_path`를 기준으로 한 리소스의 경로입니다.

  • mode (str) – 이 모드로 파일을 엽니다. 읽기 전용만 지원되며, 유효한 값은 "r" (또는 "rt")와 ``”rb”``입니다.

  • encoding (str | None) – 텍스트 모드로 파일을 열 때 사용할 인코딩입니다. 바이너리 모드로 열 경우에는 무시됩니다.

반환 형식:

IO

버전 3.1에서 변경: encoding 파라미터가 추가되었습니다.

open_instance_resource(resource, mode='rb', encoding='utf-8')

애플리케이션의 인스턴스 폴더 :attr:`instance_path`를 기준으로 리소스 파일을 엽니다. :meth:`open_resource`와 달리, 인스턴스 폴더의 파일은 쓰기 모드로 열 수 있습니다.

매개변수:
  • resource (str) – :attr:`instance_path`를 기준으로 한 리소스의 경로입니다.

  • mode (str) – 이 모드로 파일을 엽니다.

  • encoding (str | None) – 텍스트 모드로 파일을 열 때 사용할 인코딩입니다. 바이너리 모드로 열 경우에는 무시됩니다.

반환 형식:

IO

버전 3.1에서 변경: encoding 파라미터가 추가되었습니다.

create_jinja_environment()

:attr:`jinja_options`와 애플리케이션의 다양한 Jinja 관련 메서드를 기반으로 Jinja 환경을 생성합니다. 이 작업 이후에 :attr:`jinja_options`를 변경해도 영향을 미치지 않습니다. 또한 환경에 Flask 관련 글로벌 변수와 필터를 추가합니다.

Changelog

버전 0.11에서 변경: Environment.auto_reload``는 ``TEMPLATES_AUTO_RELOAD 구성 옵션에 따라 설정됩니다.

Added in version 0.5.

반환 형식:

Environment

create_url_adapter(request)

주어진 요청에 대해 URL 어댑터를 생성합니다. URL 어댑터는 요청 컨텍스트가 아직 설정되지 않은 시점에 생성되므로 요청이 명시적으로 전달됩니다.

버전 3.1에서 변경: SERVER_NAME`이 설정된 경우, ``subdomain_matching`host_matching 모두 해당 도메인으로만 요청을 제한하지 않습니다.

Changelog

버전 1.0에서 변경: :data:`SERVER_NAME`은 더 이상 서브 도메인 매칭을 암시적으로 활성화하지 않습니다. 대신 :attr:`subdomain_matching`을 사용하세요.

버전 0.9에서 변경: 이것은 URL 어댑터가 애플리케이션 컨텍스트를 위해 생성될 때 요청 외부에서도 호출할 수 있습니다.

Added in version 0.6.

매개변수:

request (Request | None)

반환 형식:

MapAdapter | None

update_template_context(context)

템플릿 컨텍스트에 자주 사용되는 변수를 업데이트합니다. 이 작업은 request, session, config, g를 템플릿 컨텍스트에 추가하며, 템플릿 컨텍스트 프로세서가 추가하고자 하는 모든 값도 포함됩니다. Flask 0.6부터는 컨텍스트 프로세서가 동일한 키로 값을 반환하더라도 컨텍스트의 기존 값은 덮어쓰지 않는다는 점에 유의하세요.

매개변수:

context (dict[str, Any]) – 컨텍스트는 딕셔너리 형태로 제공되며, 여기에 추가 변수를 더해 실시간으로 업데이트됩니다.

반환 형식:

None

make_shell_context()

이 애플리케이션을 위한 인터랙티브 셸의 컨텍스트를 반환합니다. 이 과정에서 등록된 모든 셸 컨텍스트 프로세서가 실행됩니다.

Changelog

Added in version 0.11.

반환 형식:

dict[str, Any]

run(host=None, port=None, debug=None, load_dotenv=True, **options)

애플리케이션을 로컬 개발 서버에서 실행합니다.

``run()``은 프로덕션 환경에서 사용하지 마세요. 이 함수는 프로덕션 서버의 보안 및 성능 요구 사항을 충족하도록 설계되지 않았습니다. 대신, WSGI 서버에 대한 권장 사항은 :doc:`/deploying/index`를 참조하세요.

debug 플래그가 설정된 경우, 서버는 코드 변경 시 자동으로 다시 로드되며, 예외가 발생했을 때 디버거를 표시합니다.

애플리케이션을 디버그 모드로 실행하되 인터랙티브 디버거에서 코드 실행을 비활성화하고 싶다면, 파라미터로 ``use_evalex=False``를 전달하면 됩니다. 이렇게 하면 디버거의 트레이스백 화면은 활성 상태로 유지되지만 코드 실행은 비활성화됩니다.

이 함수는 자동 재로딩이 제대로 지원되지 않기 때문에 개발 목적으로 사용하는 것이 권장되지 않습니다. 대신 flask 명령줄 스크립트의 run 기능을 사용하는 것이 좋습니다.

주의할 점

Flask는 디버그 모드가 아닐 경우 일반적인 오류 페이지로 서버 오류를 숨깁니다. 따라서 코드 재로딩 없이 인터랙티브 디버거만 활성화하려면, :meth:`run`을 호출할 때 ``debug=True``와 ``use_reloader=False``를 설정해야 합니다. 디버그 모드가 아닌 상태에서 ``use_debugger``를 ``True``로 설정하면 예외를 잡을 수 없습니다. 이는 디버거가 잡을 예외가 없기 때문입니다.

매개변수:
  • host (str | None) – 서버가 요청을 수신할 호스트 이름입니다. 외부에서도 서버에 접근 가능하도록 하려면 '0.0.0.0'``으로 설정하세요. 기본값은 ``'127.0.0.1'``이며, ``SERVER_NAME 구성 변수에 호스트가 지정된 경우 해당 값을 사용합니다.

  • port (int | None) – 웹 서버의 포트입니다. 기본값은 5000``이며, ``SERVER_NAME 구성 변수에 포트가 정의되어 있는 경우 해당 값을 사용합니다.

  • debug (bool | None) – 지정된 경우 디버그 모드를 활성화하거나 비활성화합니다. 자세한 내용은 :attr:`debug`를 참조하세요.

  • load_dotenv (bool) – 가장 가까운 .env.flaskenv 파일을 로드하여 환경 변수를 설정합니다. 또한, 첫 번째로 발견된 파일이 위치한 디렉터리로 작업 디렉터리를 변경합니다.

  • options (Any) – 기본 Werkzeug 서버에 전달될 옵션입니다. 자세한 내용은 :func:`werkzeug.serving.run_simple`을 참조하세요.

반환 형식:

None

Changelog

버전 1.0에서 변경: python-dotenv`이 설치되어 있으면 :file:.env` 및 .flaskenv 파일에서 환경 변수를 로드하는 데 사용됩니다.

FLASK_DEBUG 환경 변수는 debug 값을 덮어씁니다.

스레드 모드는 기본적으로 활성화되어 있습니다.

버전 0.10에서 변경: 기본 포트는 이제 SERVER_NAME 변수에서 선택됩니다.

test_client(use_cookies=True, **kwargs)

이 애플리케이션을 위한 테스트 클라이언트를 생성합니다. 단위 테스트에 대한 자세한 정보는 :doc:`/testing`를 참조하세요.

애플리케이션 코드에서 어설션이나 예외를 테스트하려면 app.testing = True로 설정해야 예외가 테스트 클라이언트로 전달됩니다. 그렇지 않으면 예외가 애플리케이션에서 처리되어 테스트 클라이언트에는 보이지 않으며, AssertionError나 다른 예외가 발생했다는 유일한 표시로 500 상태 코드 응답만 반환됩니다. 자세한 내용은 :attr:testing 속성을 참조하세요. 예를 들어:

app.testing = True
client = app.test_client()

테스트 클라이언트는 with 블록 내에서 사용할 수 있으며, 블록이 끝날 때까지 컨텍스트 종료를 지연시킵니다. 이는 테스트를 위해 컨텍스트 로컬에 접근하려는 경우에 유용합니다:

with app.test_client() as c:
    rv = c.get('/?vodka=42')
    assert request.args['vodka'] == '42'

또한 선택적인 키워드 인수를 전달할 수 있으며, 이는 애플리케이션의 test_client_class 생성자에 전달됩니다. 예를 들어:

from flask.testing import FlaskClient

class CustomClient(FlaskClient):
    def __init__(self, *args, **kwargs):
        self._authentication = kwargs.pop("authentication")
        super(CustomClient,self).__init__( *args, **kwargs)

app.test_client_class = CustomClient
client = app.test_client(authentication='Basic ....')

자세한 내용은 :class:`~flask.testing.FlaskClient`를 참조하세요.

Changelog

버전 0.11에서 변경: `**kwargs`가 추가되어 :attr:`test_client_class`의 생성자에 추가적인 키워드 인수를 전달할 수 있게 되었습니다.

Added in version 0.7: use_cookies 파라미터가 추가되었으며, test_client_class 속성을 설정하여 사용될 클라이언트를 재정의할 수 있는 기능이 추가되었습니다.

버전 0.4에서 변경: 클라이언트에서 with 블록 사용을 지원하게 되었습니다.

매개변수:
  • use_cookies (bool)

  • kwargs (t.Any)

반환 형식:

FlaskClient

test_cli_runner(**kwargs)

CLI 명령어 테스트를 위한 CLI 러너를 생성합니다. 자세한 내용은 :ref:`testing-cli`를 참조하세요.

기본적으로 :class:`~flask.testing.FlaskCliRunner`인 :attr:`test_cli_runner_class`의 인스턴스를 반환합니다. Flask 앱 객체는 첫 번째 인수로 전달됩니다.

Changelog

Added in version 1.0.

매개변수:

kwargs (t.Any)

반환 형식:

FlaskCliRunner

handle_http_exception(e)

HTTP 예외를 처리합니다. 기본적으로 등록된 오류 처리기를 호출하고, 예외를 응답으로 반환하는 방식으로 처리됩니다.

Changelog

버전 1.0.3에서 변경: ``RoutingException``은 라우팅 중 슬래시 리다이렉션과 같은 작업에 내부적으로 사용되며, 오류 처리기로 전달되지 않습니다.

버전 1.0에서 변경: 예외는 코드와 MRO(메서드 해석 순서)에 따라 조회되므로, ``HTTPException``의 서브클래스는 기본 ``HTTPException``에 대한 포괄적인 핸들러로 처리할 수 있습니다.

Added in version 0.3.

매개변수:

e (HTTPException)

반환 형식:

HTTPException | ft.ResponseReturnValue

handle_user_exception(e)

이 메서드는 처리해야 할 예외가 발생할 때마다 호출됩니다. 특별한 경우로는 HTTPException`이 있으며, 이는 :meth:`handle_http_exception 메서드로 전달됩니다. 이 함수는 응답 값을 반환하거나 동일한 트레이스백을 가진 예외를 다시 발생시킵니다.

Changelog

버전 1.0에서 변경: ``form``과 같은 요청 데이터에서 발생한 키 오류는 디버그 모드에서 일반적인 잘못된 요청 메시지 대신 잘못된 키를 표시합니다.

Added in version 0.7.

매개변수:

e (Exception)

반환 형식:

HTTPException | ft.ResponseReturnValue

handle_exception(e)

오류 처리기와 연결되지 않았거나 오류 처리기에서 발생한 예외를 처리합니다. 이 경우 항상 500 ``InternalServerError``가 발생합니다.

항상 got_request_exception 신호를 보냅니다.

:data:`PROPAGATE_EXCEPTIONS`가 ``True``인 경우(예: 디버그 모드에서), 오류는 다시 발생하여 디버거가 이를 표시할 수 있게 됩니다. 그렇지 않으면 원래 예외가 로그에 기록되고, :exc:`~werkzeug.exceptions.InternalServerError`가 반환됩니다.

InternalServerError 또는 ``500``에 대한 오류 처리기가 등록되어 있으면, 해당 처리기가 사용됩니다. 일관성을 위해, 처리기는 항상 ``InternalServerError``를 받게 됩니다. 원래 처리되지 않은 예외는 ``e.original_exception``으로 접근할 수 있습니다.

Changelog

버전 1.1.0에서 변경: 항상 InternalServerError 인스턴스를 처리기로 전달하며, ``original_exception``을 처리되지 않은 오류로 설정합니다.

버전 1.1.0에서 변경: after_request 함수와 기타 마무리 작업은 오류 처리기가 없을 때 기본 500 응답에도 수행됩니다.

Added in version 0.3.

매개변수:

e (Exception)

반환 형식:

Response

log_exception(exc_info)

예외를 로그에 기록합니다. 이는 디버깅이 비활성화된 상태에서 :meth:`handle_exception`이 호출될 때, 그리고 오류 처리기가 호출되기 직전에 실행됩니다. 기본 구현은 예외를 :attr:`logger`에 오류로 기록합니다.

Changelog

Added in version 0.8.

매개변수:

exc_info (tuple[type, BaseException, TracebackType] | tuple[None, None, None])

반환 형식:

None

dispatch_request()

요청을 처리합니다. URL을 매칭하고 뷰 또는 오류 처리기의 반환 값을 반환합니다. 반환 값이 반드시 응답 객체일 필요는 없습니다. 반환 값을 적절한 응답 객체로 변환하려면 :func:`make_response`를 호출해야 합니다.

Changelog

버전 0.7에서 변경: 이제 예외 처리를 수행하지 않습니다. 이 코드는 새로운 :meth:`full_dispatch_request`로 이동되었습니다.

반환 형식:

ft.ResponseReturnValue

full_dispatch_request()

요청을 처리하고, 그 위에 요청 전후 처리 및 HTTP 예외 처리와 오류 처리를 수행합니다.

Changelog

Added in version 0.7.

반환 형식:

Response

make_default_options_response()

이 메서드는 기본 OPTIONS 응답을 생성하기 위해 호출됩니다. 이 동작은 서브클래싱을 통해 변경하여 OPTIONS 응답의 기본 동작을 수정할 수 있습니다.

Changelog

Added in version 0.7.

반환 형식:

Response

ensure_sync(func)

이 함수가 WSGI 워커에 대해 동기식 함수임을 보장합니다. 일반 def 함수는 그대로 반환되며, async def 함수는 응답을 기다리도록 랩핑됩니다.

이 메서드를 오버라이드하여 앱이 비동기 뷰를 실행하는 방식을 변경할 수 있습니다.

Changelog

Added in version 2.0.

매개변수:

func (Callable[[...], Any])

반환 형식:

Callable[[…], Any]

async_to_sync(func)

코루틴 함수를 실행할 동기 함수를 반환합니다.

result = app.async_to_sync(func)(*args, **kwargs)

이 메서드를 오버라이드하여 앱이 비동기 코드를 동기적으로 호출할 수 있도록 변환하는 방식을 변경할 수 있습니다.

Changelog

Added in version 2.0.

매개변수:

func (Callable[[...], Coroutine[Any, Any, Any]])

반환 형식:

Callable[[…], Any]

url_for(endpoint, *, _anchor=None, _method=None, _scheme=None, _external=None, **values)

주어진 엔드포인트와 값을 사용하여 URL을 생성합니다.

이 함수는 :func:`flask.url_for`에 의해 호출되며, 직접 호출할 수도 있습니다.

*엔드포인트*는 URL 규칙의 이름으로, 보통 @app.route() <route>`로 추가되며, 일반적으로 함수의 이름과 같습니다. :class:`~flask.Blueprint`에서 정의된 라우트는 엔드포인트 앞에 블루프린트의 이름을 `().``으로 구분하여 추가합니다.

일부 경우, 예를 들어 이메일 메시지에서는 URL에 스킴과 도메인이 포함되기를 원할 수 있습니다. 예를 들어 ``https://example.com/hello``와 같은 형식입니다. 활성화된 요청이 아닐 경우, URL은 기본적으로 외부 URL로 처리되지만, Flask가 어떤 도메인을 사용할지 알 수 있도록 :data:`SERVER_NAME`을 설정해야 합니다. 또한 :data:`APPLICATION_ROOT`와 :data:`PREFERRED_URL_SCHEME`도 필요에 따라 설정해야 합니다. 이 설정은 활성 요청이 아닐 때만 사용됩니다.

함수는 :meth:`url_defaults`로 데코레이터를 적용하여 URL이 생성되기 전에 키워드 인수를 수정할 수 있습니다.

생성이 실패할 경우, 예를 들어 알 수 없는 엔드포인트나 잘못된 값이 주어졌을 때, 애플리케이션의 handle_url_build_error() 메서드가 호출됩니다. 메서드가 문자열을 반환하면 그 값이 반환되고, 그렇지 않으면 :exc:`~werkzeug.routing.BuildError`가 발생합니다.

매개변수:
  • endpoint (str) – 생성할 URL과 연관된 엔드포인트 이름입니다. 만약 이 이름이 ``.``으로 시작하면, 현재 블루프린트 이름(있을 경우)이 사용됩니다.

  • _anchor (str | None) – 주어진 경우, 이를 #anchor 형태로 URL에 추가합니다.

  • _method (str | None) – 주어진 경우, 이 메서드와 관련된 엔드포인트의 URL을 생성합니다.

  • _scheme (str | None) – 주어진 경우, 외부 URL일 경우 이 스킴이 URL에 적용됩니다.

  • _external (bool | None) – 주어진 경우, URL이 내부 URL로 설정될지(False) 또는 외부 URL로 설정될지(True)를 선호합니다. 외부 URL은 스킴과 도메인을 포함합니다. 활성 요청이 아닐 때는 기본적으로 URL이 외부 URL로 처리됩니다.

  • values (Any) – URL 규칙의 변수 부분에 사용할 값들입니다. 알 수 없는 키는 쿼리 문자열 인수로 추가되며, 예를 들어 ``?a=b&c=d``와 같은 형식이 됩니다.

반환 형식:

str

Changelog

Added in version 2.2: 이 메서드는 ``flask.url_for``에서 이동된 것으로, ``flask.url_for``가 이 메서드를 호출합니다.

make_response(rv)

뷰 함수의 반환 값을 :attr:`response_class`의 인스턴스로 변환합니다.

매개변수:

rv (ft.ResponseReturnValue) – 뷰 함수의 반환 값은 응답이어야 합니다. 반환 값이 None``이거나 함수가 반환 없이 끝나는 것은 허용되지 않습니다. ``view_rv``에 허용되는 유형은 다음과 같습니다: ``str``은 문자열이 UTF-8로 인코딩되어 본문으로 사용된 응답 객체가 생성됩니다. ``bytes``는 바이트가 본문으로 사용된 응답 객체가 생성됩니다. ``dict``는 반환 전에 JSON으로 변환되는 딕셔너리입니다. ``list``는 반환 전에 JSON으로 변환되는 리스트입니다. ``generator 또는 iterator``는 ``str 또는 bytes``를 반환하여 스트리밍 응답으로 사용되는 제너레이터입니다. ``tuple``은 ``(body, status, headers), (body, status), 또는 (body, headers) 형식으로, 여기서 body``는 위에서 허용된 다른 유형 하나, ``status``는 문자열 또는 정수, ``headers``는 딕셔너리 또는 ``(key, value) 튜플의 리스트입니다. 만약 ``body``가 response_class 인스턴스이면, ``status``는 기존 값을 덮어쓰고 ``headers``는 확장됩니다. response_class`는 객체가 변경되지 않고 그대로 반환됩니다. 다른 :class:`~werkzeug.wrappers.Response 클래스는 객체가 :attr:`response_class`로 강제 변환됩니다. :func:`callable`은 함수가 WSGI 애플리케이션으로 호출되어 그 결과가 응답 객체를 생성하는 데 사용됩니다.

반환 형식:

Response

Changelog

버전 2.2에서 변경: 제너레이터는 스트리밍 응답으로 변환되며, 리스트는 JSON 응답으로 변환됩니다.

버전 1.1에서 변경: 딕셔너리는 JSON 응답으로 변환됩니다.

버전 0.9에서 변경: 이전에 튜플은 응답 객체의 인수로 해석되었습니다.

preprocess_request()

요청이 디스패치되기 전에 호출됩니다. 애플리케이션과 현재 블루프린트(있는 경우)에 등록된 :attr:`url_value_preprocessors`를 호출한 후, 애플리케이션과 블루프린트에 등록된 :attr:`before_request_funcs`를 호출합니다.

before_request() 핸들러 중 하나가 ``None``이 아닌 값을 반환하면, 해당 값은 뷰 함수의 반환 값처럼 처리되며, 이후 요청 처리는 중단됩니다.

반환 형식:

ft.ResponseReturnValue | None

process_response(response)

응답 객체가 WSGI 서버로 전달되기 전에 수정하려면 이 메서드를 오버라이드할 수 있습니다. 기본적으로, 이 메서드는 모든 after_request() 데코레이터가 적용된 함수를 호출합니다.

Changelog

버전 0.5에서 변경: Flask 0.5부터 요청 후 실행을 위해 등록된 함수들은 등록된 순서의 역순으로 호출됩니다.

매개변수:

response (Response) – response_class 객체.

반환:

새로운 응답 객체 또는 동일한 객체를 반환하며, 반드시 :attr:`response_class`의 인스턴스여야 합니다.

반환 형식:

Response

do_teardown_request(exc=_sentinel)

요청이 디스패치되고 응답이 반환된 후, 요청 컨텍스트가 제거되기 직전에 호출됩니다.

요청을 처리한 블루프린트가 있을 경우, teardown_request`로 데코레이터된 모든 함수와 :meth:`Blueprint.teardown_request`를 호출합니다. 마지막으로 :data:`request_tearing_down() 신호가 전송됩니다.

이 메서드는 :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`에 의해 호출됩니다. 테스트 중에는 리소스에 대한 접근을 유지하기 위해 호출이 지연될 수 있습니다.

매개변수:

exc (BaseException | None) – 요청을 디스패치하는 동안 발생한 처리되지 않은 예외입니다. 전달되지 않은 경우, 현재 예외 정보를 통해 감지됩니다. 각 teardown 함수에 전달됩니다.

반환 형식:

None

Changelog

버전 0.9에서 변경: exc 인수가 추가되었습니다.

do_teardown_appcontext(exc=_sentinel)

애플리케이션 컨텍스트가 제거되기 직전에 호출됩니다.

요청을 처리할 때, 애플리케이션 컨텍스트는 요청 컨텍스트가 제거된 후에 제거됩니다. 자세한 내용은 :meth:`do_teardown_request`를 참조하세요.

teardown_appcontext`로 데코레이터된 모든 함수를 호출한 다음, :data:`appcontext_tearing_down() 신호를 전송합니다.

이 메서드는 :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`에 의해 호출됩니다.

Changelog

Added in version 0.9.

매개변수:

exc (BaseException | None)

반환 형식:

None

app_context()

``with` 블록에서 사용하여 컨텍스트를 푸시하면, :data:`current_app`이 해당 애플리케이션을 가리키도록 설정됩니다.

애플리케이션 컨텍스트는 요청 처리 시 :meth:`RequestContext.push() <flask.ctx.RequestContext.push>`에 의해 자동으로 푸시되며, CLI 명령 실행 시에도 자동으로 푸시됩니다. 이 메서드는 이러한 상황 외부에서 컨텍스트를 수동으로 생성할 때 사용됩니다.

with app.app_context():
    init_db()

자세한 내용은 :doc:`/appcontext`를 참조하세요.

Changelog

Added in version 0.9.

반환 형식:

AppContext

request_context(environ)

``with` 블록을 사용하여 컨텍스트를 푸시하면 :data:`request`가 해당 요청을 가리키도록 설정됩니다.

자세한 내용은 :doc:`/reqcontext`를 참조하세요.

일반적으로 이 메서드를 직접 호출하지 않아야 합니다. 요청 컨텍스트는 요청을 처리할 때 :meth:`wsgi_app`에 의해 자동으로 푸시됩니다. 이 메서드 대신 :meth:`test_request_context`를 사용하여 환경과 컨텍스트를 생성하세요.

매개변수:

environ (WSGIEnvironment) – WSGI 환경

반환 형식:

RequestContext

test_request_context(*args, **kwargs)

주어진 값으로 생성된 WSGI 환경을 기반으로 :class:`~flask.ctx.RequestContext`를 생성합니다. 이는 주로 테스트 중에 유용하며, 전체 요청을 디스패치하지 않고 요청 데이터를 사용하는 함수를 실행하고자 할 때 사용할 수 있습니다.

자세한 내용은 :doc:`/reqcontext`를 참조하세요.

with 블록을 사용하여 컨텍스트를 푸시하면 :data:`request`가 생성된 환경의 요청을 가리키도록 설정됩니다.

with app.test_request_context(...):
    generate_report()

셸을 사용할 때는 들여쓰기를 피하기 위해 컨텍스트를 수동으로 푸시하고 팝하는 것이 더 편리할 수 있습니다.

ctx = app.test_request_context(...)
ctx.push()
...
ctx.pop()

Werkzeug의 :class:`~werkzeug.test.EnvironBuilder`와 동일한 인수를 사용하며, 애플리케이션에서 일부 기본값을 제공합니다. 사용 가능한 대부분의 인수는 링크된 Werkzeug 문서를 참조하세요. Flask에 특화된 동작은 여기에 나열되어 있습니다.

매개변수:
  • path – 요청되는 URL 경로입니다.

  • base_url – 앱이 제공되는 기준 URL로, path``는 이에 상대적입니다. 지정되지 않은 경우, :data:`PREFERRED_URL_SCHEME`, ``subdomain, SERVER_NAME, 및 :data:`APPLICATION_ROOT`를 기반으로 생성됩니다.

  • subdomain – :data:`SERVER_NAME`에 추가할 서브도메인 이름입니다.

  • url_schemePREFERRED_URL_SCHEME 대신 사용할 스킴입니다.

  • data – 요청 본문으로, 문자열 또는 폼 키와 값으로 이루어진 딕셔너리 형태일 수 있습니다.

  • json – 지정된 경우, 이는 JSON으로 직렬화되어 ``data``로 전달됩니다. 또한 ``content_type``의 기본값은 ``application/json``으로 설정됩니다.

  • args (Any) – :class:`~werkzeug.test.EnvironBuilder`에 전달되는 기타 위치 인수입니다.

  • kwargs (Any) – :class:`~werkzeug.test.EnvironBuilder`에 전달되는 기타 키워드 인수입니다.

반환 형식:

RequestContext

wsgi_app(environ, start_response)

실제 WSGI 애플리케이션입니다. :meth:`__call__`에서 구현되지 않으므로, 미들웨어를 적용해도 앱 객체에 대한 참조를 잃지 않습니다. 대신 다음과 같이 처리합니다:

app = MyMiddleware(app)

다음과 같이 처리하는 것이 더 나은 방법입니다:

app.wsgi_app = MyMiddleware(app.wsgi_app)

이렇게 하면 원래의 애플리케이션 객체를 그대로 유지할 수 있으며, 해당 객체의 메서드를 계속 호출할 수 있습니다.

Changelog

버전 0.7에서 변경: 요청 및 애플리케이션 컨텍스트에 대한 테어다운 이벤트는 처리되지 않은 오류가 발생하더라도 호출됩니다. 그러나 디스패치 중 오류가 발생한 시점에 따라 다른 이벤트는 호출되지 않을 수 있습니다. 자세한 내용은 :ref:`callbacks-and-errors`를 참조하세요.

매개변수:
  • environ (WSGIEnvironment) – WSGI 환경.

  • start_response (StartResponse) – 상태 코드, 헤더 목록, 선택적인 예외 컨텍스트를 받아 응답을 시작하는 호출 가능한 객체입니다.

반환 형식:

cabc.Iterable[bytes]

aborter_class

:py:class:`~werkzeug.exceptions.Aborter`의 별칭

add_template_filter(f, name=None)

사용자 정의 템플릿 필터를 등록합니다. template_filter() 데코레이터와 동일하게 작동합니다.

매개변수:
  • name (str | None) – 필터의 선택적 이름으로, 지정하지 않으면 함수 이름이 사용됩니다.

  • f (Callable[[...], Any])

반환 형식:

None

add_template_global(f, name=None)

사용자 정의 템플릿 글로벌 함수를 등록합니다. template_global() 데코레이터와 동일하게 작동합니다.

Changelog

Added in version 0.10.

매개변수:
  • name (str | None) – 글로벌 함수의 선택적 이름으로, 지정하지 않으면 함수 이름이 사용됩니다.

  • f (Callable[[...], Any])

반환 형식:

None

add_template_test(f, name=None)

사용자 정의 템플릿 테스트를 등록합니다. template_test() 데코레이터와 동일하게 작동합니다.

Changelog

Added in version 0.10.

매개변수:
  • name (str | None) – 테스트의 선택적 이름으로, 지정하지 않으면 함수 이름이 사용됩니다.

  • f (Callable[[...], bool])

반환 형식:

None

add_url_rule(rule, endpoint=None, view_func=None, provide_automatic_options=None, **options)

수신 요청을 라우팅하고 URL을 빌드하기 위한 규칙을 등록합니다. route() 데코레이터는 view_func 인수와 함께 이 메서드를 호출하는 단축키입니다. 이 두 코드는 동일합니다:

@app.route("/")
def index():
    ...
def index():
    ...

app.add_url_rule("/", view_func=index)

:ref:`url-route-registrations`를 참조하세요.

endpoint 파라미터가 전달되지 않으면, 라우트의 엔드포인트 이름은 뷰 함수의 이름으로 기본 설정됩니다. 만약 해당 엔드포인트에 이미 함수가 등록되어 있으면 오류가 발생합니다.

methods 파라미터의 기본값은 ``[“GET”]``입니다. ``HEAD``는 항상 자동으로 추가되며, ``OPTIONS``는 기본적으로 자동으로 추가됩니다.

``view_func``는 반드시 전달될 필요는 없지만, 규칙이 라우팅에 참여해야 한다면, endpoint() 데코레이터를 사용하여 어떤 시점에서 뷰 함수와 엔드포인트 이름을 연결해야 합니다.

app.add_url_rule("/", endpoint="index")

@app.endpoint("index")
def index():
    ...

view_func``에 ``required_methods 속성이 있으면, 해당 메서드가 전달된 메서드와 자동으로 추가된 메서드에 포함됩니다. 만약 provide_automatic_methods 속성이 있으면, 파라미터가 전달되지 않았을 때 기본값으로 사용됩니다.

매개변수:
  • rule (str) – URL 규칙 문자열입니다.

  • endpoint (str | None) – 규칙과 뷰 함수와 연결할 엔드포인트 이름입니다. 라우팅 및 URL 빌딩 시 사용됩니다. 기본값은 ``view_func.__name__``입니다.

  • view_func (ft.RouteCallable | None) – 엔드포인트 이름과 연결할 뷰 함수입니다.

  • provide_automatic_options (bool | None) – OPTIONS 메서드를 추가하고, OPTIONS 요청에 자동으로 응답합니다.

  • options (t.Any) – Rule 객체에 전달되는 추가 옵션입니다.

반환 형식:

None

after_request(f)

이 객체에 대한 각 요청 후 실행될 함수를 등록합니다.

함수는 응답 객체와 함께 호출되며, 응답 객체를 반환해야 합니다. 이를 통해 함수는 응답이 전송되기 전에 응답을 수정하거나 교체할 수 있습니다.

함수가 예외를 발생시키면 나머지 after_request 함수는 호출되지 않습니다. 따라서 리소스를 닫는 등 반드시 실행해야 하는 작업에는 이 방법을 사용하지 않아야 합니다. 그런 작업에는 :meth:`teardown_request`를 사용하세요.

이 기능은 앱과 블루프린트 객체 모두에서 사용 가능합니다. 앱에서 사용할 경우, 모든 요청 후에 실행됩니다. 블루프린트에서 사용할 경우, 블루프린트가 처리하는 모든 요청 후에 실행됩니다. 블루프린트에서 모든 요청 후에 실행되도록 등록하려면 :meth:`.Blueprint.after_app_request`를 사용하세요.

매개변수:

f (T_after_request)

반환 형식:

T_after_request

app_ctx_globals_class

:py:class:`~flask.ctx._AppCtxGlobals`의 별칭

auto_find_instance_path()

애플리케이션 클래스의 생성자에 인스턴스 경로가 제공되지 않으면, 해당 경로를 찾으려고 시도합니다. 기본적으로는 주요 파일이나 패키지 옆에 있는 ``instance``라는 폴더의 경로를 계산합니다.

Changelog

Added in version 0.8.

반환 형식:

str

before_request(f)

각 요청 전에 실행될 함수를 등록합니다.

예를 들어, 데이터베이스 연결을 열거나 세션에서 로그인한 사용자를 로드하는 데 사용할 수 있습니다.

@app.before_request
def load_user():
    if "user_id" in session:
        g.user = db.session.get(session["user_id"])

함수는 인수 없이 호출됩니다. 만약 함수가 ``None``이 아닌 값을 반환하면, 그 값은 뷰 함수의 반환 값처럼 처리되며, 이후 요청 처리는 중단됩니다.

이 기능은 앱과 블루프린트 객체 모두에서 사용 가능합니다. 앱에서 사용할 경우, 모든 요청 전에 실행됩니다. 블루프린트에서 사용할 경우, 블루프린트가 처리하는 요청 전에만 실행됩니다. 블루프린트에서 모든 요청에 대해 실행되도록 등록하려면 :meth:`.Blueprint.before_app_request`를 사용하세요.

매개변수:

f (T_before_request)

반환 형식:

T_before_request

config_class

:py:class:`~flask.config.Config`의 별칭

context_processor(f)

템플릿 컨텍스트 프로세서 함수를 등록합니다. 이 함수들은 템플릿 렌더링 전에 실행됩니다. 반환된 딕셔너리의 키는 템플릿에서 사용할 수 있는 변수로 추가됩니다.

이 기능은 앱과 블루프린트 객체 모두에서 사용 가능합니다. 앱에서 사용할 경우, 모든 렌더링된 템플릿에 대해 호출됩니다. 블루프린트에서 사용할 경우, 블루프린트의 뷰에서 렌더링된 템플릿에 대해 호출됩니다. 블루프린트에서 모든 템플릿에 영향을 주도록 등록하려면 :meth:`.Blueprint.app_context_processor`를 사용하세요.

매개변수:

f (T_template_context_processor)

반환 형식:

T_template_context_processor

create_global_jinja_loader()

Jinja2 환경을 위한 로더를 생성합니다. 로더만 오버라이드하고 나머지는 변경하지 않을 수 있습니다. 이 함수를 오버라이드하는 것은 권장되지 않으며, 대신 jinja_loader() 함수를 오버라이드하는 것이 좋습니다.

전역 로더는 애플리케이션과 개별 블루프린트의 로더 사이에서 분배합니다.

Changelog

Added in version 0.7.

반환 형식:

DispatchingJinjaLoader

property debug: bool

디버그 모드가 활성화되어 있는지 여부입니다. ``flask run``을 사용하여 개발 서버를 시작하면 처리되지 않은 예외에 대해 인터랙티브 디버거가 표시되며, 코드 변경 시 서버가 자동으로 다시 로드됩니다. 이는 DEBUG 구성 키와 연결됩니다. 설정이 늦게 이루어지면 예상대로 동작하지 않을 수 있습니다.

프로덕션 환경에서 디버그 모드를 활성화하지 마세요.

기본값: False

delete(rule, **options)

``methods=[“DELETE”]``가 설정된 :meth:`route`의 단축키입니다.

Changelog

Added in version 2.0.

매개변수:
반환 형식:

Callable[[T_route], T_route]

endpoint(endpoint)

주어진 엔드포인트에 대해 뷰 함수를 등록하는 데코레이터입니다. view_func 없이 :meth:`add_url_rule`로 규칙이 추가된 경우 사용됩니다.

app.add_url_rule("/ex", endpoint="example")

@app.endpoint("example")
def example():
    ...
매개변수:

endpoint (str) – 뷰 함수와 연결할 엔드포인트 이름입니다.

반환 형식:

Callable[[F], F]

errorhandler(code_or_exception)

코드나 예외 클래스로 오류를 처리할 함수를 등록합니다.

오류 코드를 기준으로 함수를 등록하는 데 사용되는 데코레이터입니다. 예시:

@app.errorhandler(404)
def page_not_found(error):
    return 'This page does not exist', 404

임의의 예외에 대한 핸들러도 등록할 수 있습니다:

@app.errorhandler(DatabaseError)
def special_exception_handler(error):
    return 'Database connection failed', 500

이 기능은 앱과 블루프린트 객체 모두에서 사용 가능합니다. 앱에서 사용할 경우, 모든 요청에서 발생하는 오류를 처리할 수 있습니다. 블루프린트에서 사용할 경우, 블루프린트가 처리하는 요청에서 발생하는 오류를 처리할 수 있습니다. 블루프린트에서 모든 요청에 대해 오류를 처리하려면 :meth:`.Blueprint.app_errorhandler`를 사용하세요.

Changelog

Added in version 0.7: 애플리케이션 전체 오류 핸들러를 위해 :attr:`error_handler_spec`을 직접 수정하는 대신 :meth:`register_error_handler`를 사용하세요.

Added in version 0.7: 이제 HTTPException 클래스의 서브클래스일 필요가 없는 사용자 정의 예외 유형도 추가로 등록할 수 있습니다.

매개변수:

code_or_exception (type[Exception] | int) – 핸들러에 대한 코드로서의 정수 값 또는 임의의 예외입니다

반환 형식:

Callable[[T_error_handler], T_error_handler]

get(rule, **options)

``methods=[“GET”]``가 설정된 :meth:`route`의 단축키입니다.

Changelog

Added in version 2.0.

매개변수:
반환 형식:

Callable[[T_route], T_route]

handle_url_build_error(error, endpoint, values)

BuildError`가 발생했을 :meth:.url_for`에 의해 호출됩니다. 이 함수가 값을 반환하면 ``url_for``에서 그 값을 반환하고, 그렇지 않으면 오류가 다시 발생합니다.

url_build_error_handlers`에 있는 함수는 ``error`, endpoint, ``values``를 인수로 받아 호출됩니다. 만약 함수가 ``None``을 반환하거나 ``BuildError``를 발생시키면 건너뛰고, 그렇지 않으면 반환 값이 ``url_for``에 의해 반환됩니다.

매개변수:
  • error (BuildError) – 현재 처리 중인 활성 ``BuildError``입니다.

  • endpoint (str) – 생성 중인 엔드포인트입니다.

  • values (dict[str, Any]) – ``url_for``에 전달된 키워드 인수입니다.

반환 형식:

str

property has_static_folder: bool

``static_folder``가 설정된 경우 ``True``입니다.

Changelog

Added in version 0.5.

inject_url_defaults(endpoint, values)

주어진 엔드포인트에 대한 URL 기본값을 전달된 값의 딕셔너리에 직접 주입합니다. 이는 내부적으로 사용되며 URL 빌딩 시 자동으로 호출됩니다.

Changelog

Added in version 0.7.

매개변수:
반환 형식:

None

iter_blueprints()

블루프린트가 등록된 순서대로 모든 블루프린트를 순회합니다.

Changelog

Added in version 0.11.

반환 형식:

t.ValuesView[Blueprint]

property jinja_env: Environment

템플릿을 로드하는 데 사용되는 Jinja 환경입니다.

이 속성이 처음 접근될 때 환경이 생성됩니다. 이후 :attr:`jinja_options`를 변경해도 효과가 없습니다.

jinja_environment

:py:class:`~flask.templating.Environment`의 별칭

property jinja_loader: BaseLoader | None

이 객체의 템플릿을 위한 Jinja 로더입니다. 기본적으로 이는 설정된 경우 template_folder`를 위한 :class:`jinja2.loaders.FileSystemLoader 클래스입니다.

Changelog

Added in version 0.5.

jinja_options: dict[str, t.Any] = {}

create_jinja_environment`에서 Jinja 환경에 전달되는 옵션입니다. 환경이 생성된 후에 옵션을 변경( :attr:`jinja_env() 접근)해도 효과가 없습니다.

Changelog

버전 1.1.0에서 변경: 이것은 ImmutableDict 대신 ``dict``로 되어 있어 더 쉽게 구성할 수 있습니다.

json_provider_class

:py:class:`~flask.json.provider.DefaultJSONProvider`의 별칭

property logger: Logger

앱을 위한 표준 Python :class:`~logging.Logger`로, 이름은 :attr:`name`과 동일합니다.

디버그 모드에서는 로거의 :attr:`~logging.Logger.level`이 :data:`~logging.DEBUG`로 설정됩니다.

핸들러가 구성되지 않은 경우, 기본 핸들러가 추가됩니다. 자세한 내용은 :doc:`/logging`을 참조하세요.

Changelog

버전 1.1.0에서 변경: 로거는 ``”flask.app”``을 하드코딩하는 대신 :attr:`name`과 동일한 이름을 사용합니다.

버전 1.0.0에서 변경: 동작이 간소화되었습니다. 로거는 항상 ``”flask.app”``으로 이름이 설정됩니다. 레벨은 구성 시에만 설정되며, 매번 ``app.debug``를 확인하지 않습니다. 하나의 형식만 사용되며, ``app.debug``에 따라 다른 형식은 사용되지 않습니다. 핸들러는 제거되지 않으며, 핸들러가 이미 구성되지 않은 경우에만 추가됩니다.

Added in version 0.3.

make_aborter()

:attr:`aborter`에 할당할 객체를 생성합니다. 이 객체는 :func:`flask.abort`에 의해 HTTP 오류를 발생시키는 데 사용되며, 직접 호출할 수도 있습니다.

기본적으로, 이는 :attr:`aborter_class`의 인스턴스를 생성하며, 기본값은 :class:`werkzeug.exceptions.Aborter`입니다.

Changelog

Added in version 2.2.

반환 형식:

Aborter

make_config(instance_relative=False)

Flask 생성자에서 config 속성을 생성하는 데 사용됩니다. instance_relative 파라미터는 Flask의 생성자에서 전달되며(이름은 instance_relative_config), config가 인스턴스 경로 또는 애플리케이션의 루트 경로에 상대적인지 여부를 나타냅니다.

Changelog

Added in version 0.8.

매개변수:

instance_relative (bool)

반환 형식:

Config

property name: str

애플리케이션의 이름입니다. 일반적으로 이는 임포트 이름이지만, 임포트 이름이 `main`인 경우 실행 파일에서 추측됩니다. 이 이름은 Flask가 애플리케이션의 이름을 필요로 할 때 표시 이름으로 사용됩니다. 이 값을 변경하려면 설정하고 재정의할 수 있습니다.

Changelog

Added in version 0.8.

patch(rule, **options)

``methods=[“PATCH”]``가 설정된 :meth:`route`의 단축키입니다.

Changelog

Added in version 2.0.

매개변수:
반환 형식:

Callable[[T_route], T_route]

permanent_session_lifetime

영구적인 세션의 만료 날짜를 설정하는 데 사용되는 :class:~datetime.timedelta입니다. 기본값은 31일로, 이는 영구적인 세션이 약 한 달 동안 유지되도록 합니다.

이 속성은 PERMANENT_SESSION_LIFETIME 구성 키로 config에서 설정할 수도 있습니다. 기본값은 ``timedelta(days=31)``입니다

post(rule, **options)

:meth:`route`에 대한 ``methods=[“POST”]``가 설정된 단축키입니다.

Changelog

Added in version 2.0.

매개변수:
반환 형식:

Callable[[T_route], T_route]

put(rule, **options)

:meth:`route`에 대한 ``methods=[“PUT”]``가 설정된 단축키입니다.

Changelog

Added in version 2.0.

매개변수:
반환 형식:

Callable[[T_route], T_route]

redirect(location, code=302)

리다이렉션 응답 객체를 생성합니다.

이 함수는 :func:`flask.redirect`에 의해 호출되며, 직접 호출할 수도 있습니다.

매개변수:
  • location (str) – 리다이렉션할 URL입니다.

  • code (int) – 리다이렉션의 상태 코드입니다.

반환 형식:

BaseResponse

Changelog

Added in version 2.2: ``flask.redirect``에서 이동된 것으로, 이 메서드는 ``flask.redirect``가 호출합니다.

register_blueprint(blueprint, **options)

애플리케이션에 :class:`~flask.Blueprint`를 등록합니다. 이 메서드에 전달된 키워드 인수는 블루프린트에 설정된 기본값을 덮어씁니다.

블루프린트가 애플리케이션의 blueprints`에 등록된 블루프린트의 :meth:`~flask.Blueprint.register 메서드를 호출합니다.

매개변수:
  • blueprint (Blueprint) – 등록할 블루프린트입니다.

  • url_prefix – 블루프린트의 라우트는 이 값으로 접두사가 붙습니다.

  • subdomain – 블루프린트의 라우트는 이 서브도메인에서만 일치합니다.

  • url_defaults – 블루프린트의 라우트는 이 기본값을 뷰 인수로 사용합니다.

  • options (t.Any) – 추가적인 키워드 인수는 record 콜백에서 접근할 수 있습니다.

반환 형식:

None

Changelog

버전 2.0.1에서 변경: name 옵션을 사용하여 블루프린트가 등록될 이름을 변경할 수 있습니다. 이 방법을 통해 동일한 블루프린트를 여러 번 등록하고, ``url_for``에서 고유한 이름을 사용할 수 있습니다.

Added in version 0.7.

register_error_handler(code_or_exception, f)

비데코레이터 방식에서 사용하기 더 직관적인 오류 처리 함수입니다.

Changelog

Added in version 0.7.

매개변수:
반환 형식:

None

route(rule, **options)

주어진 URL 규칙과 옵션으로 뷰 함수를 등록하는 데코레이터입니다. :meth:`add_url_rule`을 호출하며, 구현에 대한 더 많은 세부사항은 여기에 나와 있습니다.

@app.route("/")
def index():
    return "Hello, World!"

:ref:`url-route-registrations`를 참조하세요.

라우트에 대한 엔드포인트 이름은 endpoint 파라미터가 전달되지 않으면 뷰 함수의 이름으로 기본 설정됩니다.

methods 파라미터는 기본값이 ``[“GET”]``입니다. ``HEAD``와 ``OPTIONS``는 자동으로 추가됩니다.

매개변수:
  • rule (str) – URL 규칙 문자열입니다.

  • options (Any) – Rule 객체에 전달되는 추가 옵션입니다.

반환 형식:

Callable[[T_route], T_route]

secret_key

비밀 키가 설정되면, 암호화 구성 요소가 이를 사용하여 쿠키와 다른 항목을 서명할 수 있습니다. 보안 쿠키를 사용하려면 복잡한 랜덤 값을 설정하세요.

이 속성은 SECRET_KEY 구성 키로부터 config에서 설정할 수도 있습니다. 기본값은 ``None``입니다.

select_jinja_autoescape(filename)

주어진 템플릿 이름에 대해 자동 이스케이프가 활성화되어야 하면 ``True``를 반환합니다. 템플릿 이름이 주어지지 않으면, ``True``를 반환합니다.

Changelog

버전 2.2에서 변경: .svg 파일에 대해 자동 이스케이핑이 기본적으로 활성화됩니다.

Added in version 0.5.

매개변수:

filename (str)

반환 형식:

bool

shell_context_processor(f)

셸 컨텍스트 프로세서 함수를 등록합니다.

Changelog

Added in version 0.11.

매개변수:

f (T_shell_context_processor)

반환 형식:

T_shell_context_processor

should_ignore_error(error)

테어다운 시스템에 따라 오류가 무시되어야 하는지 여부를 확인하는 데 호출됩니다. 이 함수가 ``True``를 반환하면 테어다운 핸들러는 오류를 전달하지 않습니다.

Changelog

Added in version 0.10.

매개변수:

error (BaseException | None)

반환 형식:

bool

property static_folder: str | None

구성된 정적 폴더의 절대 경로입니다. 정적 폴더가 설정되지 않았다면 ``None``입니다.

property static_url_path: str | None

정적 라우트가 접근 가능한 URL 접두사입니다.

초기화 중에 구성되지 않은 경우, :attr:`static_folder`에서 유도됩니다.

teardown_appcontext(f)

애플리케이션 컨텍스트가 팝될 때 호출될 함수를 등록합니다. 애플리케이션 컨텍스트는 각 요청의 요청 컨텍스트가 끝난 후, CLI 명령어가 끝난 후, 또는 수동으로 푸시된 컨텍스트가 끝날 때 팝됩니다.

with app.app_context():
    ...

with 블록이 종료되면(또는 ``ctx.pop()``이 호출되면) 테어다운 함수는 앱 컨텍스트가 비활성화되기 직전에 호출됩니다. 요청 컨텍스트가 애플리케이션 컨텍스트를 관리하기 때문에 요청 컨텍스트를 팝할 때도 호출됩니다.

예외 처리 핸들러가 등록된 경우 예외가 전달되지 않도록 테어다운 함수가 호출됩니다.

테어다운 함수는 예외를 발생시키지 않도록 해야 합니다. 실패할 수 있는 코드를 실행할 경우 try/except 블록으로 해당 코드를 감싸고, 오류를 기록해야 합니다.

테어다운 함수의 반환 값은 무시됩니다.

Changelog

Added in version 0.9.

매개변수:

f (T_teardown)

반환 형식:

T_teardown

teardown_request(f)

요청 컨텍스트가 팝될 때 호출될 함수를 등록합니다. 일반적으로 각 요청이 끝날 때 호출되지만, 테스트 중에 수동으로 컨텍스트를 푸시할 수도 있습니다.

with app.test_request_context():
    ...

with 블록이 종료되면(또는 ``ctx.pop()``이 호출되면) 테어다운 함수는 요청 컨텍스트가 비활성화되기 직전에 호출됩니다.

예외 처리 핸들러가 등록된 경우 예외가 전달되지 않도록 테어다운 함수가 호출됩니다.

테어다운 함수는 예외를 발생시키지 않도록 해야 합니다. 실패할 수 있는 코드를 실행할 경우 try/except 블록으로 해당 코드를 감싸고, 오류를 기록해야 합니다.

테어다운 함수의 반환 값은 무시됩니다.

이 기능은 앱과 블루프린트 객체 모두에서 사용 가능합니다. 앱에서 사용할 경우, 모든 요청 후에 실행됩니다. 블루프린트에서 사용할 경우, 블루프린트가 처리하는 모든 요청 후에 실행됩니다. 블루프린트에서 모든 요청 후에 실행되도록 등록하려면 :meth:`.Blueprint.teardown_app_request`를 사용하세요.

매개변수:

f (T_teardown)

반환 형식:

T_teardown

template_filter(name=None)

사용자 정의 템플릿 필터를 등록하는 데 사용되는 데코레이터입니다. 필터의 이름을 지정할 수 있으며, 지정하지 않으면 함수 이름이 사용됩니다. 예시:

@app.template_filter()
def reverse(s):
    return s[::-1]
매개변수:

name (str | None) – 필터의 선택적 이름으로, 지정하지 않으면 함수 이름이 사용됩니다.

반환 형식:

Callable[[T_template_filter], T_template_filter]

template_global(name=None)

사용자 정의 템플릿 글로벌 함수를 등록하는 데 사용되는 데코레이터입니다. 필터의 이름을 지정할 수 있으며, 지정하지 않으면 함수 이름이 사용됩니다. 예시:

@app.template_global()
def double(n):
    return 2 * n
Changelog

Added in version 0.10.

매개변수:

name (str | None) – 글로벌 함수의 선택적 이름으로, 지정하지 않으면 함수 이름이 사용됩니다.

반환 형식:

Callable[[T_template_global], T_template_global]

template_test(name=None)

사용자 정의 템플릿 테스트를 등록하는 데 사용되는 데코레이터입니다. 테스트의 이름을 지정할 수 있으며, 지정하지 않으면 함수 이름이 사용됩니다. 예시:

@app.template_test()
def is_prime(n):
    if n == 2:
        return True
    for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
        if n % i == 0:
            return False
    return True
Changelog

Added in version 0.10.

매개변수:

name (str | None) – 테스트의 선택적 이름으로, 지정하지 않으면 함수 이름이 사용됩니다.

반환 형식:

Callable[[T_template_test], T_template_test]

test_cli_runner_class: type[FlaskCliRunner] | None = None

CliRunner 서브클래스로, 기본값은 ``__init__` 메서드는 Flask 앱 객체를 첫 번째 인수로 받아야 합니다.

Changelog

Added in version 1.0.

test_client_class: type[FlaskClient] | None = None

test_client() 메서드는 이 테스트 클라이언트 클래스의 인스턴스를 생성합니다. 기본값은 :class:`~flask.testing.FlaskClient`입니다.

Changelog

Added in version 0.7.

testing

테스트 모드를 활성화하는 플래그입니다. 이를 ``True``로 설정하면 Flask 확장 프로그램의 테스트 모드가 활성화됩니다(향후 Flask 자체에도 적용될 수 있습니다). 예를 들어, 이는 추가적인 런타임 비용이 드는 테스트 헬퍼를 활성화할 수 있습니다.

이 설정이 활성화되면, ``PROPAGATE_EXCEPTIONS``가 기본값으로 설정된 상태에서 자동으로 활성화됩니다.

이 속성은 TESTING 구성 키를 사용하여 config에서 설정할 수도 있습니다. 기본값은 ``False``입니다.

trap_http_exception(e)

HTTP 예외를 트랩해야 할지 말지를 확인합니다. 기본적으로 ``TRAP_BAD_REQUEST_ERRORS``가 ``True``로 설정된 경우 bad request key 오류를 제외한 모든 예외에 대해 ``False``를 반환합니다. ``TRAP_HTTP_EXCEPTIONS``가 ``True``로 설정된 경우에는 ``True``를 반환합니다.

모든 HTTP 예외에 대해 호출됩니다. 예외에 대해 ``True``를 반환하면 해당 예외의 오류 처리기가 호출되지 않고, 트레이스백에서 일반 예외로 표시됩니다. 이는 암시적으로 발생한 HTTP 예외를 디버깅하는 데 유용합니다.

Changelog

버전 1.0에서 변경: 디버그 모드에서는 기본적으로 잘못된 요청 오류가 트랩되지 않습니다.

Added in version 0.8.

매개변수:

e (Exception)

반환 형식:

bool

url_defaults(f)

애플리케이션의 모든 뷰 함수에 대한 URL 기본값을 처리하는 콜백 함수입니다. 엔드포인트와 값을 인수로 받아 호출되며, 값은 직접 수정됩니다.

앱과 블루프린트 객체 모두에서 사용할 수 있습니다. 앱에서 사용하면 모든 요청에 대해 호출됩니다. 블루프린트에서 사용하면 블루프린트가 처리하는 요청에 대해서만 호출됩니다. 블루프린트에서 모든 요청에 영향을 주려면 :meth:`.Blueprint.app_url_defaults`를 사용하세요.

매개변수:

f (T_url_defaults)

반환 형식:

T_url_defaults

url_map_class

:py:class:`~werkzeug.routing.map.Map`의 별칭

url_rule_class

:py:class:`~werkzeug.routing.rules.Rule`의 별칭

url_value_preprocessor(f)

애플리케이션의 모든 뷰 함수에 대해 URL 값 전처리기 함수를 등록합니다. 이 함수들은 before_request() 함수가 실행되기 전에 호출됩니다.

이 함수는 매칭된 URL에서 값을 가져오기 전에 값을 수정할 수 있습니다. 예를 들어, 공통 언어 코드 값을 ``g``에 저장하고 이를 각 뷰로 전달하는 대신 사용할 수 있습니다.

이 함수는 엔드포인트 이름과 값이 담긴 딕셔너리를 인수로 받아 호출됩니다. 반환 값은 무시됩니다.

앱과 블루프린트 객체 모두에서 사용할 수 있습니다. 앱에서 사용하면 모든 요청에 대해 호출됩니다. 블루프린트에서 사용하면 블루프린트가 처리하는 요청에 대해서만 호출됩니다. 블루프린트에서 모든 요청에 영향을 주려면 :meth:`.Blueprint.app_url_value_preprocessor`를 사용하세요.

매개변수:

f (T_url_value_preprocessor)

반환 형식:

T_url_value_preprocessor

instance_path

인스턴스 폴더의 경로를 보관합니다.

Changelog

Added in version 0.8.

config

:class:`Config`로서 구성 딕셔너리입니다. 일반적인 딕셔너리처럼 동작하지만, 파일에서 구성을 로드하는 추가 메서드를 지원합니다.

aborter

:meth:`make_aborter`로 생성된 :attr:`aborter_class`의 인스턴스입니다. 이는 :func:`flask.abort`에 의해 호출되어 HTTP 오류를 발생시키며, 직접 호출할 수도 있습니다.

Changelog

Added in version 2.2: 이 메서드는 이제 ``flask.abort``에서 이동되었으며, 해당 메서드는 ``flask.abort``가 호출하는 메서드입니다.

json: JSONProvider

JSON 메서드에 접근을 제공합니다. ``flask.json``의 함수들은 애플리케이션 컨텍스트가 활성화될 때 이 제공자의 메서드를 호출합니다. JSON 요청 및 응답을 처리하는 데 사용됩니다.

:attr:`json_provider_class`의 인스턴스입니다. 이 속성을 서브클래스에서 변경하거나 이 속성에 할당하여 사용자 정의할 수 있습니다.

기본값인 DefaultJSONProvider`는 Python의 내장 :mod:`json 라이브러리를 사용합니다. 다른 제공자는 다른 JSON 라이브러리를 사용할 수 있습니다.

Changelog

Added in version 2.2.

url_build_error_handlers: list[t.Callable[[Exception, str, dict[str, t.Any]], str]]

url_for`에서 :exc:`~werkzeug.routing.BuildError`가 발생할 :meth:`handle_url_build_error`에 의해 호출되는 함수들의 리스트입니다. 함수는 ``error`(), endpoint, 그리고 ``values``와 함께 호출됩니다. 함수가 ``None``을 반환하거나 ``BuildError``를 발생시키면 건너뜁니다. 그렇지 않으면 해당 함수의 반환 값이 ``url_for``의 반환 값이 됩니다.

Changelog

Added in version 0.9.

teardown_appcontext_funcs: list[ft.TeardownCallable]

애플리케이션 컨텍스트가 파괴될 때 호출되는 함수들의 목록입니다. 요청이 끝날 때 애플리케이션 컨텍스트도 테어다운되므로, 데이터베이스 연결을 끊는 코드가 이곳에 저장됩니다.

Changelog

Added in version 0.9.

shell_context_processors: list[ft.ShellContextProcessorCallable]

셸 컨텍스트가 생성될 때 실행될 셸 컨텍스트 프로세서 함수들의 목록입니다.

Changelog

Added in version 0.11.

blueprints: dict[str, Blueprint]

등록된 블루프린트 이름을 블루프린트 객체에 매핑합니다. 딕셔너리는 블루프린트가 등록된 순서를 유지합니다. 블루프린트는 여러 번 등록할 수 있으며, 이 딕셔너리는 얼마나 자주 등록되었는지 추적하지 않습니다.

Changelog

Added in version 0.7.

extensions: dict[str, t.Any]

확장 프로그램이 애플리케이션 특정 상태를 저장할 수 있는 장소입니다. 예를 들어, 확장 프로그램이 데이터베이스 엔진과 유사한 항목을 저장할 수 있는 곳입니다.

키는 확장 모듈의 이름과 일치해야 합니다. 예를 들어, Flask-Foo 확장 프로그램의 경우 ``’foo’``라는 키를 사용합니다.

Changelog

Added in version 0.7.

url_map

이 인스턴스의 :class:`~werkzeug.routing.Map`입니다. 이를 사용하여 라우팅 변환기를 변경할 수 있습니다. 클래스가 생성된 후, 라우트를 연결하기 전에 변경이 가능합니다. 예시:

from werkzeug.routing import BaseConverter

class ListConverter(BaseConverter):
    def to_python(self, value):
        return value.split(',')
    def to_url(self, values):
        return ','.join(super(ListConverter, self).to_url(value)
                        for value in values)

app = Flask(__name__)
app.url_map.converters['list'] = ListConverter
import_name

이 객체가 속한 패키지나 모듈의 이름입니다. 생성자에서 설정된 후에는 변경하지 마세요.

template_folder

템플릿 로더에 추가할 템플릿 폴더의 경로로, :attr:`root_path`를 기준으로 상대 경로입니다. 템플릿을 추가하지 않으려면 ``None``으로 설정합니다.

root_path

파일 시스템에서 패키지의 절대 경로입니다. 패키지 내에 포함된 리소스를 찾는 데 사용됩니다.

view_functions: dict[str, ft.RouteCallable]

엔드포인트 이름을 뷰 함수에 매핑하는 딕셔너리입니다.

뷰 함수를 등록하려면 route() 데코레이터를 사용하세요.

이 데이터 구조는 내부용입니다. 직접 수정하지 말고, 그 형식은 언제든지 변경될 수 있습니다.

error_handler_spec: dict[ft.AppOrBlueprintKey, dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]]]

등록된 오류 처리기의 데이터 구조로, 형식은 {scope: {code: {class: handler}}}``입니다. ``scope 키는 핸들러가 활성화된 블루프린트의 이름 또는 모든 요청에 대한 None``입니다. ``code 키는 ``HTTPException``에 대한 HTTP 상태 코드이며, 다른 예외에 대해서는 ``None``입니다. 가장 안쪽 딕셔너리는 예외 클래스를 핸들러 함수에 매핑합니다.

오류 처리기를 등록하려면 errorhandler() 데코레이터를 사용하세요.

이 데이터 구조는 내부용입니다. 직접 수정하지 말고, 그 형식은 언제든지 변경될 수 있습니다.

before_request_funcs: dict[ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]]

각 요청 시작 시 호출할 함수들의 데이터 구조로, 형식은 {scope: [functions]}``입니다. ``scope 키는 함수가 활성화된 블루프린트의 이름 또는 모든 요청에 대한 ``None``입니다.

함수를 등록하려면 before_request() 데코레이터를 사용하세요.

이 데이터 구조는 내부용입니다. 직접 수정하지 말고, 그 형식은 언제든지 변경될 수 있습니다.

after_request_funcs: dict[ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]]]

각 요청 끝에 호출할 함수들의 데이터 구조로, 형식은 {scope: [functions]}``입니다. ``scope 키는 함수가 활성화된 블루프린트의 이름 또는 모든 요청에 대한 ``None``입니다.

함수를 등록하려면 after_request() 데코레이터를 사용하세요.

이 데이터 구조는 내부용입니다. 직접 수정하지 말고, 그 형식은 언제든지 변경될 수 있습니다.

teardown_request_funcs: dict[ft.AppOrBlueprintKey, list[ft.TeardownCallable]]

예외가 발생하더라도 각 요청 끝에 호출할 함수들의 데이터 구조로, 형식은 {scope: [functions]}``입니다. ``scope 키는 함수가 활성화된 블루프린트의 이름 또는 모든 요청에 대한 ``None``입니다.

함수를 등록하려면 teardown_request() 데코레이터를 사용하세요.

이 데이터 구조는 내부용입니다. 직접 수정하지 말고, 그 형식은 언제든지 변경될 수 있습니다.

template_context_processors: dict[ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]]

템플릿 렌더링 시 추가적인 컨텍스트 값을 전달할 함수들의 데이터 구조로, 형식은 {scope: [functions]}``입니다. ``scope 키는 함수가 활성화된 블루프린트의 이름 또는 모든 요청에 대한 ``None``입니다.

함수를 등록하려면 context_processor() 데코레이터를 사용하세요.

이 데이터 구조는 내부용입니다. 직접 수정하지 말고, 그 형식은 언제든지 변경될 수 있습니다.

url_value_preprocessors: dict[ft.AppOrBlueprintKey, list[ft.URLValuePreprocessorCallable]]

뷰 함수에 전달된 키워드 인수를 수정할 함수들의 데이터 구조로, 형식은 {scope: [functions]}``입니다. ``scope 키는 함수가 활성화된 블루프린트의 이름 또는 모든 요청에 대한 ``None``입니다.

함수를 등록하려면 url_value_preprocessor() 데코레이터를 사용하세요.

이 데이터 구조는 내부용입니다. 직접 수정하지 말고, 그 형식은 언제든지 변경될 수 있습니다.

url_default_functions: dict[ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]]

URL 생성 시 키워드 인수를 수정할 함수들의 데이터 구조로, 형식은 {scope: [functions]}``입니다. ``scope 키는 함수가 활성화된 블루프린트의 이름 또는 모든 요청에 대한 ``None``입니다.

함수를 등록하려면 url_defaults() 데코레이터를 사용하세요.

이 데이터 구조는 내부용입니다. 직접 수정하지 말고, 그 형식은 언제든지 변경될 수 있습니다.

블루프린트 객체

class flask.Blueprint(name, import_name, static_folder=None, static_url_path=None, template_folder=None, url_prefix=None, subdomain=None, url_defaults=None, root_path=None, cli_group=_sentinel)
매개변수:
cli: Group

이 객체에 대한 CLI 명령을 등록하기 위한 Click 명령 그룹입니다. 애플리케이션이 발견되고 블루프린트가 등록된 후에는 flask 명령을 통해 해당 명령을 사용할 수 있습니다.

get_send_file_max_age(filename)

send_file`에서 주어진 파일 경로에 대해 ``max_age`() 캐시 값을 결정하는 데 사용됩니다. 해당 값이 전달되지 않은 경우 적용됩니다.

기본적으로, 이는 current_app`의 설정에서 :data:`SEND_FILE_MAX_AGE_DEFAULT 값을 반환합니다. 기본값은 ``None``이며, 이는 브라우저가 시간 기반 캐시 대신 조건부 요청을 사용하도록 지시합니다. 이는 일반적으로 더 바람직한 방식입니다.

이 메서드는 Flask 클래스에 있는 동일한 메서드의 중복임을 유의하세요.

Changelog

버전 2.0에서 변경: 기본 구성은 12시간 대신 ``None``입니다.

Added in version 0.9.

매개변수:

filename (str | None)

반환 형식:

int | None

send_static_file(filename)

:attr:`static_folder`에서 파일을 제공하는 데 사용되는 뷰 함수입니다. :attr:`static_folder`가 설정되어 있으면 이 뷰에 대해 :attr:`static_url_path`에 자동으로 라우트가 등록됩니다.

이 메서드는 Flask 클래스에 있는 동일한 메서드의 중복임을 유의하세요.

Changelog

Added in version 0.5.

매개변수:

filename (str)

반환 형식:

Response

open_resource(resource, mode='rb', encoding='utf-8')

root_path`를 기준으로 리소스 파일을 열어 읽습니다. 이는 앱의 :meth:`~.Flask.open_resource 메서드의 블루프린트 상대 버전입니다.

매개변수:
  • resource (str) – :attr:`root_path`를 기준으로 한 리소스의 경로입니다.

  • mode (str) – 이 모드로 파일을 엽니다. 읽기 전용만 지원되며, 유효한 값은 "r" (또는 "rt")와 ``”rb”``입니다.

  • encoding (str | None) – 텍스트 모드로 파일을 열 때 사용할 인코딩입니다. 바이너리 모드로 열 경우에는 무시됩니다.

반환 형식:

IO

버전 3.1에서 변경: encoding 파라미터가 추가되었습니다.

add_app_template_filter(f, name=None)

애플리케이션에서 렌더링된 모든 템플릿에서 사용할 수 있는 템플릿 필터를 등록합니다. 이는 app_template_filter() 데코레이터처럼 동작합니다. :meth:`.Flask.add_template_filter`와 동일합니다.

매개변수:
  • name (str | None) – 필터의 선택적 이름으로, 지정하지 않으면 함수 이름이 사용됩니다.

  • f (Callable[[...], Any])

반환 형식:

None

add_app_template_global(f, name=None)

애플리케이션에서 렌더링된 모든 템플릿에서 사용할 수 있는 템플릿 글로벌을 등록합니다. 이는 app_template_global() 데코레이터처럼 동작합니다. :meth:`.Flask.add_template_global`와 동일합니다.

Changelog

Added in version 0.10.

매개변수:
  • name (str | None) – 글로벌의 선택적 이름을 지정할 수 있으며, 그렇지 않으면 함수 이름이 사용됩니다.

  • f (Callable[[...], Any])

반환 형식:

None

add_app_template_test(f, name=None)

애플리케이션에서 렌더링된 모든 템플릿에서 사용할 수 있는 템플릿 테스트를 등록합니다. 이는 app_template_test() 데코레이터처럼 동작합니다. :meth:`.Flask.add_template_test`와 동일합니다.

Changelog

Added in version 0.10.

매개변수:
  • name (str | None) – 테스트의 선택적 이름으로, 지정하지 않으면 함수 이름이 사용됩니다.

  • f (Callable[[...], bool])

반환 형식:

None

add_url_rule(rule, endpoint=None, view_func=None, provide_automatic_options=None, **options)

블루프린트에 URL 규칙을 등록합니다. 전체 문서는 :meth:`.Flask.add_url_rule`을 참조하세요.

URL 규칙은 블루프린트의 URL 접두어로 접두어가 붙습니다. 엔드포인트 이름은 :func:`url_for`에서 사용되며 블루프린트의 이름으로 접두어가 붙습니다.

매개변수:
  • rule (str)

  • endpoint (str | None)

  • view_func (ft.RouteCallable | None)

  • provide_automatic_options (bool | None)

  • options (t.Any)

반환 형식:

None

after_app_request(f)

after_request`와 비슷하지만, 블루프린트에서 처리한 요청뿐만 아니라 모든 요청 후에 실행됩니다. 이는 :meth:().Flask.after_request`와 동일합니다.

매개변수:

f (T_after_request)

반환 형식:

T_after_request

after_request(f)

이 객체에 대한 각 요청 후 실행될 함수를 등록합니다.

함수는 응답 객체와 함께 호출되며, 응답 객체를 반환해야 합니다. 이를 통해 함수는 응답이 전송되기 전에 응답을 수정하거나 교체할 수 있습니다.

함수가 예외를 발생시키면 나머지 after_request 함수는 호출되지 않습니다. 따라서 리소스를 닫는 등 반드시 실행해야 하는 작업에는 이 방법을 사용하지 않아야 합니다. 그런 작업에는 :meth:`teardown_request`를 사용하세요.

이 기능은 앱과 블루프린트 객체 모두에서 사용 가능합니다. 앱에서 사용할 경우, 모든 요청 후에 실행됩니다. 블루프린트에서 사용할 경우, 블루프린트가 처리하는 모든 요청 후에 실행됩니다. 블루프린트에서 모든 요청 후에 실행되도록 등록하려면 :meth:`.Blueprint.after_app_request`를 사용하세요.

매개변수:

f (T_after_request)

반환 형식:

T_after_request

app_context_processor(f)

context_processor`와 비슷하지만, 블루프린트에서만 렌더링된 템플릿이 아니라 모든 뷰에서 렌더링된 템플릿에 대해 실행됩니다. 이는 :meth:().Flask.context_processor`와 동일합니다.

매개변수:

f (T_template_context_processor)

반환 형식:

T_template_context_processor

app_errorhandler(code)

errorhandler`와 비슷하지만, 블루프린트에서 처리한 요청뿐만 아니라 모든 요청에 대해 실행됩니다. 이는 :meth:().Flask.errorhandler`와 동일합니다.

매개변수:

code (type[Exception] | int)

반환 형식:

Callable[[T_error_handler], T_error_handler]

app_template_filter(name=None)

애플리케이션에서 렌더링된 모든 템플릿에서 사용할 수 있는 템플릿 필터를 등록합니다. 이는 :meth:`.Flask.template_filter`와 동일합니다.

매개변수:

name (str | None) – 필터의 선택적 이름으로, 지정하지 않으면 함수 이름이 사용됩니다.

반환 형식:

Callable[[T_template_filter], T_template_filter]

app_template_global(name=None)

애플리케이션에서 렌더링된 모든 템플릿에서 사용할 수 있는 템플릿 글로벌을 등록합니다. :meth:`.Flask.template_global`과 동일합니다.

Changelog

Added in version 0.10.

매개변수:

name (str | None) – 글로벌의 선택적 이름을 지정할 수 있으며, 그렇지 않으면 함수 이름이 사용됩니다.

반환 형식:

Callable[[T_template_global], T_template_global]

app_template_test(name=None)

애플리케이션에서 렌더링된 모든 템플릿에서 사용할 수 있는 템플릿 테스트를 등록합니다. :meth:`.Flask.template_test`와 동일합니다.

Changelog

Added in version 0.10.

매개변수:

name (str | None) – 테스트의 선택적 이름으로, 지정하지 않으면 함수 이름이 사용됩니다.

반환 형식:

Callable[[T_template_test], T_template_test]

app_url_defaults(f)

url_defaults`와 비슷하지만, 블루프린트에서 처리한 요청뿐만 아니라 모든 요청에 대해 실행됩니다. :meth:().Flask.url_defaults`와 동일합니다.

매개변수:

f (T_url_defaults)

반환 형식:

T_url_defaults

app_url_value_preprocessor(f)

url_value_preprocessor`와 비슷하지만, 블루프린트에서 처리한 요청뿐만 아니라 모든 요청에 대해 실행됩니다. :meth:().Flask.url_value_preprocessor`와 동일합니다.

매개변수:

f (T_url_value_preprocessor)

반환 형식:

T_url_value_preprocessor

before_app_request(f)

before_request`와 비슷하지만, 블루프린트에서 처리한 요청뿐만 아니라 모든 요청 전에 실행됩니다. :meth:().Flask.before_request`와 동일합니다.

매개변수:

f (T_before_request)

반환 형식:

T_before_request

before_request(f)

각 요청 전에 실행될 함수를 등록합니다.

예를 들어, 데이터베이스 연결을 열거나 세션에서 로그인한 사용자를 로드하는 데 사용할 수 있습니다.

@app.before_request
def load_user():
    if "user_id" in session:
        g.user = db.session.get(session["user_id"])

함수는 인수 없이 호출됩니다. 만약 함수가 ``None``이 아닌 값을 반환하면, 그 값은 뷰 함수의 반환 값처럼 처리되며, 이후 요청 처리는 중단됩니다.

이 기능은 앱과 블루프린트 객체 모두에서 사용 가능합니다. 앱에서 사용할 경우, 모든 요청 전에 실행됩니다. 블루프린트에서 사용할 경우, 블루프린트가 처리하는 요청 전에만 실행됩니다. 블루프린트에서 모든 요청에 대해 실행되도록 등록하려면 :meth:`.Blueprint.before_app_request`를 사용하세요.

매개변수:

f (T_before_request)

반환 형식:

T_before_request

context_processor(f)

템플릿 컨텍스트 프로세서 함수를 등록합니다. 이 함수들은 템플릿 렌더링 전에 실행됩니다. 반환된 딕셔너리의 키는 템플릿에서 사용할 수 있는 변수로 추가됩니다.

이 기능은 앱과 블루프린트 객체 모두에서 사용 가능합니다. 앱에서 사용할 경우, 모든 렌더링된 템플릿에 대해 호출됩니다. 블루프린트에서 사용할 경우, 블루프린트의 뷰에서 렌더링된 템플릿에 대해 호출됩니다. 블루프린트에서 모든 템플릿에 영향을 주도록 등록하려면 :meth:`.Blueprint.app_context_processor`를 사용하세요.

매개변수:

f (T_template_context_processor)

반환 형식:

T_template_context_processor

delete(rule, **options)

``methods=[“DELETE”]``가 설정된 :meth:`route`의 단축키입니다.

Changelog

Added in version 2.0.

매개변수:
반환 형식:

Callable[[T_route], T_route]

endpoint(endpoint)

주어진 엔드포인트에 대해 뷰 함수를 등록하는 데코레이터입니다. view_func 없이 :meth:`add_url_rule`로 규칙이 추가된 경우 사용됩니다.

app.add_url_rule("/ex", endpoint="example")

@app.endpoint("example")
def example():
    ...
매개변수:

endpoint (str) – 뷰 함수와 연결할 엔드포인트 이름입니다.

반환 형식:

Callable[[F], F]

errorhandler(code_or_exception)

코드나 예외 클래스로 오류를 처리할 함수를 등록합니다.

오류 코드를 기준으로 함수를 등록하는 데 사용되는 데코레이터입니다. 예시:

@app.errorhandler(404)
def page_not_found(error):
    return 'This page does not exist', 404

임의의 예외에 대한 핸들러도 등록할 수 있습니다:

@app.errorhandler(DatabaseError)
def special_exception_handler(error):
    return 'Database connection failed', 500

이 기능은 앱과 블루프린트 객체 모두에서 사용 가능합니다. 앱에서 사용할 경우, 모든 요청에서 발생하는 오류를 처리할 수 있습니다. 블루프린트에서 사용할 경우, 블루프린트가 처리하는 요청에서 발생하는 오류를 처리할 수 있습니다. 블루프린트에서 모든 요청에 대해 오류를 처리하려면 :meth:`.Blueprint.app_errorhandler`를 사용하세요.

Changelog

Added in version 0.7: 애플리케이션 전체 오류 핸들러를 위해 :attr:`error_handler_spec`을 직접 수정하는 대신 :meth:`register_error_handler`를 사용하세요.

Added in version 0.7: 이제 HTTPException 클래스의 서브클래스일 필요가 없는 사용자 정의 예외 유형도 추가로 등록할 수 있습니다.

매개변수:

code_or_exception (type[Exception] | int) – 핸들러에 대한 코드로서의 정수 값 또는 임의의 예외입니다

반환 형식:

Callable[[T_error_handler], T_error_handler]

get(rule, **options)

``methods=[“GET”]``가 설정된 :meth:`route`의 단축키입니다.

Changelog

Added in version 2.0.

매개변수:
반환 형식:

Callable[[T_route], T_route]

property has_static_folder: bool

``static_folder``가 설정된 경우 ``True``입니다.

Changelog

Added in version 0.5.

property jinja_loader: BaseLoader | None

이 객체의 템플릿을 위한 Jinja 로더입니다. 기본적으로 이는 설정된 경우 template_folder`를 위한 :class:`jinja2.loaders.FileSystemLoader 클래스입니다.

Changelog

Added in version 0.5.

make_setup_state(app, options, first_registration=False)

BlueprintSetupState 객체의 인스턴스를 생성하여 나중에 등록 콜백 함수에 전달합니다. 서브클래스는 이를 오버라이드하여 설정 상태의 서브클래스를 반환할 수 있습니다.

매개변수:
  • app (App)

  • options (dict[str, t.Any])

  • first_registration (bool)

반환 형식:

BlueprintSetupState

patch(rule, **options)

``methods=[“PATCH”]``가 설정된 :meth:`route`의 단축키입니다.

Changelog

Added in version 2.0.

매개변수:
반환 형식:

Callable[[T_route], T_route]

post(rule, **options)

:meth:`route`에 대한 ``methods=[“POST”]``가 설정된 단축키입니다.

Changelog

Added in version 2.0.

매개변수:
반환 형식:

Callable[[T_route], T_route]

put(rule, **options)

:meth:`route`에 대한 ``methods=[“PUT”]``가 설정된 단축키입니다.

Changelog

Added in version 2.0.

매개변수:
반환 형식:

Callable[[T_route], T_route]

record(func)

블루프린트가 애플리케이션에 등록될 때 호출되는 함수를 등록합니다. 이 함수는 make_setup_state() 메서드에서 반환된 상태를 인수로 호출됩니다.

매개변수:

func (Callable[[BlueprintSetupState], None])

반환 형식:

None

record_once(func)

:meth:`record`와 비슷하지만, 함수를 다른 함수로 래핑하여 한 번만 호출되도록 보장합니다. 블루프린트가 애플리케이션에 두 번째로 등록되면 전달된 함수는 호출되지 않습니다.

매개변수:

func (Callable[[BlueprintSetupState], None])

반환 형식:

None

register(app, options)

Flask.register_blueprint`에 의해 호출되어 블루프린트에 등록된 모든 뷰와 콜백을 애플리케이션에 등록합니다. :class:().BlueprintSetupState`를 생성하고 각 record() 콜백을 호출합니다.

매개변수:
  • app (App) – 이 블루프린트가 등록되는 애플리케이션입니다.

  • options (dict[str, t.Any]) – :meth:`~Flask.register_blueprint`에서 전달된 키워드 인수입니다.

반환 형식:

None

Changelog

버전 2.3에서 변경: 중첩된 블루프린트가 이제 서브도메인을 올바르게 적용합니다.

버전 2.1에서 변경: 같은 이름으로 블루프린트를 여러 번 등록하는 것은 오류입니다.

버전 2.0.1에서 변경: 중첩된 블루프린트는 점으로 구분된 이름으로 등록됩니다. 이를 통해 같은 이름을 가진 블루프린트를 서로 다른 위치에 중첩할 수 있습니다.

버전 2.0.1에서 변경: name 옵션을 사용하여 블루프린트가 등록될 이름을 변경할 수 있습니다. 이 방법을 통해 동일한 블루프린트를 여러 번 등록하고, ``url_for``에서 고유한 이름을 사용할 수 있습니다.

register_blueprint(blueprint, **options)

현재 블루프린트에 다른 :class:`~flask.Blueprint`를 등록합니다. 이 메서드에 전달된 키워드 인수는 새로 등록되는 블루프린트의 기본값을 덮어씁니다.

Changelog

버전 2.0.1에서 변경: name 옵션을 사용하여 블루프린트가 등록될 이름을 변경할 수 있습니다. 이 방법을 통해 동일한 블루프린트를 여러 번 등록하고, ``url_for``에서 고유한 이름을 사용할 수 있습니다.

Added in version 2.0.

매개변수:
  • blueprint (Blueprint)

  • options (Any)

반환 형식:

None

register_error_handler(code_or_exception, f)

비데코레이터 방식에서 사용하기 더 직관적인 오류 처리 함수입니다.

Changelog

Added in version 0.7.

매개변수:
반환 형식:

None

route(rule, **options)

주어진 URL 규칙과 옵션으로 뷰 함수를 등록하는 데코레이터입니다. :meth:`add_url_rule`을 호출하며, 구현에 대한 더 많은 세부사항은 여기에 나와 있습니다.

@app.route("/")
def index():
    return "Hello, World!"

:ref:`url-route-registrations`를 참조하세요.

라우트에 대한 엔드포인트 이름은 endpoint 파라미터가 전달되지 않으면 뷰 함수의 이름으로 기본 설정됩니다.

methods 파라미터는 기본값이 ``[“GET”]``입니다. ``HEAD``와 ``OPTIONS``는 자동으로 추가됩니다.

매개변수:
  • rule (str) – URL 규칙 문자열입니다.

  • options (Any) – Rule 객체에 전달되는 추가 옵션입니다.

반환 형식:

Callable[[T_route], T_route]

property static_folder: str | None

구성된 정적 폴더의 절대 경로입니다. 정적 폴더가 설정되지 않았다면 ``None``입니다.

property static_url_path: str | None

정적 라우트가 접근 가능한 URL 접두사입니다.

초기화 중에 구성되지 않은 경우, :attr:`static_folder`에서 유도됩니다.

teardown_app_request(f)

teardown_request`와 비슷하지만, 블루프린트에서 처리한 요청뿐만 아니라 모든 요청 후에 실행됩니다. :meth:().Flask.teardown_request`와 동일합니다.

매개변수:

f (T_teardown)

반환 형식:

T_teardown

teardown_request(f)

요청 컨텍스트가 팝될 때 호출될 함수를 등록합니다. 일반적으로 각 요청이 끝날 때 호출되지만, 테스트 중에 수동으로 컨텍스트를 푸시할 수도 있습니다.

with app.test_request_context():
    ...

with 블록이 종료되면(또는 ``ctx.pop()``이 호출되면) 테어다운 함수는 요청 컨텍스트가 비활성화되기 직전에 호출됩니다.

예외 처리 핸들러가 등록된 경우 예외가 전달되지 않도록 테어다운 함수가 호출됩니다.

테어다운 함수는 예외를 발생시키지 않도록 해야 합니다. 실패할 수 있는 코드를 실행할 경우 try/except 블록으로 해당 코드를 감싸고, 오류를 기록해야 합니다.

테어다운 함수의 반환 값은 무시됩니다.

이 기능은 앱과 블루프린트 객체 모두에서 사용 가능합니다. 앱에서 사용할 경우, 모든 요청 후에 실행됩니다. 블루프린트에서 사용할 경우, 블루프린트가 처리하는 모든 요청 후에 실행됩니다. 블루프린트에서 모든 요청 후에 실행되도록 등록하려면 :meth:`.Blueprint.teardown_app_request`를 사용하세요.

매개변수:

f (T_teardown)

반환 형식:

T_teardown

url_defaults(f)

애플리케이션의 모든 뷰 함수에 대한 URL 기본값을 처리하는 콜백 함수입니다. 엔드포인트와 값을 인수로 받아 호출되며, 값은 직접 수정됩니다.

앱과 블루프린트 객체 모두에서 사용할 수 있습니다. 앱에서 사용하면 모든 요청에 대해 호출됩니다. 블루프린트에서 사용하면 블루프린트가 처리하는 요청에 대해서만 호출됩니다. 블루프린트에서 모든 요청에 영향을 주려면 :meth:`.Blueprint.app_url_defaults`를 사용하세요.

매개변수:

f (T_url_defaults)

반환 형식:

T_url_defaults

url_value_preprocessor(f)

애플리케이션의 모든 뷰 함수에 대해 URL 값 전처리기 함수를 등록합니다. 이 함수들은 before_request() 함수가 실행되기 전에 호출됩니다.

이 함수는 매칭된 URL에서 값을 가져오기 전에 값을 수정할 수 있습니다. 예를 들어, 공통 언어 코드 값을 ``g``에 저장하고 이를 각 뷰로 전달하는 대신 사용할 수 있습니다.

이 함수는 엔드포인트 이름과 값이 담긴 딕셔너리를 인수로 받아 호출됩니다. 반환 값은 무시됩니다.

앱과 블루프린트 객체 모두에서 사용할 수 있습니다. 앱에서 사용하면 모든 요청에 대해 호출됩니다. 블루프린트에서 사용하면 블루프린트가 처리하는 요청에 대해서만 호출됩니다. 블루프린트에서 모든 요청에 영향을 주려면 :meth:`.Blueprint.app_url_value_preprocessor`를 사용하세요.

매개변수:

f (T_url_value_preprocessor)

반환 형식:

T_url_value_preprocessor

import_name

이 객체가 속한 패키지나 모듈의 이름입니다. 생성자에서 설정된 후에는 변경하지 마세요.

template_folder

템플릿 로더에 추가할 템플릿 폴더의 경로로, :attr:`root_path`를 기준으로 상대 경로입니다. 템플릿을 추가하지 않으려면 ``None``으로 설정합니다.

root_path

파일 시스템에서 패키지의 절대 경로입니다. 패키지 내에 포함된 리소스를 찾는 데 사용됩니다.

view_functions: dict[str, ft.RouteCallable]

엔드포인트 이름을 뷰 함수에 매핑하는 딕셔너리입니다.

뷰 함수를 등록하려면 route() 데코레이터를 사용하세요.

이 데이터 구조는 내부용입니다. 직접 수정하지 말고, 그 형식은 언제든지 변경될 수 있습니다.

error_handler_spec: dict[ft.AppOrBlueprintKey, dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]]]

등록된 오류 처리기의 데이터 구조로, 형식은 {scope: {code: {class: handler}}}``입니다. ``scope 키는 핸들러가 활성화된 블루프린트의 이름 또는 모든 요청에 대한 None``입니다. ``code 키는 ``HTTPException``에 대한 HTTP 상태 코드이며, 다른 예외에 대해서는 ``None``입니다. 가장 안쪽 딕셔너리는 예외 클래스를 핸들러 함수에 매핑합니다.

오류 처리기를 등록하려면 errorhandler() 데코레이터를 사용하세요.

이 데이터 구조는 내부용입니다. 직접 수정하지 말고, 그 형식은 언제든지 변경될 수 있습니다.

before_request_funcs: dict[ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]]

각 요청 시작 시 호출할 함수들의 데이터 구조로, 형식은 {scope: [functions]}``입니다. ``scope 키는 함수가 활성화된 블루프린트의 이름 또는 모든 요청에 대한 ``None``입니다.

함수를 등록하려면 before_request() 데코레이터를 사용하세요.

이 데이터 구조는 내부용입니다. 직접 수정하지 말고, 그 형식은 언제든지 변경될 수 있습니다.

after_request_funcs: dict[ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]]]

각 요청 끝에 호출할 함수들의 데이터 구조로, 형식은 {scope: [functions]}``입니다. ``scope 키는 함수가 활성화된 블루프린트의 이름 또는 모든 요청에 대한 ``None``입니다.

함수를 등록하려면 after_request() 데코레이터를 사용하세요.

이 데이터 구조는 내부용입니다. 직접 수정하지 말고, 그 형식은 언제든지 변경될 수 있습니다.

teardown_request_funcs: dict[ft.AppOrBlueprintKey, list[ft.TeardownCallable]]

예외가 발생하더라도 각 요청 끝에 호출할 함수들의 데이터 구조로, 형식은 {scope: [functions]}``입니다. ``scope 키는 함수가 활성화된 블루프린트의 이름 또는 모든 요청에 대한 ``None``입니다.

함수를 등록하려면 teardown_request() 데코레이터를 사용하세요.

이 데이터 구조는 내부용입니다. 직접 수정하지 말고, 그 형식은 언제든지 변경될 수 있습니다.

template_context_processors: dict[ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]]

템플릿 렌더링 시 추가적인 컨텍스트 값을 전달할 함수들의 데이터 구조로, 형식은 {scope: [functions]}``입니다. ``scope 키는 함수가 활성화된 블루프린트의 이름 또는 모든 요청에 대한 ``None``입니다.

함수를 등록하려면 context_processor() 데코레이터를 사용하세요.

이 데이터 구조는 내부용입니다. 직접 수정하지 말고, 그 형식은 언제든지 변경될 수 있습니다.

url_value_preprocessors: dict[ft.AppOrBlueprintKey, list[ft.URLValuePreprocessorCallable]]

뷰 함수에 전달된 키워드 인수를 수정할 함수들의 데이터 구조로, 형식은 {scope: [functions]}``입니다. ``scope 키는 함수가 활성화된 블루프린트의 이름 또는 모든 요청에 대한 ``None``입니다.

함수를 등록하려면 url_value_preprocessor() 데코레이터를 사용하세요.

이 데이터 구조는 내부용입니다. 직접 수정하지 말고, 그 형식은 언제든지 변경될 수 있습니다.

url_default_functions: dict[ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]]

URL 생성 시 키워드 인수를 수정할 함수들의 데이터 구조로, 형식은 {scope: [functions]}``입니다. ``scope 키는 함수가 활성화된 블루프린트의 이름 또는 모든 요청에 대한 ``None``입니다.

함수를 등록하려면 url_defaults() 데코레이터를 사용하세요.

이 데이터 구조는 내부용입니다. 직접 수정하지 말고, 그 형식은 언제든지 변경될 수 있습니다.

수신된 요청 데이터

class flask.Request(environ, populate_request=True, shallow=False)

Flask에서 기본적으로 사용하는 요청 객체입니다. 일치하는 엔드포인트와 뷰 인수를 기억합니다.

이 객체는 :class:`~flask.request`로 최종 사용됩니다. 요청 객체를 교체하고 싶으면 이를 서브클래싱하여 :attr:`~flask.Flask.request_class`에 할당할 수 있습니다.

요청 객체는 :class:`~werkzeug.wrappers.Request`의 서브클래스이며, Werkzeug가 정의한 모든 속성과 Flask 고유의 몇 가지 속성을 제공합니다.

매개변수:
  • environ (WSGIEnvironment)

  • populate_request (bool)

  • shallow (bool)

url_rule: Rule | None = None

요청과 일치한 내부 URL 규칙입니다. 이는 before/after 핸들러에서 URL에 대해 허용된 메서드를 검사하는 데 유용할 수 있습니다 (request.url_rule.methods 등). 요청의 메서드가 URL 규칙에 대해 유효하지 않으면, 유효한 메서드 목록은 대신 ``routing_exception.valid_methods``에서 확인할 수 있습니다 (Werkzeug 예외 :exc:`~werkzeug.exceptions.MethodNotAllowed`의 속성) 이유는 요청이 내부적으로 바인딩되지 않았기 때문입니다.

Changelog

Added in version 0.6.

view_args: dict[str, t.Any] | None = None

요청과 일치한 뷰 인수의 딕셔너리입니다. 일치하는 중에 예외가 발생한 경우 ``None``이 됩니다.

routing_exception: HTTPException | None = None

URL 일치가 실패한 경우, 이 예외가 요청 처리의 일부로 발생한 예외입니다. 일반적으로 NotFound 예외입니다.

property max_content_length: int | None

이 요청에서 읽을 수 있는 최대 바이트 수입니다. 이 제한을 초과하면 413 RequestEntityTooLarge 오류가 발생합니다. 만약 이 값이 None``으로 설정되면, Flask 애플리케이션 수준에서 제한이 적용되지 않습니다. 그러나 값이 ``None``이고 요청에 ``Content-Length 헤더가 없으며 WSGI 서버가 스트림 종료를 알리지 않으면 무한 스트림을 피하기 위해 데이터가 읽히지 않습니다.

각 요청은 기본적으로 MAX_CONTENT_LENGTH 설정을 따르며, 이 설정의 기본값은 ``None``입니다. 이 값은 특정 ``request``에 설정하여 해당 뷰에만 제한을 적용할 수 있습니다. 이 제한은 애플리케이션이나 뷰의 특정 요구 사항에 맞게 적절하게 설정해야 합니다.

버전 3.1에서 변경: 이것은 요청별로 설정할 수 있습니다.

Changelog

버전 0.6에서 변경: 이것은 Flask 설정을 통해 구성할 수 있습니다.

property max_form_memory_size: int | None

multipart/form-data 본문에서 파일이 아닌 폼 필드의 최대 크기(바이트 단위)입니다. 이 한도를 초과하면 413 RequestEntityTooLarge 오류가 발생합니다. 만약 이 값이 ``None``으로 설정되면, Flask 애플리케이션 수준에서 한도가 적용되지 않습니다.

각 요청은 기본적으로 MAX_FORM_MEMORY_SIZE 설정을 따르며, 기본값은 ``500_000``입니다. 이 값은 특정 ``request``에 대해 설정하여 해당 뷰에 한도를 적용할 수 있습니다. 이 설정은 애플리케이션 또는 뷰의 특정 요구에 맞게 적절하게 설정해야 합니다.

버전 3.1에서 변경: 이것은 Flask 설정을 통해 구성할 수 있습니다.

property max_form_parts: int | None

multipart/form-data 본문에 포함될 수 있는 최대 필드 수입니다. 이 한도를 초과하면 413 RequestEntityTooLarge 오류가 발생합니다. 만약 이 값이 ``None``으로 설정되면, Flask 애플리케이션 수준에서 한도가 적용되지 않습니다.

각 요청은 기본적으로 MAX_FORM_PARTS 설정을 따르며, 기본값은 ``1_000``입니다. 이 값은 특정 ``request``에 설정하여 해당 뷰에 한도를 적용할 수 있습니다. 이 값은 애플리케이션이나 뷰의 특정 요구 사항에 맞게 적절히 설정해야 합니다.

버전 3.1에서 변경: 이것은 Flask 설정을 통해 구성할 수 있습니다.

property endpoint: str | None

요청 URL과 일치한 엔드포인트입니다.

매칭에 실패했거나 아직 매칭이 수행되지 않은 경우, 이는 ``None``이 됩니다.

이것은 :attr:`view_args`와 결합하여 동일한 URL이나 수정된 URL을 재구성하는 데 사용할 수 있습니다.

property blueprint: str | None

현재 블루프린트의 등록된 이름입니다.

이 값은 엔드포인트가 블루프린트의 일부가 아니거나, URL 매칭에 실패했거나 아직 매칭이 수행되지 않은 경우 ``None``이 됩니다.

이 값은 반드시 블루프린트가 생성될 때 사용된 이름과 일치하지 않을 수 있습니다. 블루프린트가 중첩되었거나 다른 이름으로 등록되었을 수 있습니다.

property blueprints: list[str]

현재 블루프린트에서 부모 블루프린트까지의 등록된 이름들입니다.

현재 블루프린트가 없거나 URL 매칭에 실패한 경우, 이는 빈 리스트가 됩니다.

Changelog

Added in version 2.0.1.

on_json_loading_failed(e)

`get_json`이 실패하고 오류가 무시되지 않은 경우 호출됩니다.

이 메서드가 값을 반환하면, 해당 값이 get_json`의 반환값으로 사용됩니다. 기본 구현은 :exc:`~werkzeug.exceptions.BadRequest() 오류를 발생시킵니다.

매개변수:

e (ValueError | None) – 파싱이 실패한 경우, 이 값은 예외입니다. 만약 콘텐츠 타입이 ``application/json``이 아니면 ``None``이 됩니다.

반환 형식:

Any

Changelog

버전 2.3에서 변경: 400 대신 415 오류를 발생시킵니다.

property accept_charsets: CharsetAccept

이 클라이언트가 지원하는 문자셋 리스트는 CharsetAccept 객체로 제공됩니다.

property accept_encodings: Accept

이 클라이언트가 수락하는 인코딩 목록입니다. HTTP 용어에서 인코딩은 gzip과 같은 압축 인코딩을 의미합니다. 문자셋에 대해서는 :attr:`accept_charset`을 확인하세요.

property accept_languages: LanguageAccept

이 클라이언트가 수락하는 언어 리스트입니다. LanguageAccept 객체로 표현됩니다.

property accept_mimetypes: MIMEAccept

이 클라이언트가 지원하는 MIME 타입의 리스트로, ~werkzeug.datastructures.MIMEAccept 객체로 표현됩니다.

access_control_request_headers

교차 출처 요청과 함께 전송될 헤더를 나타내기 위해 프리플라이트 요청과 함께 전송됩니다. 응답에서 ~CORSResponseMixin.access_control_allow_headers 속성을 설정하여 허용된 헤더를 표시합니다.

access_control_request_method

교차 출처 요청에 사용할 방법을 나타내기 위해 프리플라이트 요청과 함께 전송됩니다. 응답에서 ~CORSResponseMixin.access_control_allow_methods 속성을 설정하여 허용된 방법을 표시합니다.

property access_route: list[str]

포워딩된 헤더가 존재하면, 이는 클라이언트 IP에서 마지막 프록시 서버까지의 모든 IP 주소의 목록입니다.

classmethod application(f)

요청을 마지막 인수로 받는 함수로 데코레이터를 적용합니다. 이는 responder() 데코레이터와 유사하지만, 함수가 요청 객체를 마지막 인수로 받으며 요청 객체는 자동으로 닫힙니다:

@Request.application
def my_wsgi_app(request):
    return Response('Hello World!')

Werkzeug 0.14부터는 HTTP 예외가 자동으로 포착되어 서버가 중단되지 않고 응답으로 변환됩니다.

매개변수:

f (t.Callable[[Request], WSGIApplication]) – 데코레이트할 WSGI 호출 가능 객체

반환:

새로운 WSGI 호출 가능 객체

반환 형식:

WSGIApplication

property args: MultiDict[str, str]

구문 분석된 URL 매개변수(물음표 뒤의 URL 부분).

기본적으로 이 함수는 :class:`~werkzeug.datastructures.ImmutableMultiDict`를 반환합니다. 양식 데이터의 순서가 중요한 경우, :attr:`parameter_storage_class`를 다른 타입으로 설정하여 이를 변경할 수 있습니다.

Changelog

버전 2.3에서 변경: 유효하지 않은 바이트는 퍼센트 인코딩된 상태로 유지됩니다.

property authorization: Authorization | None

Authorization 헤더가 Authorization 객체로 파싱됩니다. 헤더가 존재하지 않으면 ``None``을 반환합니다.

Changelog

버전 2.3에서 변경: Authorization`은 이상 ``dict``가 아닙니다. 매개변수 대신 토큰을 사용하는 인증 스킴에서는 ``token` 속성이 추가되었습니다.

property base_url: str

:attr:`url`과 비슷하지만 쿼리 문자열은 포함되지 않습니다.

property cache_control: RequestCacheControl

들어오는 캐시 제어 헤더에 대한 RequestCacheControl 객체입니다.

close()

이 요청 객체와 관련된 리소스를 닫습니다. 이 작업은 모든 파일 핸들을 명시적으로 닫습니다. 또한, 요청 객체를 with 문에서 사용하면 자동으로 닫힙니다.

Changelog

Added in version 0.9.

반환 형식:

None

content_encoding

Content-Encoding 엔티티 헤더 필드는 미디어 타입에 대한 수정자로 사용됩니다. 이 헤더가 존재할 경우, 값은 엔티티 본문에 적용된 추가 콘텐츠 코딩을 나타내며, 이를 통해 Content-Type 헤더 필드에서 참조한 미디어 타입을 얻기 위해 필요한 디코딩 메커니즘을 지정합니다.

Changelog

Added in version 0.9.

property content_length: int | None

Content-Length 엔티티 헤더 필드는 엔티티 본문의 크기를 바이트 단위로 나타냅니다. HEAD 메서드의 경우, 요청이 GET이었다면 전송되었을 엔티티 본문의 크기를 나타냅니다.

content_md5

Content-MD5 엔티티 헤더 필드는 RFC 1864에 정의된 바와 같이 엔티티 본문의 MD5 다이제스트를 나타내며, 엔티티 본문의 종단 간 메시지 무결성 검사(MIC)를 제공하기 위한 용도로 사용됩니다. (참고: MIC는 전송 중 발생할 수 있는 본문의 우발적인 수정은 감지할 수 있지만, 악의적인 공격에 대한 증명으로는 충분하지 않습니다.)

Changelog

Added in version 0.9.

content_type

Content-Type 엔티티 헤더 필드는 수신자에게 전송된 엔티티 본문의 미디어 타입을 나타냅니다. HEAD 메서드의 경우, 요청이 GET이었다면 전송되었을 미디어 타입을 나타냅니다.

property cookies: ImmutableMultiDict[str, str]

요청과 함께 전송된 모든 쿠키 내용을 포함한 :class:`dict`입니다.

property data: bytes

:attr:`stream`에서 읽은 로우 데이터입니다. 요청이 폼 데이터인 경우 비어 있습니다.

로우 데이터가 폼 데이터인 경우에도 가져오려면 :meth:get_data를 사용하세요.

date

Date 일반 헤더 필드는 메시지가 생성된 날짜와 시간을 나타내며, RFC 822의 orig-date와 동일한 의미를 갖습니다.

Changelog

버전 2.0에서 변경: datetime 객체는 시간대 정보를 인식합니다.

dict_storage_class

:py:class:`~werkzeug.datastructures.structures.ImmutableMultiDict`의 별칭

property files: ImmutableMultiDict[str, FileStorage]

업로드된 모든 파일을 포함하는 :class:`~werkzeug.datastructures.MultiDict` 객체입니다. files`의 키는 ``<input type="file" name="">``의 name 속성 값이며, :attr:`files`의 값은 Werkzeug의 :class:`~werkzeug.datastructures.FileStorage 객체입니다.

이 객체는 기본적으로 Python의 표준 파일 객체처럼 동작합니다. 하지만 파일을 파일 시스템에 저장할 수 있는 save() 메서드를 추가로 제공합니다.

`:attr:`files``는 요청 메서드가 POST, PUT 또는 PATCH이고, 요청을 보낸 ``<form>``이 ``enctype=”multipart/form-data”``를 사용한 경우에만 데이터를 포함합니다. 그렇지 않으면 비어 있습니다.

사용된 데이터 구조에 대한 자세한 내용은 MultiDict / FileStorage 문서를 참조하세요.

property form: ImmutableMultiDict[str, str]

폼 파라미터입니다. 기본적으로 이 함수는 ImmutableMultiDict 를 반환합니다. 이 동작은 parameter_storage_class 를 다른 타입으로 설정하여 변경할 수 있습니다. 폼 데이터의 순서가 중요한 경우 이를 설정해야 할 수도 있습니다.

파일 업로드는 여기에 저장되지 않으며, 대신 files 속성에 저장됩니다.

Changelog

버전 0.9에서 변경: Werkzeug 0.9 이전에는 POST 및 PUT 요청의 폼 데이터만 포함되었습니다.

form_data_parser_class

:py:class:`~werkzeug.formparser.FormDataParser`의 별칭

classmethod from_values(*args, **kwargs)

제공된 값에 기반하여 새로운 요청 객체를 생성합니다. environ`이 주어지면 누락된 값은 거기서 채워집니다. 메서드는 URL에서 요청을 시뮬레이션해야 하는 작은 스크립트에 유용합니다. 메서드는 유닛 테스트에 사용하지 마세요. 멀티파트 요청 생성, 쿠키 지원 등을 제공하는 완전한 기능의 클라이언트 객체(:class:`Client)가 있습니다.

이것은 :class:`~werkzeug.test.EnvironBuilder`와 동일한 옵션을 허용합니다.

Changelog

버전 0.5에서 변경: 이 메서드는 이제 따라서 `environ 파라미터는 이제 `environ_overrides`로 불립니다.

반환:

요청 객체

매개변수:
반환 형식:

Request

property full_path: str

쿼리 문자열을 포함한, 요청된 경로.

get_data(cache=True, as_text=False, parse_form_data=False)

클라이언트로부터 버퍼링된 들어오는 데이터를 하나의 바이트 객체로 읽습니다. 기본적으로 이 데이터는 캐시되지만, `cache`를 `False`로 설정하여 이 동작을 변경할 수 있습니다.

클라이언트가 수십 메가바이트 이상의 데이터를 보내 서버에 메모리 문제가 발생할 수 있으므로, 이 메서드를 호출하기 전에 먼저 콘텐츠 길이를 확인하지 않고 호출하는 것은 일반적으로 좋지 않은 방법입니다.

폼 데이터가 이미 파싱된 경우, 이 메서드는 아무것도 반환하지 않습니다. 폼 데이터 파싱은 이 메서드처럼 데이터를 캐시하지 않기 때문입니다. `parse_form_data`를 `True`로 설정하면 폼 데이터 파싱이 암시적으로 호출됩니다. 이 경우 폼 파서가 데이터를 처리하면 이 메서드의 반환 값은 빈 문자열이 됩니다. 일반적으로 이는 필요하지 않습니다. 데이터가 전체적으로 캐시된 경우(기본값) 폼 파서는 캐시된 데이터를 사용해 폼 데이터를 파싱합니다. 서버 메모리 소모를 방지하기 위해 이 메서드를 호출하기 전에 반드시 콘텐츠 길이를 먼저 확인하는 것이 좋습니다.

`as_text`가 `True`로 설정된 경우, 반환 값은 디코딩된 문자열이 됩니다.

Changelog

Added in version 0.9.

매개변수:
반환 형식:

bytes | str

get_json(force=False, silent=False, cache=True)

:attr:`data`를 JSON으로 파싱합니다.

mimetype가 JSON을 나타내지 않거나 (application/json, is_json 참조), 파싱에 실패하면 :meth:`on_json_loading_failed`가 호출되며 해당 메서드의 반환 값이 사용됩니다. 기본적으로 이는 415 Unsupported Media Type resp을 발생시킵니다.

매개변수:
  • force (bool) – mimetype을 무시하고 항상 JSON을 파싱합니다.

  • silent (bool) – mimetype 및 파싱 오류를 무시하고 ``None``을 반환합니다.

  • cache (bool) – 파싱된 JSON을 저장하여 이후 호출 시 반환합니다.

반환 형식:

Any | None

Changelog

버전 2.3에서 변경: 400 대신 415 오류를 발생시킵니다.

버전 2.1에서 변경: 콘텐츠 타입이 올바르지 않으면 400 오류를 발생시킵니다.

property host: str

요청이 전송된 호스트 이름이며, 비표준 포트일 경우 포트까지 포함됩니다. :attr:`trusted_hosts`로 검증됩니다.

See get_host() for a detailed explanation.

property host_url: str

The request URL scheme and host only.

property if_match: ETags

An object containing all the etags in the If-Match header.

반환 형식:

ETags

property if_modified_since: datetime | None

The parsed If-Modified-Since header as a datetime object.

Changelog

버전 2.0에서 변경: datetime 객체는 시간대 정보를 인식합니다.

property if_none_match: ETags

An object containing all the etags in the If-None-Match header.

반환 형식:

ETags

property if_range: IfRange

The parsed If-Range header.

Changelog

버전 2.0에서 변경: IfRange.date is timezone-aware.

Added in version 0.7.

property if_unmodified_since: datetime | None

The parsed If-Unmodified-Since header as a datetime object.

Changelog

버전 2.0에서 변경: datetime 객체는 시간대 정보를 인식합니다.

input_stream

The raw WSGI input stream, without any safety checks.

This is dangerous to use. It does not guard against infinite streams or reading past content_length or max_content_length.

Use stream instead.

property is_json: bool

Check if the mimetype indicates JSON data, either application/json or application/*+json.

is_multiprocess

boolean that is True if the application is served by a WSGI server that spawns multiple processes.

is_multithread

boolean that is True if the application is served by a multithreaded WSGI server.

is_run_once

boolean that is True if the application will be executed only once in a process lifetime. This is the case for CGI for example, but it’s not guaranteed that the execution only happens one time.

property is_secure: bool

True if the request was made with a secure protocol (HTTPS or WSS).

property json: Any

The parsed JSON data if mimetype indicates JSON (application/json, see is_json).

Calls get_json() with default arguments.

If the request content type is not application/json, this will raise a 415 Unsupported Media Type error.

Changelog

버전 2.3에서 변경: 400 대신 415 오류를 발생시킵니다.

버전 2.1에서 변경: 콘텐츠 타입이 올바르지 않으면 400 오류를 발생시킵니다.

list_storage_class

:py:class:`~werkzeug.datastructures.structures.ImmutableList`의 별칭

make_form_data_parser()

Creates the form data parser. Instantiates the form_data_parser_class with some parameters.

Changelog

Added in version 0.8.

반환 형식:

FormDataParser

max_forwards

The Max-Forwards request-header field provides a mechanism with the TRACE and OPTIONS methods to limit the number of proxies or gateways that can forward the request to the next inbound server.

property mimetype: str

Like content_type, but without parameters (eg, without charset, type etc.) and always lowercase. For example if the content type is text/HTML; charset=utf-8 the mimetype would be 'text/html'.

property mimetype_params: dict[str, str]

The mimetype parameters as dict. For example if the content type is text/html; charset=utf-8 the params would be {'charset': 'utf-8'}.

origin

The host that the request originated from. Set access_control_allow_origin on the response to indicate which origins are allowed.

parameter_storage_class

:py:class:`~werkzeug.datastructures.structures.ImmutableMultiDict`의 별칭

property pragma: HeaderSet

The Pragma general-header field is used to include implementation-specific directives that might apply to any recipient along the request/response chain. All pragma directives specify optional behavior from the viewpoint of the protocol; however, some systems MAY require that behavior be consistent with the directives.

property range: Range | None

The parsed Range header.

Changelog

Added in version 0.7.

반환 형식:

Range

referrer

The Referer[sic] request-header field allows the client to specify, for the server’s benefit, the address (URI) of the resource from which the Request-URI was obtained (the “referrer”, although the header field is misspelled).

remote_user

If the server supports user authentication, and the script is protected, this attribute contains the username the user has authenticated as.

property root_url: str

The request URL scheme, host, and root path. This is the root that the application is accessed from.

property script_root: str

Alias for self.root_path. environ["SCRIPT_NAME"] without a trailing slash.

property stream: IO[bytes]

The WSGI input stream, with safety checks. This stream can only be consumed once.

Use get_data() to get the full data as bytes or text. The data attribute will contain the full bytes only if they do not represent form data. The form attribute will contain the parsed form data in that case.

Unlike input_stream, this stream guards against infinite streams or reading past content_length or max_content_length.

If max_content_length is set, it can be enforced on streams if wsgi.input_terminated is set. Otherwise, an empty stream is returned.

If the limit is reached before the underlying stream is exhausted (such as a file that is too large, or an infinite stream), the remaining contents of the stream cannot be read safely. Depending on how the server handles this, clients may show a “connection reset” failure instead of seeing the 413 response.

Changelog

버전 2.3에서 변경: Check max_content_length preemptively and while reading.

버전 0.9에서 변경: The stream is always set (but may be consumed) even if form parsing was accessed first.

trusted_hosts: list[str] | None = None

Valid host names when handling requests. By default all hosts are trusted, which means that whatever the client says the host is will be accepted.

Because Host and X-Forwarded-Host headers can be set to any value by a malicious client, it is recommended to either set this property or implement similar validation in the proxy (if the application is being run behind one).

Changelog

Added in version 0.9.

property url: str

The full request URL with the scheme, host, root path, path, and query string.

property url_root: str

Alias for root_url. The URL with scheme, host, and root path. For example, https://example.com/app/.

property user_agent: UserAgent

The user agent. Use user_agent.string to get the header value. Set user_agent_class to a subclass of UserAgent to provide parsing for the other properties or other extended data.

Changelog

버전 2.1에서 변경: The built-in parser was removed. Set user_agent_class to a UserAgent subclass to parse data from the string.

user_agent_class

:py:class:`~werkzeug.user_agent.UserAgent`의 별칭

property values: CombinedMultiDict[str, str]

A werkzeug.datastructures.CombinedMultiDict that combines args and form.

For GET requests, only args are present, not form.

Changelog

버전 2.0에서 변경: For GET requests, only args are present, not form.

property want_form_data_parsed: bool

True if the request method carries content. By default this is true if a Content-Type is sent.

Changelog

Added in version 0.8.

environ: WSGIEnvironment

The WSGI environment containing HTTP headers and information from the WSGI server.

shallow: bool

Set when creating the request object. If True, reading from the request body will cause a RuntimeException. Useful to prevent modifying the stream from middleware.

method

The method the request was made with, such as GET.

scheme

The URL scheme of the protocol the request used, such as https or wss.

server

The address of the server. (host, port), (path, None) for unix sockets, or None if not known.

root_path

The prefix that the application is mounted under, without a trailing slash. path comes after this.

path

The path part of the URL after root_path. This is the path used for routing within the application.

query_string

The part of the URL after the “?”. This is the raw value, use args for the parsed values.

headers

The headers received with the request.

remote_addr

The address of the client sending the request.

flask.request

To access incoming request data, you can use the global request object. Flask parses incoming request data for you and gives you access to it through that global object. Internally Flask makes sure that you always get the correct data for the active thread if you are in a multithreaded environment.

This is a proxy. See Notes On Proxies for more information.

The request object is an instance of a Request.

Response Objects

class flask.Response(response=None, status=None, headers=None, mimetype=None, content_type=None, direct_passthrough=False)

The response object that is used by default in Flask. Works like the response object from Werkzeug but is set to have an HTML mimetype by default. Quite often you don’t have to create this object yourself because make_response() will take care of that for you.

If you want to replace the response object used you can subclass this and set response_class to your subclass.

Changelog

버전 1.0에서 변경: JSON support is added to the response, like the request. This is useful when testing to get the test client response data as JSON.

버전 1.0에서 변경: Added max_cookie_size.

매개변수:
default_mimetype: str | None = 'text/html'

the default mimetype if none is provided.

accept_ranges

The Accept-Ranges header. Even though the name would indicate that multiple values are supported, it must be one string token only.

The values 'bytes' and 'none' are common.

Changelog

Added in version 0.7.

property access_control_allow_credentials: bool

Whether credentials can be shared by the browser to JavaScript code. As part of the preflight request it indicates whether credentials can be used on the cross origin request.

access_control_allow_headers

Which headers can be sent with the cross origin request.

access_control_allow_methods

Which methods can be used for the cross origin request.

access_control_allow_origin

The origin or ‘*’ for any origin that may make cross origin requests.

access_control_expose_headers

Which headers can be shared by the browser to JavaScript code.

access_control_max_age

The maximum age in seconds the access control settings can be cached for.

add_etag(overwrite=False, weak=False)

Add an etag for the current response if there is none yet.

Changelog

버전 2.0에서 변경: SHA-1 is used to generate the value. MD5 may not be available in some environments.

매개변수:
반환 형식:

None

age

The Age response-header field conveys the sender’s estimate of the amount of time since the response (or its revalidation) was generated at the origin server.

Age values are non-negative decimal integers, representing time in seconds.

property allow: HeaderSet

The Allow entity-header field lists the set of methods supported by the resource identified by the Request-URI. The purpose of this field is strictly to inform the recipient of valid methods associated with the resource. An Allow header field MUST be present in a 405 (Method Not Allowed) response.

automatically_set_content_length = True

Should this response object automatically set the content-length header if possible? This is true by default.

Changelog

Added in version 0.8.

property cache_control: ResponseCacheControl

The Cache-Control general-header field is used to specify directives that MUST be obeyed by all caching mechanisms along the request/response chain.

calculate_content_length()

Returns the content length if available or None otherwise.

반환 형식:

int | None

call_on_close(func)

Adds a function to the internal list of functions that should be called as part of closing down the response. Since 0.7 this function also returns the function that was passed so that this can be used as a decorator.

Changelog

Added in version 0.6.

매개변수:

func (Callable[[], Any])

반환 형식:

Callable[[], Any]

close()

Close the wrapped response if possible. You can also use the object in a with statement which will automatically close it.

Changelog

Added in version 0.9: Can now be used in a with statement.

반환 형식:

None

content_encoding

Content-Encoding 엔티티 헤더 필드는 미디어 타입에 대한 수정자로 사용됩니다. 이 헤더가 존재할 경우, 값은 엔티티 본문에 적용된 추가 콘텐츠 코딩을 나타내며, 이를 통해 Content-Type 헤더 필드에서 참조한 미디어 타입을 얻기 위해 필요한 디코딩 메커니즘을 지정합니다.

property content_language: HeaderSet

The Content-Language entity-header field describes the natural language(s) of the intended audience for the enclosed entity. Note that this might not be equivalent to all the languages used within the entity-body.

content_length

The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.

content_location

The Content-Location entity-header field MAY be used to supply the resource location for the entity enclosed in the message when that entity is accessible from a location separate from the requested resource’s URI.

content_md5

Content-MD5 엔티티 헤더 필드는 RFC 1864에 정의된 바와 같이 엔티티 본문의 MD5 다이제스트를 나타내며, 엔티티 본문의 종단 간 메시지 무결성 검사(MIC)를 제공하기 위한 용도로 사용됩니다. (참고: MIC는 전송 중 발생할 수 있는 본문의 우발적인 수정은 감지할 수 있지만, 악의적인 공격에 대한 증명으로는 충분하지 않습니다.)

property content_range: ContentRange

The Content-Range header as a ContentRange object. Available even if the header is not set.

Changelog

Added in version 0.7.

property content_security_policy: ContentSecurityPolicy

The Content-Security-Policy header as a ContentSecurityPolicy object. Available even if the header is not set.

The Content-Security-Policy header adds an additional layer of security to help detect and mitigate certain types of attacks.

property content_security_policy_report_only: ContentSecurityPolicy

The Content-Security-policy-report-only header as a ContentSecurityPolicy object. Available even if the header is not set.

The Content-Security-Policy-Report-Only header adds a csp policy that is not enforced but is reported thereby helping detect certain types of attacks.

content_type

Content-Type 엔티티 헤더 필드는 수신자에게 전송된 엔티티 본문의 미디어 타입을 나타냅니다. HEAD 메서드의 경우, 요청이 GET이었다면 전송되었을 미디어 타입을 나타냅니다.

cross_origin_embedder_policy

Prevents a document from loading any cross-origin resources that do not explicitly grant the document permission. Values must be a member of the werkzeug.http.COEP enum.

cross_origin_opener_policy

Allows control over sharing of browsing context group with cross-origin documents. Values must be a member of the werkzeug.http.COOP enum.

property data: bytes | str

A descriptor that calls get_data() and set_data().

date

Date 일반 헤더 필드는 메시지가 생성된 날짜와 시간을 나타내며, RFC 822의 orig-date와 동일한 의미를 갖습니다.

Changelog

버전 2.0에서 변경: datetime 객체는 시간대 정보를 인식합니다.

default_status = 200

the default status if none is provided.

Delete a cookie. Fails silently if key doesn’t exist.

매개변수:
  • key (str) – the key (name) of the cookie to be deleted.

  • path (str | None) – if the cookie that should be deleted was limited to a path, the path has to be defined here.

  • domain (str | None) – if the cookie that should be deleted was limited to a domain, that domain has to be defined here.

  • secure (bool) – If True, the cookie will only be available via HTTPS.

  • httponly (bool) – Disallow JavaScript access to the cookie.

  • samesite (str | None) – Limit the scope of the cookie to only be attached to requests that are “same-site”.

  • partitioned (bool) – If True, the cookie will be partitioned.

반환 형식:

None

expires

The Expires entity-header field gives the date/time after which the response is considered stale. A stale cache entry may not normally be returned by a cache.

Changelog

버전 2.0에서 변경: datetime 객체는 시간대 정보를 인식합니다.

classmethod force_type(response, environ=None)

Enforce that the WSGI response is a response object of the current type. Werkzeug will use the Response internally in many situations like the exceptions. If you call get_response() on an exception you will get back a regular Response object, even if you are using a custom subclass.

This method can enforce a given response type, and it will also convert arbitrary WSGI callables into response objects if an environ is provided:

# convert a Werkzeug response object into an instance of the
# MyResponseClass subclass.
response = MyResponseClass.force_type(response)

# convert any WSGI application into a response object
response = MyResponseClass.force_type(response, environ)

This is especially useful if you want to post-process responses in the main dispatcher and use functionality provided by your subclass.

Keep in mind that this will modify response objects in place if possible!

매개변수:
  • response (Response) – a response object or wsgi application.

  • environ (WSGIEnvironment | None) – a WSGI environment object.

반환:

a response object.

반환 형식:

Response

freeze()

Make the response object ready to be pickled. Does the following:

  • Buffer the response into a list, ignoring implicity_sequence_conversion and direct_passthrough.

  • Set the Content-Length header.

  • Generate an ETag header if one is not already set.

Changelog

버전 2.1에서 변경: Removed the no_etag parameter.

버전 2.0에서 변경: An ETag header is always added.

버전 0.6에서 변경: The Content-Length header is set.

반환 형식:

None

classmethod from_app(app, environ, buffered=False)

Create a new response object from an application output. This works best if you pass it an application that returns a generator all the time. Sometimes applications may use the write() callable returned by the start_response function. This tries to resolve such edge cases automatically. But if you don’t get the expected output you should set buffered to True which enforces buffering.

매개변수:
  • app (WSGIApplication) – the WSGI application to execute.

  • environ (WSGIEnvironment) – the WSGI environment to execute against.

  • buffered (bool) – set to True to enforce buffering.

반환:

a response object.

반환 형식:

Response

get_app_iter(environ)

Returns the application iterator for the given environ. Depending on the request method and the current status code the return value might be an empty response rather than the one from the response.

If the request method is HEAD or the status code is in a range where the HTTP specification requires an empty response, an empty iterable is returned.

Changelog

Added in version 0.6.

매개변수:

environ (WSGIEnvironment) – the WSGI environment of the request.

반환:

a response iterable.

반환 형식:

t.Iterable[bytes]

get_data(as_text=False)

The string representation of the response body. Whenever you call this property the response iterable is encoded and flattened. This can lead to unwanted behavior if you stream big data.

This behavior can be disabled by setting implicit_sequence_conversion to False.

`as_text`가 `True`로 설정된 경우, 반환 값은 디코딩된 문자열이 됩니다.

Changelog

Added in version 0.9.

매개변수:

as_text (bool)

반환 형식:

bytes | str

get_etag()

Return a tuple in the form (etag, is_weak). If there is no ETag the return value is (None, None).

반환 형식:

tuple[str, bool] | tuple[None, None]

get_json(force=False, silent=False)

Parse data as JSON. Useful during testing.

If the mimetype does not indicate JSON (application/json, see is_json), this returns None.

Unlike Request.get_json(), the result is not cached.

매개변수:
  • force (bool) – mimetype을 무시하고 항상 JSON을 파싱합니다.

  • silent (bool) – Silence parsing errors and return None instead.

반환 형식:

Any | None

get_wsgi_headers(environ)

This is automatically called right before the response is started and returns headers modified for the given environment. It returns a copy of the headers from the response with some modifications applied if necessary.

For example the location header (if present) is joined with the root URL of the environment. Also the content length is automatically set to zero here for certain status codes.

Changelog

버전 0.6에서 변경: Previously that function was called fix_headers and modified the response object in place. Also since 0.6, IRIs in location and content-location headers are handled properly.

Also starting with 0.6, Werkzeug will attempt to set the content length if it is able to figure it out on its own. This is the case if all the strings in the response iterable are already encoded and the iterable is buffered.

매개변수:

environ (WSGIEnvironment) – the WSGI environment of the request.

반환:

returns a new Headers object.

반환 형식:

Headers

get_wsgi_response(environ)

Returns the final WSGI response as tuple. The first item in the tuple is the application iterator, the second the status and the third the list of headers. The response returned is created specially for the given environment. For example if the request method in the WSGI environment is 'HEAD' the response will be empty and only the headers and status code will be present.

Changelog

Added in version 0.6.

매개변수:

environ (WSGIEnvironment) – the WSGI environment of the request.

반환:

an (app_iter, status, headers) tuple.

반환 형식:

tuple[t.Iterable[bytes], str, list[tuple[str, str]]]

implicit_sequence_conversion = True

if set to False accessing properties on the response object will not try to consume the response iterator and convert it into a list.

Changelog

Added in version 0.6.2: That attribute was previously called implicit_seqence_conversion. (Notice the typo). If you did use this feature, you have to adapt your code to the name change.

property is_json: bool

Check if the mimetype indicates JSON data, either application/json or application/*+json.

property is_sequence: bool

If the iterator is buffered, this property will be True. A response object will consider an iterator to be buffered if the response attribute is a list or tuple.

Changelog

Added in version 0.6.

property is_streamed: bool

If the response is streamed (the response is not an iterable with a length information) this property is True. In this case streamed means that there is no information about the number of iterations. This is usually True if a generator is passed to the response object.

This is useful for checking before applying some sort of post filtering that should not take place for streamed responses.

iter_encoded()

Iter the response encoded with the encoding of the response. If the response object is invoked as WSGI application the return value of this method is used as application iterator unless direct_passthrough was activated.

반환 형식:

Iterator[bytes]

property json: Any | None

The parsed JSON data if mimetype indicates JSON (application/json, see is_json).

Calls get_json() with default arguments.

last_modified

The Last-Modified entity-header field indicates the date and time at which the origin server believes the variant was last modified.

Changelog

버전 2.0에서 변경: datetime 객체는 시간대 정보를 인식합니다.

location

The Location response-header field is used to redirect the recipient to a location other than the Request-URI for completion of the request or identification of a new resource.

make_conditional(request_or_environ, accept_ranges=False, complete_length=None)

Make the response conditional to the request. This method works best if an etag was defined for the response already. The add_etag method can be used to do that. If called without etag just the date header is set.

This does nothing if the request method in the request or environ is anything but GET or HEAD.

For optimal performance when handling range requests, it’s recommended that your response data object implements seekable, seek and tell methods as described by io.IOBase. Objects returned by wrap_file() automatically implement those methods.

It does not remove the body of the response because that’s something the __call__() function does for us automatically.

Returns self so that you can do return resp.make_conditional(req) but modifies the object in-place.

매개변수:
  • request_or_environ (WSGIEnvironment | Request) – a request object or WSGI environment to be used to make the response conditional against.

  • accept_ranges (bool | str) – This parameter dictates the value of Accept-Ranges header. If False (default), the header is not set. If True, it will be set to "bytes". If it’s a string, it will use this value.

  • complete_length (int | None) – Will be used only in valid Range Requests. It will set Content-Range complete length value and compute Content-Length real value. This parameter is mandatory for successful Range Requests completion.

Raises:

RequestedRangeNotSatisfiable if Range header could not be parsed or satisfied.

반환 형식:

Response

Changelog

버전 2.0에서 변경: Range processing is skipped if length is 0 instead of raising a 416 Range Not Satisfiable error.

make_sequence()

Converts the response iterator in a list. By default this happens automatically if required. If implicit_sequence_conversion is disabled, this method is not automatically called and some properties might raise exceptions. This also encodes all the items.

Changelog

Added in version 0.6.

반환 형식:

None

property mimetype: str | None

The mimetype (content type without charset etc.)

property mimetype_params: dict[str, str]

The mimetype parameters as dict. For example if the content type is text/html; charset=utf-8 the params would be {'charset': 'utf-8'}.

Changelog

Added in version 0.5.

property retry_after: datetime | None

The Retry-After response-header field can be used with a 503 (Service Unavailable) response to indicate how long the service is expected to be unavailable to the requesting client.

Time in seconds until expiration or date.

Changelog

버전 2.0에서 변경: datetime 객체는 시간대 정보를 인식합니다.

Sets a cookie.

A warning is raised if the size of the cookie header exceeds max_cookie_size, but the header will still be set.

매개변수:
  • key (str) – the key (name) of the cookie to be set.

  • value (str) – the value of the cookie.

  • max_age (timedelta | int | None) – should be a number of seconds, or None (default) if the cookie should last only as long as the client’s browser session.

  • expires (str | datetime | int | float | None) – should be a datetime object or UNIX timestamp.

  • path (str | None) – limits the cookie to a given path, per default it will span the whole domain.

  • domain (str | None) – if you want to set a cross-domain cookie. For example, domain="example.com" will set a cookie that is readable by the domain www.example.com, foo.example.com etc. Otherwise, a cookie will only be readable by the domain that set it.

  • secure (bool) – If True, the cookie will only be available via HTTPS.

  • httponly (bool) – Disallow JavaScript access to the cookie.

  • samesite (str | None) – Limit the scope of the cookie to only be attached to requests that are “same-site”.

  • partitioned (bool) – If True, the cookie will be partitioned.

반환 형식:

None

버전 3.1에서 변경: The partitioned parameter was added.

set_data(value)

Sets a new string as response. The value must be a string or bytes. If a string is set it’s encoded to the charset of the response (utf-8 by default).

Changelog

Added in version 0.9.

매개변수:

value (bytes | str)

반환 형식:

None

set_etag(etag, weak=False)

Set the etag, and override the old one if there was one.

매개변수:
반환 형식:

None

property status: str

The HTTP status code as a string.

property status_code: int

The HTTP status code as a number.

property stream: ResponseStream

The response iterable as write-only stream.

property vary: HeaderSet

The Vary field value indicates the set of request-header fields that fully determines, while the response is fresh, whether a cache is permitted to use the response to reply to a subsequent request without revalidation.

property www_authenticate: WWWAuthenticate

The WWW-Authenticate header parsed into a WWWAuthenticate object. Modifying the object will modify the header value.

This header is not set by default. To set this header, assign an instance of WWWAuthenticate to this attribute.

response.www_authenticate = WWWAuthenticate(
    "basic", {"realm": "Authentication Required"}
)

Multiple values for this header can be sent to give the client multiple options. Assign a list to set multiple headers. However, modifying the items in the list will not automatically update the header values, and accessing this attribute will only ever return the first value.

To unset this header, assign None or use del.

Changelog

버전 2.3에서 변경: This attribute can be assigned to set the header. A list can be assigned to set multiple header values. Use del to unset the header.

버전 2.3에서 변경: WWWAuthenticate is no longer a dict. The token attribute was added for auth challenges that use a token instead of parameters.

response: t.Iterable[str] | t.Iterable[bytes]

The response body to send as the WSGI iterable. A list of strings or bytes represents a fixed-length response, any other iterable is a streaming response. Strings are encoded to bytes as UTF-8.

Do not set to a plain string or bytes, that will cause sending the response to be very inefficient as it will iterate one byte at a time.

direct_passthrough

Pass the response body directly through as the WSGI iterable. This can be used when the body is a binary file or other iterator of bytes, to skip some unnecessary checks. Use send_file() instead of setting this manually.

autocorrect_location_header = False

If a redirect Location header is a relative URL, make it an absolute URL, including scheme and domain.

Changelog

버전 2.1에서 변경: This is disabled by default, so responses will send relative redirects.

Added in version 0.8.

Read-only view of the MAX_COOKIE_SIZE config key.

See max_cookie_size in Werkzeug’s docs.

Sessions

If you have set Flask.secret_key (or configured it from SECRET_KEY) you can use sessions in Flask applications. A session makes it possible to remember information from one request to another. The way Flask does this is by using a signed cookie. The user can look at the session contents, but can’t modify it unless they know the secret key, so make sure to set that to something complex and unguessable.

To access the current session you can use the session object:

class flask.session

The session object works pretty much like an ordinary dict, with the difference that it keeps track of modifications.

This is a proxy. See Notes On Proxies for more information.

The following attributes are interesting:

new

True if the session is new, False otherwise.

modified

True if the session object detected a modification. Be advised that modifications on mutable structures are not picked up automatically, in that situation you have to explicitly set the attribute to True yourself. Here an example:

# this change is not picked up because a mutable object (here
# a list) is changed.
session['objects'].append(42)
# so mark it as modified yourself
session.modified = True
permanent

If set to True the session lives for permanent_session_lifetime seconds. The default is 31 days. If set to False (which is the default) the session will be deleted when the user closes the browser.

Session Interface

Changelog

Added in version 0.8.

The session interface provides a simple way to replace the session implementation that Flask is using.

class flask.sessions.SessionInterface

The basic interface you have to implement in order to replace the default session interface which uses werkzeug’s securecookie implementation. The only methods you have to implement are open_session() and save_session(), the others have useful defaults which you don’t need to change.

The session object returned by the open_session() method has to provide a dictionary like interface plus the properties and methods from the SessionMixin. We recommend just subclassing a dict and adding that mixin:

class Session(dict, SessionMixin):
    pass

If open_session() returns None Flask will call into make_null_session() to create a session that acts as replacement if the session support cannot work because some requirement is not fulfilled. The default NullSession class that is created will complain that the secret key was not set.

To replace the session interface on an application all you have to do is to assign flask.Flask.session_interface:

app = Flask(__name__)
app.session_interface = MySessionInterface()

Multiple requests with the same session may be sent and handled concurrently. When implementing a new session interface, consider whether reads or writes to the backing store must be synchronized. There is no guarantee on the order in which the session for each request is opened or saved, it will occur in the order that requests begin and end processing.

Changelog

Added in version 0.8.

null_session_class

make_null_session() will look here for the class that should be created when a null session is requested. Likewise the is_null_session() method will perform a typecheck against this type.

:py:class:`~flask.sessions.NullSession`의 별칭

pickle_based = False

A flag that indicates if the session interface is pickle based. This can be used by Flask extensions to make a decision in regards to how to deal with the session object.

Changelog

Added in version 0.10.

make_null_session(app)

Creates a null session which acts as a replacement object if the real session support could not be loaded due to a configuration error. This mainly aids the user experience because the job of the null session is to still support lookup without complaining but modifications are answered with a helpful error message of what failed.

This creates an instance of null_session_class by default.

매개변수:

app (Flask)

반환 형식:

NullSession

is_null_session(obj)

Checks if a given object is a null session. Null sessions are not asked to be saved.

This checks if the object is an instance of null_session_class by default.

매개변수:

obj (object)

반환 형식:

bool

The name of the session cookie. Uses``app.config[“SESSION_COOKIE_NAME”]``.

매개변수:

app (Flask)

반환 형식:

str

The value of the Domain parameter on the session cookie. If not set, browsers will only send the cookie to the exact domain it was set from. Otherwise, they will send it to any subdomain of the given value as well.

Uses the SESSION_COOKIE_DOMAIN config.

Changelog

버전 2.3에서 변경: Not set by default, does not fall back to SERVER_NAME.

매개변수:

app (Flask)

반환 형식:

str | None

Returns the path for which the cookie should be valid. The default implementation uses the value from the SESSION_COOKIE_PATH config var if it’s set, and falls back to APPLICATION_ROOT or uses / if it’s None.

매개변수:

app (Flask)

반환 형식:

str

Returns True if the session cookie should be httponly. This currently just returns the value of the SESSION_COOKIE_HTTPONLY config var.

매개변수:

app (Flask)

반환 형식:

bool

Returns True if the cookie should be secure. This currently just returns the value of the SESSION_COOKIE_SECURE setting.

매개변수:

app (Flask)

반환 형식:

bool

Return 'Strict' or 'Lax' if the cookie should use the SameSite attribute. This currently just returns the value of the SESSION_COOKIE_SAMESITE setting.

매개변수:

app (Flask)

반환 형식:

str | None

Returns True if the cookie should be partitioned. By default, uses the value of SESSION_COOKIE_PARTITIONED.

Added in version 3.1.

매개변수:

app (Flask)

반환 형식:

bool

get_expiration_time(app, session)

A helper method that returns an expiration date for the session or None if the session is linked to the browser session. The default implementation returns now + the permanent session lifetime configured on the application.

매개변수:
반환 형식:

datetime | None

Used by session backends to determine if a Set-Cookie header should be set for this session cookie for this response. If the session has been modified, the cookie is set. If the session is permanent and the SESSION_REFRESH_EACH_REQUEST config is true, the cookie is always set.

This check is usually skipped if the session was deleted.

Changelog

Added in version 0.11.

매개변수:
반환 형식:

bool

open_session(app, request)

This is called at the beginning of each request, after pushing the request context, before matching the URL.

This must return an object which implements a dictionary-like interface as well as the SessionMixin interface.

This will return None to indicate that loading failed in some way that is not immediately an error. The request context will fall back to using make_null_session() in this case.

매개변수:
반환 형식:

SessionMixin | None

save_session(app, session, response)

This is called at the end of each request, after generating a response, before removing the request context. It is skipped if is_null_session() returns True.

매개변수:
반환 형식:

None

class flask.sessions.SecureCookieSessionInterface

The default session interface that stores sessions in signed cookies through the itsdangerous module.

salt = 'cookie-session'

the salt that should be applied on top of the secret key for the signing of cookie based sessions.

static digest_method(string=b'')

the hash function to use for the signature. The default is sha1

매개변수:

string (bytes)

반환 형식:

Any

key_derivation = 'hmac'

the name of the itsdangerous supported key derivation. The default is hmac.

serializer = <flask.json.tag.TaggedJSONSerializer object>

A python serializer for the payload. The default is a compact JSON derived serializer with support for some extra Python types such as datetime objects or tuples.

session_class

:py:class:`~flask.sessions.SecureCookieSession`의 별칭

open_session(app, request)

This is called at the beginning of each request, after pushing the request context, before matching the URL.

This must return an object which implements a dictionary-like interface as well as the SessionMixin interface.

This will return None to indicate that loading failed in some way that is not immediately an error. The request context will fall back to using make_null_session() in this case.

매개변수:
반환 형식:

SecureCookieSession | None

save_session(app, session, response)

This is called at the end of each request, after generating a response, before removing the request context. It is skipped if is_null_session() returns True.

매개변수:
반환 형식:

None

class flask.sessions.SecureCookieSession(initial=None)

Base class for sessions based on signed cookies.

This session backend will set the modified and accessed attributes. It cannot reliably track whether a session is new (vs. empty), so new remains hard coded to False.

매개변수:

initial (c.Mapping[str, t.Any] | c.Iterable[tuple[str, t.Any]] | None)

modified = False

When data is changed, this is set to True. Only the session dictionary itself is tracked; if the session contains mutable data (for example a nested dict) then this must be set to True manually when modifying that data. The session cookie will only be written to the response if this is True.

accessed = False

header, which allows caching proxies to cache different pages for different users.

get(key, default=None)

Return the value for key if key is in the dictionary, else default.

매개변수:
반환 형식:

Any

setdefault(key, default=None)

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

매개변수:
반환 형식:

Any

class flask.sessions.NullSession(initial=None)

Class used to generate nicer error messages if sessions are not available. Will still allow read-only access to the empty session but fail on setting.

매개변수:

initial (c.Mapping[str, t.Any] | c.Iterable[tuple[str, t.Any]] | None)

clear(*args, **kwargs)

Remove all items from the dict.

매개변수:
반환 형식:

NoReturn

pop(k[, d]) v, remove specified key and return the corresponding value.

If the key is not found, return the default if given; otherwise, raise a KeyError.

매개변수:
반환 형식:

NoReturn

popitem(*args, **kwargs)

Remove and return a (key, value) pair as a 2-tuple.

Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.

매개변수:
반환 형식:

NoReturn

update([E, ]**F) None.  Update D from mapping/iterable E and F.

If E is present and has a .keys() method, then does: for k in E.keys(): D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

매개변수:
반환 형식:

NoReturn

setdefault(*args, **kwargs)

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

매개변수:
반환 형식:

NoReturn

class flask.sessions.SessionMixin

Expands a basic dictionary with session attributes.

property permanent: bool

This reflects the '_permanent' key in the dict.

modified = True

Some implementations can detect changes to the session and set this when that happens. The mixin default is hard coded to True.

accessed = True

Some implementations can detect when session data is read or written and set this when that happens. The mixin default is hard coded to True.

Notice

The PERMANENT_SESSION_LIFETIME config can be an integer or timedelta. The permanent_session_lifetime attribute is always a timedelta.

Test Client

class flask.testing.FlaskClient(*args, **kwargs)

Works like a regular Werkzeug test client but has knowledge about Flask’s contexts to defer the cleanup of the request context until the end of a with block. For general information about how to use this class refer to werkzeug.test.Client.

Changelog

버전 0.12에서 변경: app.test_client() includes preset default environment, which can be set after instantiation of the app.test_client() object in client.environ_base.

Basic usage is outlined in the Testing Flask Applications chapter.

매개변수:
  • args (t.Any)

  • kwargs (t.Any)

session_transaction(*args, **kwargs)

When used in combination with a with statement this opens a session transaction. This can be used to modify the session that the test client uses. Once the with block is left the session is stored back.

with client.session_transaction() as session:
    session['value'] = 42

Internally this is implemented by going through a temporary test request context and since session handling could depend on request variables this function accepts the same arguments as test_request_context() which are directly passed through.

매개변수:
반환 형식:

Iterator[SessionMixin]

open(*args, buffered=False, follow_redirects=False, **kwargs)

Generate an environ dict from the given arguments, make a request to the application using it, and return the response.

매개변수:
  • args (t.Any) – Passed to EnvironBuilder to create the environ for the request. If a single arg is passed, it can be an existing EnvironBuilder or an environ dict.

  • buffered (bool) – Convert the iterator returned by the app into a list. If the iterator has a close() method, it is called automatically.

  • follow_redirects (bool) – Make additional requests to follow HTTP redirects until a non-redirect status is returned. TestResponse.history lists the intermediate responses.

  • kwargs (t.Any)

반환 형식:

TestResponse

Changelog

버전 2.1에서 변경: Removed the as_tuple parameter.

버전 2.0에서 변경: The request input stream is closed when calling response.close(). Input streams for redirects are automatically closed.

버전 0.5에서 변경: If a dict is provided as file in the dict for the data parameter the content type has to be called content_type instead of mimetype. This change was made for consistency with werkzeug.FileWrapper.

버전 0.5에서 변경: Added the follow_redirects parameter.

Test CLI Runner

class flask.testing.FlaskCliRunner(app, **kwargs)

A CliRunner for testing a Flask app’s CLI commands. Typically created using test_cli_runner(). See Running Commands with the CLI Runner.

매개변수:
  • app (Flask)

  • kwargs (t.Any)

invoke(cli=None, args=None, **kwargs)

Invokes a CLI command in an isolated environment. See CliRunner.invoke for full method documentation. See Running Commands with the CLI Runner for examples.

If the obj argument is not given, passes an instance of ScriptInfo that knows how to load the Flask app being tested.

매개변수:
  • cli (Any) – Command object to invoke. Default is the app’s cli group.

  • args (Any) – List of strings to invoke the command with.

  • kwargs (Any)

반환:

a Result object.

반환 형식:

Any

Application Globals

To share data that is valid for one request only from one function to another, a global variable is not good enough because it would break in threaded environments. Flask provides you with a special object that ensures it is only valid for the active request and that will return different values for each request. In a nutshell: it does the right thing, like it does for request and session.

flask.g

A namespace object that can store data during an application context. This is an instance of Flask.app_ctx_globals_class, which defaults to ctx._AppCtxGlobals.

This is a good place to store resources during a request. For example, a before_request function could load a user object from a session id, then set g.user to be used in the view function.

This is a proxy. See Notes On Proxies for more information.

Changelog

버전 0.10에서 변경: Bound to the application context instead of the request context.

class flask.ctx._AppCtxGlobals

A plain object. Used as a namespace for storing data during an application context.

Creating an app context automatically creates this object, which is made available as the g proxy.

'key' in g

Check whether an attribute is present.

Changelog

Added in version 0.10.

iter(g)

Return an iterator over the attribute names.

Changelog

Added in version 0.10.

get(name, default=None)

Get an attribute by name, or a default value. Like dict.get().

매개변수:
  • name (str) – Name of attribute to get.

  • default (Any | None) – Value to return if the attribute is not present.

반환 형식:

Any

Changelog

Added in version 0.10.

pop(name, default=_sentinel)

Get and remove an attribute by name. Like dict.pop().

매개변수:
  • name (str) – Name of attribute to pop.

  • default (Any) – Value to return if the attribute is not present, instead of raising a KeyError.

반환 형식:

Any

Changelog

Added in version 0.11.

setdefault(name, default=None)

Get the value of an attribute if it is present, otherwise set and return a default value. Like dict.setdefault().

매개변수:
  • name (str) – Name of attribute to get.

  • default (Any) – Value to set and return if the attribute is not present.

반환 형식:

Any

Changelog

Added in version 0.11.

Useful Functions and Classes

flask.current_app

A proxy to the application handling the current request. This is useful to access the application without needing to import it, or if it can’t be imported, such as when using the application factory pattern or in blueprints and extensions.

This is only available when an application context is pushed. This happens automatically during requests and CLI commands. It can be controlled manually with app_context().

This is a proxy. See Notes On Proxies for more information.

flask.has_request_context()

If you have code that wants to test if a request context is there or not this function can be used. For instance, you may want to take advantage of request information if the request object is available, but fail silently if it is unavailable.

class User(db.Model):

    def __init__(self, username, remote_addr=None):
        self.username = username
        if remote_addr is None and has_request_context():
            remote_addr = request.remote_addr
        self.remote_addr = remote_addr

Alternatively you can also just test any of the context bound objects (such as request or g) for truthness:

class User(db.Model):

    def __init__(self, username, remote_addr=None):
        self.username = username
        if remote_addr is None and request:
            remote_addr = request.remote_addr
        self.remote_addr = remote_addr
Changelog

Added in version 0.7.

반환 형식:

bool

flask.copy_current_request_context(f)

A helper function that decorates a function to retain the current request context. This is useful when working with greenlets. The moment the function is decorated a copy of the request context is created and then pushed when the function is called. The current session is also included in the copied request context.

Example:

import gevent
from flask import copy_current_request_context

@app.route('/')
def index():
    @copy_current_request_context
    def do_some_work():
        # do some work here, it can access flask.request or
        # flask.session like you would otherwise in the view function.
        ...
    gevent.spawn(do_some_work)
    return 'Regular response'
Changelog

Added in version 0.10.

매개변수:

f (F)

반환 형식:

F

flask.has_app_context()

Works like has_request_context() but for the application context. You can also just do a boolean check on the current_app object instead.

Changelog

Added in version 0.9.

반환 형식:

bool

flask.url_for(endpoint, *, _anchor=None, _method=None, _scheme=None, _external=None, **values)

주어진 엔드포인트와 값을 사용하여 URL을 생성합니다.

This requires an active request or application context, and calls current_app.url_for(). See that method for full documentation.

매개변수:
  • endpoint (str) – 생성할 URL과 연관된 엔드포인트 이름입니다. 만약 이 이름이 ``.``으로 시작하면, 현재 블루프린트 이름(있을 경우)이 사용됩니다.

  • _anchor (str | None) – 주어진 경우, 이를 #anchor 형태로 URL에 추가합니다.

  • _method (str | None) – 주어진 경우, 이 메서드와 관련된 엔드포인트의 URL을 생성합니다.

  • _scheme (str | None) – 주어진 경우, 외부 URL일 경우 이 스킴이 URL에 적용됩니다.

  • _external (bool | None) – 주어진 경우, URL이 내부 URL로 설정될지(False) 또는 외부 URL로 설정될지(True)를 선호합니다. 외부 URL은 스킴과 도메인을 포함합니다. 활성 요청이 아닐 때는 기본적으로 URL이 외부 URL로 처리됩니다.

  • values (Any) – URL 규칙의 변수 부분에 사용할 값들입니다. 알 수 없는 키는 쿼리 문자열 인수로 추가되며, 예를 들어 ``?a=b&c=d``와 같은 형식이 됩니다.

반환 형식:

str

Changelog

버전 2.2에서 변경: Calls current_app.url_for, allowing an app to override the behavior.

버전 0.10에서 변경: The _scheme parameter was added.

버전 0.9에서 변경: The _anchor and _method parameters were added.

버전 0.9에서 변경: Calls app.handle_url_build_error on build errors.

flask.abort(code, *args, **kwargs)

Raise an HTTPException for the given status code.

If current_app is available, it will call its aborter object, otherwise it will use werkzeug.exceptions.abort().

매개변수:
  • code (int | Response) – The status code for the exception, which must be registered in app.aborter.

  • args (Any) – Passed to the exception.

  • kwargs (Any) – Passed to the exception.

반환 형식:

NoReturn

Changelog

Added in version 2.2: Calls current_app.aborter if available instead of always using Werkzeug’s default abort.

flask.redirect(location, code=302, Response=None)

리다이렉션 응답 객체를 생성합니다.

If current_app is available, it will use its redirect() method, otherwise it will use werkzeug.utils.redirect().

매개변수:
  • location (str) – 리다이렉션할 URL입니다.

  • code (int) – 리다이렉션의 상태 코드입니다.

  • Response (type[Response] | None) – The response class to use. Not used when current_app is active, which uses app.response_class.

반환 형식:

Response

Changelog

Added in version 2.2: Calls current_app.redirect if available instead of always using Werkzeug’s default redirect.

flask.make_response(*args)

Sometimes it is necessary to set additional headers in a view. Because views do not have to return response objects but can return a value that is converted into a response object by Flask itself, it becomes tricky to add headers to it. This function can be called instead of using a return and you will get a response object which you can use to attach headers.

If view looked like this and you want to add a new header:

def index():
    return render_template('index.html', foo=42)

You can now do something like this:

def index():
    response = make_response(render_template('index.html', foo=42))
    response.headers['X-Parachutes'] = 'parachutes are cool'
    return response

This function accepts the very same arguments you can return from a view function. This for example creates a response with a 404 error code:

response = make_response(render_template('not_found.html'), 404)

The other use case of this function is to force the return value of a view function into a response which is helpful with view decorators:

response = make_response(view_function())
response.headers['X-Parachutes'] = 'parachutes are cool'

Internally this function does the following things:

Changelog

Added in version 0.6.

매개변수:

args (t.Any)

반환 형식:

Response

flask.after_this_request(f)

Executes a function after this request. This is useful to modify response objects. The function is passed the response object and has to return the same or a new one.

Example:

@app.route('/')
def index():
    @after_this_request
    def add_header(response):
        response.headers['X-Foo'] = 'Parachute'
        return response
    return 'Hello World!'

This is more useful if a function other than the view function wants to modify a response. For instance think of a decorator that wants to add some headers without converting the return value into a response object.

Changelog

Added in version 0.9.

매개변수:

f (Callable[[Any], Any] | Callable[[Any], Awaitable[Any]])

반환 형식:

Callable[[Any], Any] | Callable[[Any], Awaitable[Any]]

flask.send_file(path_or_file, mimetype=None, as_attachment=False, download_name=None, conditional=True, etag=True, last_modified=None, max_age=None)

Send the contents of a file to the client.

The first argument can be a file path or a file-like object. Paths are preferred in most cases because Werkzeug can manage the file and get extra information from the path. Passing a file-like object requires that the file is opened in binary mode, and is mostly useful when building a file in memory with io.BytesIO.

Never pass file paths provided by a user. The path is assumed to be trusted, so a user could craft a path to access a file you didn’t intend. Use send_from_directory() to safely serve user-requested paths from within a directory.

If the WSGI server sets a file_wrapper in environ, it is used, otherwise Werkzeug’s built-in wrapper is used. Alternatively, if the HTTP server supports X-Sendfile, configuring Flask with USE_X_SENDFILE = True will tell the server to send the given path, which is much more efficient than reading it in Python.

매개변수:
  • path_or_file (os.PathLike[t.AnyStr] | str | t.BinaryIO) – The path to the file to send, relative to the current working directory if a relative path is given. Alternatively, a file-like object opened in binary mode. Make sure the file pointer is seeked to the start of the data.

  • mimetype (str | None) – The MIME type to send for the file. If not provided, it will try to detect it from the file name.

  • as_attachment (bool) – Indicate to a browser that it should offer to save the file instead of displaying it.

  • download_name (str | None) – The default name browsers will use when saving the file. Defaults to the passed file name.

  • conditional (bool) – Enable conditional and range responses based on request headers. Requires passing a file path and environ.

  • etag (bool | str) – Calculate an ETag for the file, which requires passing a file path. Can also be a string to use instead.

  • last_modified (datetime | int | float | None) – The last modified time to send for the file, in seconds. If not provided, it will try to detect it from the file path.

  • max_age (None | (int | t.Callable[[str | None], int | None])) – How long the client should cache the file, in seconds. If set, Cache-Control will be public, otherwise it will be no-cache to prefer conditional caching.

반환 형식:

Response

Changelog

버전 2.0에서 변경: download_name replaces the attachment_filename parameter. If as_attachment=False, it is passed with Content-Disposition: inline instead.

버전 2.0에서 변경: max_age replaces the cache_timeout parameter. conditional is enabled and max_age is not set by default.

버전 2.0에서 변경: etag replaces the add_etags parameter. It can be a string to use instead of generating one.

버전 2.0에서 변경: Passing a file-like object that inherits from TextIOBase will raise a ValueError rather than sending an empty file.

Added in version 2.0: Moved the implementation to Werkzeug. This is now a wrapper to pass some Flask-specific arguments.

버전 1.1에서 변경: filename may be a PathLike object.

버전 1.1에서 변경: Passing a BytesIO object supports range requests.

버전 1.0.3에서 변경: Filenames are encoded with ASCII instead of Latin-1 for broader compatibility with WSGI servers.

버전 1.0에서 변경: UTF-8 filenames as specified in RFC 2231 are supported.

버전 0.12에서 변경: The filename is no longer automatically inferred from file objects. If you want to use automatic MIME and etag support, pass a filename via filename_or_fp or attachment_filename.

버전 0.12에서 변경: attachment_filename is preferred over filename for MIME detection.

버전 0.9에서 변경: cache_timeout defaults to Flask.get_send_file_max_age().

버전 0.7에서 변경: MIME guessing and etag support for file-like objects was removed because it was unreliable. Pass a filename if you are able to, otherwise attach an etag yourself.

버전 0.5에서 변경: The add_etags, cache_timeout and conditional parameters were added. The default behavior is to add etags.

Added in version 0.2.

flask.send_from_directory(directory, path, **kwargs)

Send a file from within a directory using send_file().

@app.route("/uploads/<path:name>")
def download_file(name):
    return send_from_directory(
        app.config['UPLOAD_FOLDER'], name, as_attachment=True
    )

This is a secure way to serve files from a folder, such as static files or uploads. Uses safe_join() to ensure the path coming from the client is not maliciously crafted to point outside the specified directory.

If the final path does not point to an existing regular file, raises a 404 NotFound error.

매개변수:
  • directory (os.PathLike[str] | str) – The directory that path must be located under, relative to the current application’s root path. This must not be a value provided by the client, otherwise it becomes insecure.

  • path (os.PathLike[str] | str) – The path to the file to send, relative to directory.

  • kwargs (t.Any) – Arguments to pass to send_file().

반환 형식:

Response

Changelog

버전 2.0에서 변경: path replaces the filename parameter.

Added in version 2.0: Moved the implementation to Werkzeug. This is now a wrapper to pass some Flask-specific arguments.

Added in version 0.5.

Message Flashing

flask.flash(message, category='message')

Flashes a message to the next request. In order to remove the flashed message from the session and to display it to the user, the template has to call get_flashed_messages().

Changelog

버전 0.3에서 변경: category parameter added.

매개변수:
  • message (str) – the message to be flashed.

  • category (str) – the category for the message. The following values are recommended: 'message' for any kind of message, 'error' for errors, 'info' for information messages and 'warning' for warnings. However any kind of string can be used as category.

반환 형식:

None

flask.get_flashed_messages(with_categories=False, category_filter=())

Pulls all flashed messages from the session and returns them. Further calls in the same request to the function will return the same messages. By default just the messages are returned, but when with_categories is set to True, the return value will be a list of tuples in the form (category, message) instead.

Filter the flashed messages to one or more categories by providing those categories in category_filter. This allows rendering categories in separate html blocks. The with_categories and category_filter arguments are distinct:

  • with_categories controls whether categories are returned with message text (True gives a tuple, where False gives just the message text).

  • category_filter filters the messages down to only those matching the provided categories.

See Message Flashing for examples.

Changelog

버전 0.9에서 변경: category_filter parameter added.

버전 0.3에서 변경: with_categories parameter added.

매개변수:
  • with_categories (bool) – set to True to also receive categories.

  • category_filter (Iterable[str]) – filter of categories to limit return values. Only categories in the list will be returned.

반환 형식:

list[str] | list[tuple[str, str]]

JSON Support

Flask uses Python’s built-in json module for handling JSON by default. The JSON implementation can be changed by assigning a different provider to flask.Flask.json_provider_class or flask.Flask.json. The functions provided by flask.json will use methods on app.json if an app context is active.

Jinja’s |tojson filter is configured to use the app’s JSON provider. The filter marks the output with |safe. Use it to render data inside HTML <script> tags.

<script>
    const names = {{ names|tojson }};
    renderChart(names, {{ axis_data|tojson }});
</script>
flask.json.jsonify(*args, **kwargs)

Serialize the given arguments as JSON, and return a Response object with the application/json mimetype. A dict or list returned from a view will be converted to a JSON response automatically without needing to call this.

This requires an active request or application context, and calls app.json.response().

In debug mode, the output is formatted with indentation to make it easier to read. This may also be controlled by the provider.

Either positional or keyword arguments can be given, not both. If no arguments are given, None is serialized.

매개변수:
  • args (t.Any) – A single value to serialize, or multiple values to treat as a list to serialize.

  • kwargs (t.Any) – Treat as a dict to serialize.

반환 형식:

Response

Changelog

버전 2.2에서 변경: Calls current_app.json.response, allowing an app to override the behavior.

버전 2.0.2에서 변경: decimal.Decimal is supported by converting to a string.

버전 0.11에서 변경: Added support for serializing top-level arrays. This was a security risk in ancient browsers. See JSON Security.

Added in version 0.2.

flask.json.dumps(obj, **kwargs)

Serialize data as JSON.

If current_app is available, it will use its app.json.dumps() method, otherwise it will use json.dumps().

매개변수:
  • obj (Any) – The data to serialize.

  • kwargs (Any) – Arguments passed to the dumps implementation.

반환 형식:

str

Changelog

버전 2.3에서 변경: The app parameter was removed.

버전 2.2에서 변경: Calls current_app.json.dumps, allowing an app to override the behavior.

버전 2.0.2에서 변경: decimal.Decimal is supported by converting to a string.

버전 2.0에서 변경: encoding will be removed in Flask 2.1.

버전 1.0.3에서 변경: app can be passed directly, rather than requiring an app context for configuration.

flask.json.dump(obj, fp, **kwargs)

Serialize data as JSON and write to a file.

If current_app is available, it will use its app.json.dump() method, otherwise it will use json.dump().

매개변수:
  • obj (Any) – The data to serialize.

  • fp (IO[str]) – A file opened for writing text. Should use the UTF-8 encoding to be valid JSON.

  • kwargs (Any) – Arguments passed to the dump implementation.

반환 형식:

None

Changelog

버전 2.3에서 변경: The app parameter was removed.

버전 2.2에서 변경: Calls current_app.json.dump, allowing an app to override the behavior.

버전 2.0에서 변경: Writing to a binary file, and the encoding argument, will be removed in Flask 2.1.

flask.json.loads(s, **kwargs)

Deserialize data as JSON.

If current_app is available, it will use its app.json.loads() method, otherwise it will use json.loads().

매개변수:
  • s (str | bytes) – Text or UTF-8 bytes.

  • kwargs (Any) – Arguments passed to the loads implementation.

반환 형식:

Any

Changelog

버전 2.3에서 변경: The app parameter was removed.

버전 2.2에서 변경: Calls current_app.json.loads, allowing an app to override the behavior.

버전 2.0에서 변경: encoding will be removed in Flask 2.1. The data must be a string or UTF-8 bytes.

버전 1.0.3에서 변경: app can be passed directly, rather than requiring an app context for configuration.

flask.json.load(fp, **kwargs)

Deserialize data as JSON read from a file.

If current_app is available, it will use its app.json.load() method, otherwise it will use json.load().

매개변수:
  • fp (IO) – A file opened for reading text or UTF-8 bytes.

  • kwargs (Any) – Arguments passed to the load implementation.

반환 형식:

Any

Changelog

버전 2.3에서 변경: The app parameter was removed.

버전 2.2에서 변경: Calls current_app.json.load, allowing an app to override the behavior.

버전 2.2에서 변경: The app parameter will be removed in Flask 2.3.

버전 2.0에서 변경: encoding will be removed in Flask 2.1. The file must be text mode, or binary mode with UTF-8 bytes.

class flask.json.provider.JSONProvider(app)

A standard set of JSON operations for an application. Subclasses of this can be used to customize JSON behavior or use different JSON libraries.

To implement a provider for a specific library, subclass this base class and implement at least dumps() and loads(). All other methods have default implementations.

To use a different provider, either subclass Flask and set json_provider_class to a provider class, or set app.json to an instance of the class.

매개변수:

app (App) – An application instance. This will be stored as a weakref.proxy on the _app attribute.

Changelog

Added in version 2.2.

dumps(obj, **kwargs)

Serialize data as JSON.

매개변수:
  • obj (Any) – The data to serialize.

  • kwargs (Any) – May be passed to the underlying JSON library.

반환 형식:

str

dump(obj, fp, **kwargs)

Serialize data as JSON and write to a file.

매개변수:
  • obj (Any) – The data to serialize.

  • fp (IO[str]) – A file opened for writing text. Should use the UTF-8 encoding to be valid JSON.

  • kwargs (Any) – May be passed to the underlying JSON library.

반환 형식:

None

loads(s, **kwargs)

Deserialize data as JSON.

매개변수:
  • s (str | bytes) – Text or UTF-8 bytes.

  • kwargs (Any) – May be passed to the underlying JSON library.

반환 형식:

Any

load(fp, **kwargs)

Deserialize data as JSON read from a file.

매개변수:
  • fp (IO) – A file opened for reading text or UTF-8 bytes.

  • kwargs (Any) – May be passed to the underlying JSON library.

반환 형식:

Any

response(*args, **kwargs)

Serialize the given arguments as JSON, and return a Response object with the application/json mimetype.

The jsonify() function calls this method for the current application.

Either positional or keyword arguments can be given, not both. If no arguments are given, None is serialized.

매개변수:
  • args (t.Any) – A single value to serialize, or multiple values to treat as a list to serialize.

  • kwargs (t.Any) – Treat as a dict to serialize.

반환 형식:

Response

class flask.json.provider.DefaultJSONProvider(app)

Provide JSON operations using Python’s built-in json library. Serializes the following additional data types:

매개변수:

app (App)

static default(o)

Apply this function to any object that json.dumps() does not know how to serialize. It should return a valid JSON type or raise a TypeError.

매개변수:

o (Any)

반환 형식:

Any

ensure_ascii = True

Replace non-ASCII characters with escape sequences. This may be more compatible with some clients, but can be disabled for better performance and size.

sort_keys = True

Sort the keys in any serialized dicts. This may be useful for some caching situations, but can be disabled for better performance. When enabled, keys must all be strings, they are not converted before sorting.

compact: bool | None = None

If True, or None out of debug mode, the response() output will not add indentation, newlines, or spaces. If False, or None in debug mode, it will use a non-compact representation.

mimetype = 'application/json'

The mimetype set in response().

dumps(obj, **kwargs)

Serialize data as JSON to a string.

Keyword arguments are passed to json.dumps(). Sets some parameter defaults from the default, ensure_ascii, and sort_keys attributes.

매개변수:
반환 형식:

str

loads(s, **kwargs)

Deserialize data as JSON from a string or bytes.

매개변수:
반환 형식:

Any

response(*args, **kwargs)

Serialize the given arguments as JSON, and return a Response object with it. The response mimetype will be “application/json” and can be changed with mimetype.

If compact is False or debug mode is enabled, the output will be formatted to be easier to read.

Either positional or keyword arguments can be given, not both. If no arguments are given, None is serialized.

매개변수:
  • args (t.Any) – A single value to serialize, or multiple values to treat as a list to serialize.

  • kwargs (t.Any) – Treat as a dict to serialize.

반환 형식:

Response

Tagged JSON

A compact representation for lossless serialization of non-standard JSON types. SecureCookieSessionInterface uses this to serialize the session data, but it may be useful in other places. It can be extended to support other types.

class flask.json.tag.TaggedJSONSerializer

Serializer that uses a tag system to compactly represent objects that are not JSON types. Passed as the intermediate serializer to itsdangerous.Serializer.

The following extra types are supported:

default_tags = [<class 'flask.json.tag.TagDict'>, <class 'flask.json.tag.PassDict'>, <class 'flask.json.tag.TagTuple'>, <class 'flask.json.tag.PassList'>, <class 'flask.json.tag.TagBytes'>, <class 'flask.json.tag.TagMarkup'>, <class 'flask.json.tag.TagUUID'>, <class 'flask.json.tag.TagDateTime'>]

Tag classes to bind when creating the serializer. Other tags can be added later using register().

register(tag_class, force=False, index=None)

Register a new tag with this serializer.

매개변수:
  • tag_class (type[JSONTag]) – tag class to register. Will be instantiated with this serializer instance.

  • force (bool) – overwrite an existing tag. If false (default), a KeyError is raised.

  • index (int | None) – index to insert the new tag in the tag order. Useful when the new tag is a special case of an existing tag. If None (default), the tag is appended to the end of the order.

예외 발생:

KeyError – if the tag key is already registered and force is not true.

반환 형식:

None

tag(value)

Convert a value to a tagged representation if necessary.

매개변수:

value (Any)

반환 형식:

Any

untag(value)

Convert a tagged representation back to the original type.

매개변수:

value (dict[str, Any])

반환 형식:

Any

dumps(value)

Tag the value and dump it to a compact JSON string.

매개변수:

value (Any)

반환 형식:

str

loads(value)

Load data from a JSON string and deserialized any tagged objects.

매개변수:

value (str)

반환 형식:

Any

class flask.json.tag.JSONTag(serializer)

Base class for defining type tags for TaggedJSONSerializer.

매개변수:

serializer (TaggedJSONSerializer)

key: str = ''

The tag to mark the serialized object with. If empty, this tag is only used as an intermediate step during tagging.

check(value)

Check if the given value should be tagged by this tag.

매개변수:

value (Any)

반환 형식:

bool

to_json(value)

Convert the Python object to an object that is a valid JSON type. The tag will be added later.

매개변수:

value (Any)

반환 형식:

Any

to_python(value)

Convert the JSON representation back to the correct type. The tag will already be removed.

매개변수:

value (Any)

반환 형식:

Any

tag(value)

Convert the value to a valid JSON type and add the tag structure around it.

매개변수:

value (Any)

반환 형식:

dict[str, Any]

Let’s see an example that adds support for OrderedDict. Dicts don’t have an order in JSON, so to handle this we will dump the items as a list of [key, value] pairs. Subclass JSONTag and give it the new key ' od' to identify the type. The session serializer processes dicts first, so insert the new tag at the front of the order since OrderedDict must be processed before dict.

from flask.json.tag import JSONTag

class TagOrderedDict(JSONTag):
    __slots__ = ('serializer',)
    key = ' od'

    def check(self, value):
        return isinstance(value, OrderedDict)

    def to_json(self, value):
        return [[k, self.serializer.tag(v)] for k, v in iteritems(value)]

    def to_python(self, value):
        return OrderedDict(value)

app.session_interface.serializer.register(TagOrderedDict, index=0)

Template Rendering

flask.render_template(template_name_or_list, **context)

Render a template by name with the given context.

매개변수:
  • template_name_or_list (str | Template | list[str | Template]) – The name of the template to render. If a list is given, the first name to exist will be rendered.

  • context (Any) – The variables to make available in the template.

반환 형식:

str

flask.render_template_string(source, **context)

Render a template from the given source string with the given context.

매개변수:
  • source (str) – The source code of the template to render.

  • context (Any) – The variables to make available in the template.

반환 형식:

str

flask.stream_template(template_name_or_list, **context)

Render a template by name with the given context as a stream. This returns an iterator of strings, which can be used as a streaming response from a view.

매개변수:
  • template_name_or_list (str | Template | list[str | Template]) – The name of the template to render. If a list is given, the first name to exist will be rendered.

  • context (Any) – The variables to make available in the template.

반환 형식:

Iterator[str]

Changelog

Added in version 2.2.

flask.stream_template_string(source, **context)

Render a template from the given source string with the given context as a stream. This returns an iterator of strings, which can be used as a streaming response from a view.

매개변수:
  • source (str) – The source code of the template to render.

  • context (Any) – The variables to make available in the template.

반환 형식:

Iterator[str]

Changelog

Added in version 2.2.

flask.get_template_attribute(template_name, attribute)

Loads a macro (or variable) a template exports. This can be used to invoke a macro from within Python code. If you for example have a template named _cider.html with the following contents:

{% macro hello(name) %}Hello {{ name }}!{% endmacro %}

You can access this from Python code like this:

hello = get_template_attribute('_cider.html', 'hello')
return hello('World')
Changelog

Added in version 0.2.

매개변수:
  • template_name (str) – the name of the template

  • attribute (str) – the name of the variable of macro to access

반환 형식:

Any

Configuration

class flask.Config(root_path, defaults=None)

Works exactly like a dict but provides ways to fill it from files or special dictionaries. There are two common patterns to populate the config.

Either you can fill the config from a config file:

app.config.from_pyfile('yourconfig.cfg')

Or alternatively you can define the configuration options in the module that calls from_object() or provide an import path to a module that should be loaded. It is also possible to tell it to use the same module and with that provide the configuration values just before the call:

DEBUG = True
SECRET_KEY = 'development key'
app.config.from_object(__name__)

In both cases (loading from any Python file or loading from modules), only uppercase keys are added to the config. This makes it possible to use lowercase values in the config file for temporary values that are not added to the config or to define the config keys in the same file that implements the application.

Probably the most interesting way to load configurations is from an environment variable pointing to a file:

app.config.from_envvar('YOURAPPLICATION_SETTINGS')

In this case before launching the application you have to set this environment variable to the file you want to use. On Linux and OS X use the export statement:

export YOURAPPLICATION_SETTINGS='/path/to/config/file'

On windows use set instead.

매개변수:
  • root_path (str | os.PathLike[str]) – path to which files are read relative from. When the config object is created by the application, this is the application’s root_path.

  • defaults (dict[str, t.Any] | None) – an optional dictionary of default values

from_envvar(variable_name, silent=False)

Loads a configuration from an environment variable pointing to a configuration file. This is basically just a shortcut with nicer error messages for this line of code:

app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])
매개변수:
  • variable_name (str) – name of the environment variable

  • silent (bool) – set to True if you want silent failure for missing files.

반환:

True if the file was loaded successfully.

반환 형식:

bool

from_prefixed_env(prefix='FLASK', *, loads=json.loads)

Load any environment variables that start with FLASK_, dropping the prefix from the env key for the config key. Values are passed through a loading function to attempt to convert them to more specific types than strings.

Keys are loaded in sorted() order.

The default loading function attempts to parse values as any valid JSON type, including dicts and lists.

Specific items in nested dicts can be set by separating the keys with double underscores (__). If an intermediate key doesn’t exist, it will be initialized to an empty dict.

매개변수:
  • prefix (str) – Load env vars that start with this prefix, separated with an underscore (_).

  • loads (Callable[[str], Any]) – Pass each string value to this function and use the returned value as the config value. If any error is raised it is ignored and the value remains a string. The default is json.loads().

반환 형식:

bool

Changelog

Added in version 2.1.

from_pyfile(filename, silent=False)

Updates the values in the config from a Python file. This function behaves as if the file was imported as module with the from_object() function.

매개변수:
  • filename (str | PathLike[str]) – the filename of the config. This can either be an absolute filename or a filename relative to the root path.

  • silent (bool) – set to True if you want silent failure for missing files.

반환:

True if the file was loaded successfully.

반환 형식:

bool

Changelog

Added in version 0.7: silent parameter.

from_object(obj)

Updates the values from the given object. An object can be of one of the following two types:

  • a string: in this case the object with that name will be imported

  • an actual object reference: that object is used directly

Objects are usually either modules or classes. from_object() loads only the uppercase attributes of the module/class. A dict object will not work with from_object() because the keys of a dict are not attributes of the dict class.

Example of module-based configuration:

app.config.from_object('yourapplication.default_config')
from yourapplication import default_config
app.config.from_object(default_config)

Nothing is done to the object before loading. If the object is a class and has @property attributes, it needs to be instantiated before being passed to this method.

You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with from_pyfile() and ideally from a location not within the package because the package might be installed system wide.

See Development / Production for an example of class-based configuration using from_object().

매개변수:

obj (object | str) – an import name or object

반환 형식:

None

from_file(filename, load, silent=False, text=True)

Update the values in the config from a file that is loaded using the load parameter. The loaded data is passed to the from_mapping() method.

import json
app.config.from_file("config.json", load=json.load)

import tomllib
app.config.from_file("config.toml", load=tomllib.load, text=False)
매개변수:
  • filename (str | PathLike[str]) – The path to the data file. This can be an absolute path or relative to the config root path.

  • load (Callable[[Reader], Mapping] where Reader implements a read method.) – A callable that takes a file handle and returns a mapping of loaded data from the file.

  • silent (bool) – Ignore the file if it doesn’t exist.

  • text (bool) – Open the file in text or binary mode.

반환:

True if the file was loaded successfully.

반환 형식:

bool

Changelog

버전 2.3에서 변경: The text parameter was added.

Added in version 2.0.

from_mapping(mapping=None, **kwargs)

Updates the config like update() ignoring items with non-upper keys.

반환:

Always returns True.

매개변수:
반환 형식:

bool

Changelog

Added in version 0.11.

get_namespace(namespace, lowercase=True, trim_namespace=True)

Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix. Example usage:

app.config['IMAGE_STORE_TYPE'] = 'fs'
app.config['IMAGE_STORE_PATH'] = '/var/app/images'
app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'
image_store_config = app.config.get_namespace('IMAGE_STORE_')

The resulting dictionary image_store_config would look like:

{
    'type': 'fs',
    'path': '/var/app/images',
    'base_url': 'http://img.website.com'
}

This is often useful when configuration options map directly to keyword arguments in functions or class constructors.

매개변수:
  • namespace (str) – a configuration namespace

  • lowercase (bool) – a flag indicating if the keys of the resulting dictionary should be lowercase

  • trim_namespace (bool) – a flag indicating if the keys of the resulting dictionary should not include the namespace

반환 형식:

dict[str, Any]

Changelog

Added in version 0.11.

Stream Helpers

flask.stream_with_context(generator_or_function: Iterator) Iterator
flask.stream_with_context(generator_or_function: Callable[[...], Iterator]) Callable[[Iterator], Iterator]

Request contexts disappear when the response is started on the server. This is done for efficiency reasons and to make it less likely to encounter memory leaks with badly written WSGI middlewares. The downside is that if you are using streamed responses, the generator cannot access request bound information any more.

This function however can help you keep the context around for longer:

from flask import stream_with_context, request, Response

@app.route('/stream')
def streamed_response():
    @stream_with_context
    def generate():
        yield 'Hello '
        yield request.args['name']
        yield '!'
    return Response(generate())

Alternatively it can also be used around a specific generator:

from flask import stream_with_context, request, Response

@app.route('/stream')
def streamed_response():
    def generate():
        yield 'Hello '
        yield request.args['name']
        yield '!'
    return Response(stream_with_context(generate()))
Changelog

Added in version 0.9.

Useful Internals

class flask.ctx.RequestContext(app, environ, request=None, session=None)

The request context contains per-request information. The Flask app creates and pushes it at the beginning of the request, then pops it at the end of the request. It will create the URL adapter and request object for the WSGI environment provided.

Do not attempt to use this class directly, instead use test_request_context() and request_context() to create this object.

When the request context is popped, it will evaluate all the functions registered on the application for teardown execution (teardown_request()).

The request context is automatically popped at the end of the request. When using the interactive debugger, the context will be restored so request is still accessible. Similarly, the test client can preserve the context after the request ends. However, teardown functions may already have closed some resources such as database connections.

매개변수:
copy()

Creates a copy of this request context with the same request object. This can be used to move a request context to a different greenlet. Because the actual request object is the same this cannot be used to move a request context to a different thread unless access to the request object is locked.

Changelog

버전 1.1에서 변경: The current session object is used instead of reloading the original data. This prevents flask.session pointing to an out-of-date object.

Added in version 0.10.

반환 형식:

RequestContext

match_request()

Can be overridden by a subclass to hook into the matching of the request.

반환 형식:

None

pop(exc=_sentinel)

Pops the request context and unbinds it by doing that. This will also trigger the execution of functions registered by the teardown_request() decorator.

Changelog

버전 0.9에서 변경: Added the exc argument.

매개변수:

exc (BaseException | None)

반환 형식:

None

flask.globals.request_ctx

The current RequestContext. If a request context is not active, accessing attributes on this proxy will raise a RuntimeError.

This is an internal object that is essential to how Flask handles requests. Accessing this should not be needed in most cases. Most likely you want request and session instead.

class flask.ctx.AppContext(app)

The app context contains application-specific information. An app context is created and pushed at the beginning of each request if one is not already active. An app context is also pushed when running CLI commands.

매개변수:

app (Flask)

push()

Binds the app context to the current context.

반환 형식:

None

pop(exc=_sentinel)

Pops the app context.

매개변수:

exc (BaseException | None)

반환 형식:

None

flask.globals.app_ctx

The current AppContext. If an app context is not active, accessing attributes on this proxy will raise a RuntimeError.

This is an internal object that is essential to how Flask handles requests. Accessing this should not be needed in most cases. Most likely you want current_app and g instead.

class flask.blueprints.BlueprintSetupState(blueprint, app, options, first_registration)

Temporary holder object for registering a blueprint with the application. An instance of this class is created by the make_setup_state() method and later passed to all register callback functions.

매개변수:
  • blueprint (Blueprint)

  • app (App)

  • options (t.Any)

  • first_registration (bool)

app

a reference to the current application

blueprint

a reference to the blueprint that created this setup state.

options

a dictionary with all options that were passed to the register_blueprint() method.

first_registration

as blueprints can be registered multiple times with the application and not everything wants to be registered multiple times on it, this attribute can be used to figure out if the blueprint was registered in the past already.

subdomain

The subdomain that the blueprint should be active for, None otherwise.

url_prefix

The prefix that should be used for all URLs defined on the blueprint.

url_defaults

A dictionary with URL defaults that is added to each and every URL that was defined with the blueprint.

add_url_rule(rule, endpoint=None, view_func=None, **options)

A helper method to register a rule (and optionally a view function) to the application. The endpoint is automatically prefixed with the blueprint’s name.

매개변수:
  • rule (str)

  • endpoint (str | None)

  • view_func (ft.RouteCallable | None)

  • options (t.Any)

반환 형식:

None

Signals

Signals are provided by the Blinker library. See Signals for an introduction.

flask.template_rendered

This signal is sent when a template was successfully rendered. The signal is invoked with the instance of the template as template and the context as dictionary (named context).

Example subscriber:

def log_template_renders(sender, template, context, **extra):
    sender.logger.debug('Rendering template "%s" with context %s',
                        template.name or 'string template',
                        context)

from flask import template_rendered
template_rendered.connect(log_template_renders, app)
flask.before_render_template

This signal is sent before template rendering process. The signal is invoked with the instance of the template as template and the context as dictionary (named context).

Example subscriber:

def log_template_renders(sender, template, context, **extra):
    sender.logger.debug('Rendering template "%s" with context %s',
                        template.name or 'string template',
                        context)

from flask import before_render_template
before_render_template.connect(log_template_renders, app)
flask.request_started

This signal is sent when the request context is set up, before any request processing happens. Because the request context is already bound, the subscriber can access the request with the standard global proxies such as request.

Example subscriber:

def log_request(sender, **extra):
    sender.logger.debug('Request context is set up')

from flask import request_started
request_started.connect(log_request, app)
flask.request_finished

This signal is sent right before the response is sent to the client. It is passed the response to be sent named response.

Example subscriber:

def log_response(sender, response, **extra):
    sender.logger.debug('Request context is about to close down. '
                        'Response: %s', response)

from flask import request_finished
request_finished.connect(log_response, app)
flask.got_request_exception

This signal is sent when an unhandled exception happens during request processing, including when debugging. The exception is passed to the subscriber as exception.

This signal is not sent for HTTPException, or other exceptions that have error handlers registered, unless the exception was raised from an error handler.

This example shows how to do some extra logging if a theoretical SecurityException was raised:

from flask import got_request_exception

def log_security_exception(sender, exception, **extra):
    if not isinstance(exception, SecurityException):
        return

    security_logger.exception(
        f"SecurityException at {request.url!r}",
        exc_info=exception,
    )

got_request_exception.connect(log_security_exception, app)
flask.request_tearing_down

This signal is sent when the request is tearing down. This is always called, even if an exception is caused. Currently functions listening to this signal are called after the regular teardown handlers, but this is not something you can rely on.

Example subscriber:

def close_db_connection(sender, **extra):
    session.close()

from flask import request_tearing_down
request_tearing_down.connect(close_db_connection, app)

As of Flask 0.9, this will also be passed an exc keyword argument that has a reference to the exception that caused the teardown if there was one.

flask.appcontext_tearing_down

This signal is sent when the app context is tearing down. This is always called, even if an exception is caused. Currently functions listening to this signal are called after the regular teardown handlers, but this is not something you can rely on.

Example subscriber:

def close_db_connection(sender, **extra):
    session.close()

from flask import appcontext_tearing_down
appcontext_tearing_down.connect(close_db_connection, app)

This will also be passed an exc keyword argument that has a reference to the exception that caused the teardown if there was one.

flask.appcontext_pushed

This signal is sent when an application context is pushed. The sender is the application. This is usually useful for unittests in order to temporarily hook in information. For instance it can be used to set a resource early onto the g object.

Example usage:

from contextlib import contextmanager
from flask import appcontext_pushed

@contextmanager
def user_set(app, user):
    def handler(sender, **kwargs):
        g.user = user
    with appcontext_pushed.connected_to(handler, app):
        yield

And in the testcode:

def test_user_me(self):
    with user_set(app, 'john'):
        c = app.test_client()
        resp = c.get('/users/me')
        assert resp.data == 'username=john'
Changelog

Added in version 0.10.

flask.appcontext_popped

This signal is sent when an application context is popped. The sender is the application. This usually falls in line with the appcontext_tearing_down signal.

Changelog

Added in version 0.10.

flask.message_flashed

This signal is sent when the application is flashing a message. The messages is sent as message keyword argument and the category as category.

Example subscriber:

recorded = []
def record(sender, message, category, **extra):
    recorded.append((message, category))

from flask import message_flashed
message_flashed.connect(record, app)
Changelog

Added in version 0.10.

Class-Based Views

Changelog

Added in version 0.7.

class flask.views.View

Subclass this class and override dispatch_request() to create a generic class-based view. Call as_view() to create a view function that creates an instance of the class with the given arguments and calls its dispatch_request method with any URL variables.

See Class-based Views for a detailed guide.

class Hello(View):
    init_every_request = False

    def dispatch_request(self, name):
        return f"Hello, {name}!"

app.add_url_rule(
    "/hello/<name>", view_func=Hello.as_view("hello")
)

Set methods on the class to change what methods the view accepts.

Set decorators on the class to apply a list of decorators to the generated view function. Decorators applied to the class itself will not be applied to the generated view function!

Set init_every_request to False for efficiency, unless you need to store request-global data on self.

methods: ClassVar[Collection[str] | None] = None

The methods this view is registered for. Uses the same default (["GET", "HEAD", "OPTIONS"]) as route and add_url_rule by default.

provide_automatic_options: ClassVar[bool | None] = None

Control whether the OPTIONS method is handled automatically. Uses the same default (True) as route and add_url_rule by default.

decorators: ClassVar[list[Callable[[...], Any]]] = []

A list of decorators to apply, in order, to the generated view function. Remember that @decorator syntax is applied bottom to top, so the first decorator in the list would be the bottom decorator.

Changelog

Added in version 0.8.

init_every_request: ClassVar[bool] = True

Create a new instance of this view class for every request by default. If a view subclass sets this to False, the same instance is used for every request.

A single instance is more efficient, especially if complex setup is done during init. However, storing data on self is no longer safe across requests, and g should be used instead.

Changelog

Added in version 2.2.

dispatch_request()

The actual view function behavior. Subclasses must override this and return a valid response. Any variables from the URL rule are passed as keyword arguments.

반환 형식:

ft.ResponseReturnValue

classmethod as_view(name, *class_args, **class_kwargs)

Convert the class into a view function that can be registered for a route.

By default, the generated view will create a new instance of the view class for every request and call its dispatch_request() method. If the view class sets init_every_request to False, the same instance will be used for every request.

Except for name, all other arguments passed to this method are forwarded to the view class __init__ method.

Changelog

버전 2.2에서 변경: Added the init_every_request class attribute.

매개변수:
  • name (str)

  • class_args (t.Any)

  • class_kwargs (t.Any)

반환 형식:

ft.RouteCallable

class flask.views.MethodView

Dispatches request methods to the corresponding instance methods. For example, if you implement a get method, it will be used to handle GET requests.

This can be useful for defining a REST API.

methods is automatically set based on the methods defined on the class.

See Class-based Views for a detailed guide.

class CounterAPI(MethodView):
    def get(self):
        return str(session.get("counter", 0))

    def post(self):
        session["counter"] = session.get("counter", 0) + 1
        return redirect(url_for("counter"))

app.add_url_rule(
    "/counter", view_func=CounterAPI.as_view("counter")
)
dispatch_request(**kwargs)

The actual view function behavior. Subclasses must override this and return a valid response. Any variables from the URL rule are passed as keyword arguments.

매개변수:

kwargs (t.Any)

반환 형식:

ft.ResponseReturnValue

URL Route Registrations

Generally there are three ways to define rules for the routing system:

  1. You can use the flask.Flask.route() decorator.

  2. You can use the flask.Flask.add_url_rule() function.

  3. You can directly access the underlying Werkzeug routing system which is exposed as flask.Flask.url_map.

Variable parts in the route can be specified with angular brackets (/user/<username>). By default a variable part in the URL accepts any string without a slash however a different converter can be specified as well by using <converter:name>.

Variable parts are passed to the view function as keyword arguments.

The following converters are available:

string

accepts any text without a slash (the default)

int

accepts integers

float

like int but for floating point values

path

like the default but also accepts slashes

any

matches one of the items provided

uuid

accepts UUID strings

Custom converters can be defined using flask.Flask.url_map.

Here are some examples:

@app.route('/')
def index():
    pass

@app.route('/<username>')
def show_user(username):
    pass

@app.route('/post/<int:post_id>')
def show_post(post_id):
    pass

An important detail to keep in mind is how Flask deals with trailing slashes. The idea is to keep each URL unique so the following rules apply:

  1. If a rule ends with a slash and is requested without a slash by the user, the user is automatically redirected to the same page with a trailing slash attached.

  2. If a rule does not end with a trailing slash and the user requests the page with a trailing slash, a 404 not found is raised.

This is consistent with how web servers deal with static files. This also makes it possible to use relative link targets safely.

You can also define multiple rules for the same function. They have to be unique however. Defaults can also be specified. Here for example is a definition for a URL that accepts an optional page:

@app.route('/users/', defaults={'page': 1})
@app.route('/users/page/<int:page>')
def show_users(page):
    pass

This specifies that /users/ will be the URL for page one and /users/page/N will be the URL for page N.

If a URL contains a default value, it will be redirected to its simpler form with a 301 redirect. In the above example, /users/page/1 will be redirected to /users/. If your route handles GET and POST requests, make sure the default route only handles GET, as redirects can’t preserve form data.

@app.route('/region/', defaults={'id': 1})
@app.route('/region/<int:id>', methods=['GET', 'POST'])
def region(id):
   pass

Here are the parameters that route() and add_url_rule() accept. The only difference is that with the route parameter the view function is defined with the decorator instead of the view_func parameter.

rule

the URL rule as string

endpoint

the endpoint for the registered URL rule. Flask itself assumes that the name of the view function is the name of the endpoint if not explicitly stated.

view_func

the function to call when serving a request to the provided endpoint. If this is not provided one can specify the function later by storing it in the view_functions dictionary with the endpoint as key.

defaults

A dictionary with defaults for this rule. See the example above for how defaults work.

subdomain

specifies the rule for the subdomain in case subdomain matching is in use. If not specified the default subdomain is assumed.

**options

the options to be forwarded to the underlying Rule object. A change to Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (GET, POST etc.). By default a rule just listens for GET (and implicitly HEAD). Starting with Flask 0.6, OPTIONS is implicitly added and handled by the standard request handling. They have to be specified as keyword arguments.

View Function Options

For internal usage the view functions can have some attributes attached to customize behavior the view function would normally not have control over. The following attributes can be provided optionally to either override some defaults to add_url_rule() or general behavior:

  • __name__: The name of a function is by default used as endpoint. If endpoint is provided explicitly this value is used. Additionally this will be prefixed with the name of the blueprint by default which cannot be customized from the function itself.

  • methods: If methods are not provided when the URL rule is added, Flask will look on the view function object itself if a methods attribute exists. If it does, it will pull the information for the methods from there.

  • provide_automatic_options: if this attribute is set Flask will either force enable or disable the automatic implementation of the HTTP OPTIONS response. This can be useful when working with decorators that want to customize the OPTIONS response on a per-view basis.

  • required_methods: if this attribute is set, Flask will always add these methods when registering a URL rule even if the methods were explicitly overridden in the route() call.

Full example:

def index():
    if request.method == 'OPTIONS':
        # custom options handling here
        ...
    return 'Hello World!'
index.provide_automatic_options = False
index.methods = ['GET', 'OPTIONS']

app.add_url_rule('/', index)
Changelog

Added in version 0.8: The provide_automatic_options functionality was added.

Command Line Interface

class flask.cli.FlaskGroup(add_default_commands=True, create_app=None, add_version_option=True, load_dotenv=True, set_debug_flag=True, **extra)

Special subclass of the AppGroup group that supports loading more commands from the configured Flask app. Normally a developer does not have to interface with this class but there are some very advanced use cases for which it makes sense to create an instance of this. see Custom Scripts.

매개변수:
  • add_default_commands (bool) – if this is True then the default run and shell commands will be added.

  • add_version_option (bool) – adds the --version option.

  • create_app (t.Callable[..., Flask] | None) – an optional callback that is passed the script info and returns the loaded app.

  • load_dotenv (bool) – 가장 가까운 .env.flaskenv 파일을 로드하여 환경 변수를 설정합니다. 또한, 첫 번째로 발견된 파일이 위치한 디렉터리로 작업 디렉터리를 변경합니다.

  • set_debug_flag (bool) – Set the app’s debug flag.

  • extra (t.Any)

버전 3.1에서 변경: -e path takes precedence over default .env and .flaskenv files.

Changelog

버전 2.2에서 변경: Added the -A/--app, --debug/--no-debug, -e/--env-file options.

버전 2.2에서 변경: An app context is pushed when running app.cli commands, so @with_appcontext is no longer required for those commands.

버전 1.0에서 변경: python-dotenv`이 설치되어 있으면 :file:.env` 및 .flaskenv 파일에서 환경 변수를 로드하는 데 사용됩니다.

get_command(ctx, name)

Given a context and a command name, this returns a Command object if it exists or returns None.

매개변수:
반환 형식:

Command | None

list_commands(ctx)

Returns a list of subcommand names in the order they should appear.

매개변수:

ctx (Context)

반환 형식:

list[str]

make_context(info_name, args, parent=None, **extra)

This function when given an info name and arguments will kick off the parsing and create a new Context. It does not invoke the actual command callback though.

To quickly customize the context class used without overriding this method, set the context_class attribute.

매개변수:
  • info_name (str | None) – the info name for this invocation. Generally this is the most descriptive name for the script or command. For the toplevel script it’s usually the name of the script, for commands below it’s the name of the command.

  • args (list[str]) – the arguments to parse as list of strings.

  • parent (Context | None) – the parent context if available.

  • extra (Any) – extra keyword arguments forwarded to the context constructor.

반환 형식:

Context

버전 8.0에서 변경: Added the context_class attribute.

class flask.cli.AppGroup(name=None, commands=None, invoke_without_command=False, no_args_is_help=None, subcommand_metavar=None, chain=False, result_callback=None, **kwargs)

This works similar to a regular click Group but it changes the behavior of the command() decorator so that it automatically wraps the functions in with_appcontext().

Not to be confused with FlaskGroup.

매개변수:
  • name (str | None)

  • commands (cabc.MutableMapping[str, Command] | cabc.Sequence[Command] | None)

  • invoke_without_command (bool)

  • no_args_is_help (bool | None)

  • subcommand_metavar (str | None)

  • chain (bool)

  • result_callback (t.Callable[..., t.Any] | None)

  • kwargs (t.Any)

command(*args, **kwargs)

This works exactly like the method of the same name on a regular click.Group but it wraps callbacks in with_appcontext() unless it’s disabled by passing with_appcontext=False.

매개변수:
반환 형식:

Callable[[Callable[[…], Any]], Command]

group(*args, **kwargs)

This works exactly like the method of the same name on a regular click.Group but it defaults the group class to AppGroup.

매개변수:
반환 형식:

Callable[[Callable[[…], Any]], Group]

class flask.cli.ScriptInfo(app_import_path=None, create_app=None, set_debug_flag=True, load_dotenv_defaults=True)

Helper object to deal with Flask applications. This is usually not necessary to interface with as it’s used internally in the dispatching to click. In future versions of Flask this object will most likely play a bigger role. Typically it’s created automatically by the FlaskGroup but you can also manually create it and pass it onwards as click object.

버전 3.1에서 변경: Added the load_dotenv_defaults parameter and attribute.

매개변수:
  • app_import_path (str | None)

  • create_app (t.Callable[..., Flask] | None)

  • set_debug_flag (bool)

  • load_dotenv_defaults (bool)

app_import_path

Optionally the import path for the Flask application.

create_app

Optionally a function that is passed the script info to create the instance of the application.

data: dict[t.Any, t.Any]

A dictionary with arbitrary data that can be associated with this script info.

load_dotenv_defaults

Whether default .flaskenv and .env files should be loaded.

ScriptInfo doesn’t load anything, this is for reference when doing the load elsewhere during processing.

Added in version 3.1.

load_app()

Loads the Flask app (if not yet loaded) and returns it. Calling this multiple times will just result in the already loaded app to be returned.

반환 형식:

Flask

flask.cli.load_dotenv(path=None, load_defaults=True)

Load “dotenv” files to set environment variables. A given path takes precedence over .env, which takes precedence over .flaskenv. After loading and combining these files, values are only set if the key is not already set in os.environ.

This is a no-op if python-dotenv is not installed.

매개변수:
  • path (str | PathLike[str] | None) – Load the file at this location.

  • load_defaults (bool) – Search for and load the default .flaskenv and .env files.

반환:

True if at least one env var was loaded.

반환 형식:

bool

버전 3.1에서 변경: Added the load_defaults parameter. A given path takes precedence over default files.

Changelog

버전 2.0에서 변경: The current directory is not changed to the location of the loaded file.

버전 2.0에서 변경: When loading the env files, set the default encoding to UTF-8.

버전 1.1.0에서 변경: Returns False when python-dotenv is not installed, or when the given path isn’t a file.

Added in version 1.0.

flask.cli.with_appcontext(f)

Wraps a callback so that it’s guaranteed to be executed with the script’s application context.

Custom commands (and their options) registered under app.cli or blueprint.cli will always have an app context available, this decorator is not required in that case.

Changelog

버전 2.2에서 변경: The app context is active for subcommands as well as the decorated callback. The app context is always available to app.cli command and parameter callbacks.

매개변수:

f (F)

반환 형식:

F

flask.cli.pass_script_info(f)

Marks a function so that an instance of ScriptInfo is passed as first argument to the click callback.

매개변수:

f (t.Callable[te.Concatenate[T, P], R])

반환 형식:

t.Callable[P, R]

flask.cli.run_command = <Command run>

Run a local development server.

This server is for development purposes only. It does not provide the stability, security, or performance of production WSGI servers.

The reloader and debugger are enabled by default with the ‘–debug’ option.

매개변수:
  • args (t.Any)

  • kwargs (t.Any)

반환 형식:

t.Any

flask.cli.shell_command = <Command shell>

Run an interactive Python shell in the context of a given Flask application. The application will populate the default namespace of this shell according to its configuration.

This is useful for executing small snippets of management code without having to manually configure the application.

매개변수:
  • args (t.Any)

  • kwargs (t.Any)

반환 형식:

t.Any