Flask web framework

김제현·2024년 1월 5일
post-thumbnail

pip3 install flask

1. Routing

from flask import Flask

app = Flask(__name__)

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

@app.route('/create/')
def create():
    return 'Create'

@app.route('/read/1/')
def read():
    return 'Read 1'

# debug=True로 변경시 코드 수정시 자동 재실행
app.run(port=5555, debug=True)

2. Variable Rules

from flask import Flask

app = Flask(__name__)

@app.route('/read/<id>')
def read(id):
    print(id)
    return f"Reading data for ID: {id}"

if __name__ == '__main__':
    app.run(debug=True)
  • 위 코드는 간단한 Flask 앱을 정의한다. /read/와 같은 경로를 정의하고, 해당 경로로 들어온 요청에서 부분을 동적으로 추출하여 read 함수의 id 매개변수에 전달하며. 그리고 해당 id 값을 출력하고 응답으로 "Reading data for ID: {id}"를 반환한다.

  • 예를 들어, /read/123에 접속하면 "Reading data for ID: 123"이 출력되고, /read/456에 접속하면 "Reading data for ID: 456"이 출력된다. 이렇게 동적으로 변하는 URL을 다룰 때 Variable Rules는 유용하게 사용된다.

3. Create

# form 태그는 서버에게 데이터를 보내기 위한 수단
# GET 방식은 URL을 통해 데이터를 전송 - 특정 페이지를 읽어올 때 GET 방식 사용
# POST 방식으로 데이터를 전송시 Payload에 저장
@app.route('/create/', methods=['GET', 'POST'])
def create():
    if request.method == 'GET':
        content = '''
            <form action="/create/" method="POST">
                <p><input type="text" name="title" placeholder="title"></p>
                <p><textarea name="body" placeholder="body"></textarea></p>
                <p><input type="submit" value="create"></p>
            </form>
        '''
        return template(getContents(), content)
    elif request.method == 'POST':
        global nextId
        title = request.form['title']
        body = request.form['body']
        newTopic = {'id': nextId, 'title': title, 'body': body}
        topics.append(newTopic)
        url = '/read/'+str(nextId)+'/'
        nextId = nextId + 1
        return redirect(url)

참고
https://opentutorials.org/course/4904

0개의 댓글