Files
python-examples/doc/39_01_controller.md
2025-01-23 11:02:27 +09:00

5.9 KiB

Flask에서 라우팅하는 방법

Flask에서 라우팅은 특정 URL에 어떤 함수를 연결하여 요청을 처리하는 것을 의미합니다. 즉, 사용자가 어떤 URL로 접속하면 그에 해당하는 함수가 실행되어 동적인 웹 페이지를 생성하게 됩니다.

@app.route 데코레이터

Flask에서 라우팅은 @app.route 데코레이터를 사용하여 간단하게 정의할 수 있습니다. 이 데코레이터는 함수 위에 붙여서 해당 함수가 처리할 URL을 지정합니다.

from flask import Flask

app = Flask(__name__)

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

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

위 코드에서 @app.route('/')는 루트 경로('/')에 대한 요청이 들어오면 index() 함수를 실행하도록 설정합니다.

다양한 라우팅 방법

정적 라우팅

특정 URL에 하나의 함수를 연결하는 방식입니다.

@app.route('/about')

동적 라우팅

URL에 변수를 포함하여 다양한 요청을 처리할 수 있습니다.

@app.route('/user/<username>')
from flask import Flask

app = Flask(__name__)

@app.route('/user/<username>')
def show_user_profile(username):
    # 사용자 정보를 조회하여 반환
    return f'User {username}'

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

위 코드에서 /user/ 라우트는 username이라는 변수를 포함하고 있습니다. 이를 통해 /user/john과 같은 URL에 접속하면 username 변수에 'john'이 할당되고, show_user_profile 함수에서 이 값을 사용하여 사용자 정보를 조회할 수 있습니다.

HTTP 메서드

methods 인자를 사용하여 GET, POST, PUT 등 다양한 HTTP 메서드를 지원할 수 있습니다.

@app.route('/login', methods=['GET', 'POST'])

다양한 변수 형식

Flask는 다양한 URL 변환기를 제공하여 URL에서 값을 추출하고 검증하는 기능을 제공합니다.

  • int:변수명: 정수 값
  • float:변수명: 부동소수점 값
  • path:변수명: 슬래시(/)를 포함한 경로
  • uuid:변수명: UUID 값
@app.route('/post/<int:post_id>')
def show_post(post_id):
    # post_id는 정수형으로 변환되어 사용됩니다.
    return f'Post {post_id}'
  • 변환기 사용자 정의: Converter를 상속하여 사용자 정의 변환기를 만들 수 있습니다.
  • 기본값 설정: default 인자를 사용하여 변수에 기본값을 설정할 수 있습니다.
  • 필수 파라미터: required 인자를 사용하여 필수 파라미터를 지정할 수 있습니다.

URL 파라미터 값 가져오기

URL에 ?를 붙여 쿼리 파라미터를 전달할 수 있습니다. 예를 들어, /search?q=python과 같이 사용합니다. 이러한 쿼리 파라미터는 request.args를 통해 접근할 수 있습니다.

from flask import Flask, request

app = Flask(__name__)

@app.route('/search')
def search():
    query = request.args.get('q')
    return f'You searched for: {query}'

응답 코드 지정

from flask import Flask, make_response

app = Flask(__name__)

@app.route('/')
def index():
    # 404 Not Found 응답
    return make_response('Not Found', 404)
  • make_response() 함수: 직접 응답 객체를 생성하여 응답 코드를 지정할 수 있습니다. 첫 번째 인자는 응답 내용, 두 번째 인자는 상태 코드입니다.

Flask의 내장 함수 활용

  • abort(code): 특정 상태 코드와 함께 예외를 발생시켜 응답을 중단합니다.
  • redirect(location, code=302): 다른 URL로 리다이렉트합니다.
from flask import abort, redirect, url_for

@app.route('/admin')
def admin_page():
    if not is_admin:
        abort(403)  # 403 Forbidden
    return 'Welcome, admin!'

Jinja2 템플릿과 함께 사용

from flask import render_template

@app.route('/error')
def error_page():
    return render_template('error.html'), 404

Response 객체

더 복잡한 응답을 생성하려면 Response 객체를 직접 사용할 수 있습니다.

from flask import Response

@app.route('/custom_response')
def custom_response():
    response = Response('Custom response', status=201, mimetype='text/plain')
    response.headers['X-Custom-Header'] = 'custom value'
    return response

파일 업로드

from flask import Flask, request, render_template

app = Flask(__name__)
UPLOAD_FOLDER = 'static/uploads'  # 업로드 파일 저장 경로

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file:
            filename = secure_filename(file.filename)
            file.save(os.path.join(UPLOAD_FOLDER, filename))
            return 'Uploaded file successfully'
    return render_template('upload.html')

if __name__ == '__main__':
    app.run(debug=True)
  • UPLOAD_FOLDER: 업로드된 파일을 저장할 폴더 경로를 설정합니다.
  • request.files: enctype="multipart/form-data"로 설정된 폼에서 전송된 파일을 담고 있는 딕셔너리입니다.
  • secure_filename: Flask에서 제공하는 함수로, 업로드 파일 이름을 안전하게 처리하여 디렉토리 트래버설 공격을 방지합니다.
  • file.save(): 파일을 지정된 경로에 저장합니다.

추가적인 기능

  • URL for: url_for 함수를 사용하여 URL을 생성할 수 있습니다.
  • HTTP 메서드: GET, POST, PUT, DELETE 등 다양한 HTTP 메서드를 지원합니다.
  • HTTP 상태 코드: return 문에서 상태 코드를 지정하여 응답할 수 있습니다.
  • 템플릿 엔진: Jinja2를 사용하여 동적인 HTML 페이지를 생성할 수 있습니다.