상세 컨텐츠

본문 제목

03. Flask / D-03

IT/파이썬-Flask

by 후즈테크 2022. 7. 21. 17:33

본문

반응형

1. Variable Rule

from flask import Flask

app = Flask(__name__)
from markupsafe import escape

@app.route('/user/<username>')
def show_user_profile(username):
    # show the user profile for that user
    return f'User {escape(username)}'

@app.route('/post/<int:post_id>') # post_id 값을 정수형으로만 받는 옵션
def show_post(post_id):
    # show the post with the given id, the id is an integer
    return f'Post {post_id}'

@app.route('/path/<path:subpath>') # path : / 허용
def show_subpath(subpath):
    # show the subpath after /path/
    return f'Subpath {escape(subpath)}'

    
app.run(host='0.0.0.0', port = 80, debug=True)

 

변수를 여러가지 형태로 받을 수 있는데, post_id 와 같이 int(정수)만 받는 옵션을 적용하면 숫자 외 문자가 함께 포함되면 Error 가 발생한다.

 

적용되는 숫자는 양의 정수만 적용 가능하고, 문자와 함께 쓰고 싶다면 int 대신 string 을 적용하면된다.

변환 가능한 타입은 아래와 같다.

Converter types:

string (default) accepts any text without a slash
int accepts positive integers
float accepts positive floating point values
path like but also accepts slashesstring
uuid accepts UUID strings
반응형

 

 

path는 '/'를 포함할 수 있지만 string은 포함할 수 없다.

 

2. URL Building / redirect, url_for

from flask import Flask

app = Flask(__name__)

from flask import url_for

@app.route('/')
def index():
    return 'index'

@app.route('/login')
def login():
    return 'login'

@app.route('/user/<username>')
def profile(username):
    return f'{username}\'s profile'

with app.test_request_context():
    print(url_for('index'))
    print(url_for('login'))
    print(url_for('login', next='/'))
    print(url_for('profile', username='John Doe'))


app.run(port = 80, debug=True)

url_for ... 처음에 어떤걸 의미하는지 몰라 많이 헤매던 내용이다..... 실제 함수명을 기준으로 실행되는 route를 찾는 함수이다.

빨간색 선을 따라가보면, url_for 안에 포함된 함수명을 찾고, 해당 함수의 route를 적용한다.

해당 항목을 통해 다른 URL로 이동이 가능하다.

 

해당 기능을 쓰는 상황을 테스트 하려면 redicrect 에 대한 기능을 먼저 확인하여야 하는데,

redirect는 입력한 URL로 이동할 수 있다.

from flask import Flask, redirect

app = Flask(__name__)

from flask import url_for

@app.route('/')
def index():
    return 'index'

@app.route('/login')
def login():
    return 'login'

@app.route('/user/<username>')
def profile(username):
    return f'{username}\'s profile'

@app.route('/whosetech')
def whosetech():
    return redirect('https://whosetech.tistory.com/') #whosetech 가 route 조건으로 입력되면 특정 page로 이동


@app.route('/url_for_test')
def url_for_test():
    return redirect(url_for('whosetech'))

with app.test_request_context():
    print(url_for('index'))
    print(url_for('login'))
    print(url_for('login', next='/'))
    print(url_for('profile', username='John Doe'))


app.run(port = 80, debug=True)

 

- redicect를 이용하면, http://127.0.0.1/whosetech 를 입력하였을 때, 입력된 https://whosetech.tistory.com/  으로 이동하는 것을 확인할 수 있다.

 

 

 

하지만 다른 URL이 입력되어도 동일한 페이지를 연결하여 호출하는 방법이 있으니,

이 방법이 url_for 이다.

아래에서 보는 것과 같이 http://127.0.0.1/url_for_test 를 입력하면, url_for를 통해 입력된 whosetech 함수를 찾아가고,

해당 경로에서 반환된 tistory 사이트로 이동가능하다.

해당 기능을 통해 app.route의 경로가 변경되더라도 큰 수정 없이 사이트를 운용할 수 있다.

반응형

'IT > 파이썬-Flask' 카테고리의 다른 글

02. Flask / D-02  (0) 2022.07.20
01. Flask / D-01  (0) 2022.07.20
Flask 시작??  (0) 2022.07.20

관련글 더보기

댓글 영역