쉘 사용하기

Beginner

This tutorial is from open-source community. Access the source code

소개

Python Flask 튜토리얼 "Working with the Shell"은 Flask 에서 대화형 쉘을 사용하여 Python 명령을 실시간으로 실행하는 방법에 대한 지침을 제공합니다. 이 튜토리얼은 요청 컨텍스트를 생성하고, 요청 전/후 함수를 실행하며, 쉘 경험을 향상시키는 방법을 설명합니다.

참고: 코드 파일을 직접 생성하고 환경에서 실행해야 합니다. Web 5000 에서 Flask 서비스 상태를 미리 볼 수 있습니다.

쉘 시작하기

쉘을 시작하려면 flask shell 명령을 사용하십시오. 이 명령은 로드된 애플리케이션 컨텍스트 (application context) 로 쉘을 자동으로 초기화합니다.

명령줄 인터페이스 (Command Line Interface):

flask shell

요청 컨텍스트 생성하기

쉘에서 적절한 요청 컨텍스트를 생성하려면 test_request_context() 메서드를 사용하십시오. 이 메서드는 RequestContext 객체를 생성합니다. 쉘에서는 push()pop() 메서드를 사용하여 요청 컨텍스트를 수동으로 푸시 (push) 하고 팝 (pop) 합니다.

## File: shell.py
## Execution: python shell.py

from flask import Flask

app = Flask(__name__)

## Create a request context
ctx = app.test_request_context()

## Push the request context
ctx.push()

## Work with the request object

## Pop the request context
ctx.pop()

요청 전/후 함수 실행하기

요청 컨텍스트를 생성하면 일반적으로 요청 전에 실행되는 코드가 트리거되지 않습니다. before-request 기능을 시뮬레이션하려면 preprocess_request() 메서드를 호출하십시오. 이렇게 하면 데이터베이스 연결 및 기타 리소스를 사용할 수 있습니다.

## File: shell.py
## Execution: python shell.py

from flask import Flask

app = Flask(__name__)

## Create a request context
ctx = app.test_request_context()
ctx.push()

## Simulate the before-request functionality
app.preprocess_request()

## Work with the request object

## Pop the request context
ctx.pop()

after-request 기능을 시뮬레이션하려면 요청 컨텍스트를 팝하기 전에 더미 응답 객체와 함께 process_response() 메서드를 호출하십시오.

## File: shell.py
## Execution: python shell.py

from flask import Flask

app = Flask(__name__)

## Create a request context
ctx = app.test_request_context()
ctx.push()

## Simulate the before-request functionality
app.preprocess_request()

## Work with the request object

## Simulate the after-request functionality
app.process_response(app.response_class())

## Pop the request context
ctx.pop()

쉘 경험 향상시키기

쉘 경험을 향상시키려면 대화형 세션으로 가져올 수 있는 헬퍼 메서드가 있는 모듈 (shelltools.py) 을 생성하십시오. 이 모듈에는 데이터베이스 초기화 또는 테이블 삭제와 같은 작업에 대한 추가 헬퍼 메서드가 포함될 수 있습니다.

## File: shelltools.py

def initialize_database():
    ## Code to initialize the database
    pass

def drop_tables():
    ## Code to drop tables
    pass

대화형 쉘에서 shelltools 모듈에서 원하는 메서드를 가져오십시오.

## File: shell.py
## Execution: python shell.py

from shelltools import initialize_database, drop_tables

## Import desired methods from shelltools module
from shelltools import *

## Use imported methods
initialize_database()
drop_tables()

요약

"쉘 사용하기" 튜토리얼은 Flask 에서 대화형 쉘을 사용하는 방법에 대한 단계별 지침을 제공합니다. 요청 컨텍스트를 생성하고, before/after request 함수를 실행하며, 별도의 모듈에서 헬퍼 메서드를 가져와 쉘 경험을 향상시키는 방법을 설명합니다.