크롤링을 구현하다 클라이언트에서 서버로 요청하는 부분을 더 자세히 알고싶어서

파이썬의 Flask를 사용해서 하나 구현해보기로 했다.

 

웹 페이지에서 버튼을 클릭하면 새로운 페이지로 넘어가는 기능을 할 것이다.


소스코드

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from flask import Flask, render_template, redirect, request, url_for
 
app = Flask(__name__)
 
@app.route('/', methods=['POST'])
def main():
    if request.method == 'POST':
        return redirect(url_for('test'))
    return render_template('main.html')
 
@app.route('/test')
def test():
    return 'NEW PAGE'
 
if __name__ == '__main__':
    app.run()
cs

 

POST 방식을 사용해서 기본 웹 페이지로 어떤 값이 전달되면, url for 함수를 사용해서 test 페이지로 redirect 시킨다.

다음 render_template 함수를 사용해서 html 파일들을 렌더링한다.

test 페이지에서는 NEW PAGE를 출력한다.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>
        Flask #2
    </title>
</head>
<body>
    <form action=" " method="POST">
        <button type="submit", value="Button"> 페이지 넘기기 </button>
    </form>
</body>
</html>
cs

 

HTML에서는 버튼을 하나 만들어 POST형식으로 요청을 서버에 보낸다.

 

결과

 

+ Recent posts