kaki1013

5. 쓰기 기능 구현 (2) 본문

버그바운티 스터디/FLASK

5. 쓰기 기능 구현 (2)

kaki1013 2023. 7. 22. 00:28

# 예시 코드

from flask import Flask, request, redirect

app = Flask(__name__)

nextId = 4
topics = [
    {'id': 1, 'title': 'html', 'body': 'html is ...'},
    {'id': 2, 'title': 'css', 'body': 'css is ...'},
    {'id': 3, 'title': 'javascript', 'body': 'javascript is ...'}
]


def template(contents, content):
    return f'''<!doctype html>
    <html>
        <body>
            <h1><a href="/">WEB</a></h1>
            <ol>
                {contents}
            </ol>
            {content}
            <ul>
                <li><a href="/create/">create</a></li>
            </ul>
        </body>
    </html>
    '''


def getContents():
    liTags = ''
    for topic in topics:
        liTags = liTags + f'<li><a href="/read/{topic["id"]}/">{topic["title"]}</a></li>'
    return liTags


@app.route('/')
def index():
    return template(getContents(), '<h2>Welcome</h2>Hello, WEB')


@app.route('/read/<int:id>/')
def read(id):
    title = ''
    body = ''
    for topic in topics:
        if id == topic['id']:
            title = topic['title']
            body = topic['body']
            break
    return template(getContents(), f'<h2>{title}</h2>{body}')


@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)

app.run(debug=True)

 

# 요약

- 브라우저의 요청 정보를 확인하기 위해서는 flask.request 모듈을 이용합니다.

- request.method는 브라우저가 전송한 method를 확인할 수 있습니다.

- request.form['NAME'] 는 브라우저가 전송한 POST 데이터를 확인할 수 있습니다.

 

#  추가 정보

1. HTTP Methods

- 기본적으로 GET 요청에만 응답함 → route 데코레이터의 methods 인자를 통해 다른 방식의 요청에도 대응이 가능

- @app.get('/login') 와 @app.get('/login') 같은 형태로도 작성이 가능

 

출처 : Flask Documentation (https://flask.palletsprojects.com/en/2.3.x/quickstart/#http-methods)

 

Quickstart — Flask Documentation (2.3.x)

Quickstart Eager to get started? This page gives a good introduction to Flask. Follow Installation to set up a project and install Flask first. A Minimal Application A minimal Flask application looks something like this: from flask import Flask app = Flask

flask.palletsprojects.com

2. The Request Object

- request.method : 현재 요청 방식을 알려줌

- request.form['username'] : POST나 PUT 요청과 함께 전달된, form data에 접근 가능

- request.args.get('key', '') : URL (?key=value)의 파라미터에 접근 가능

 

출처 : Flask Documentation (https://flask.palletsprojects.com/en/2.3.x/quickstart/#the-request-object)

 

Quickstart — Flask Documentation (2.3.x)

Quickstart Eager to get started? This page gives a good introduction to Flask. Follow Installation to set up a project and install Flask first. A Minimal Application A minimal Flask application looks something like this: from flask import Flask app = Flask

flask.palletsprojects.com

 

3. Redirects and Errors

redirect(url) : url 의 주소로 이동

출처 : Flask Documentation (https://flask.palletsprojects.com/en/2.3.x/quickstart/#redirects-and-errors)

 

Quickstart — Flask Documentation (2.3.x)

Quickstart Eager to get started? This page gives a good introduction to Flask. Follow Installation to set up a project and install Flask first. A Minimal Application A minimal Flask application looks something like this: from flask import Flask app = Flask

flask.palletsprojects.com

 

'버그바운티 스터디 > FLASK' 카테고리의 다른 글

7. 삭제 기능 구현  (0) 2023.07.26
6. 수정 기능 구현  (0) 2023.07.26
4. 쓰기 기능 구현 (1)  (0) 2023.07.21
3. 읽기 기능 구현  (0) 2023.07.21
2. 홈페이지 구현  (0) 2023.07.21