English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
쿠키는 클라이언트 컴퓨터에 텍스트 파일 형식으로 저장됩니다. 목적은 고객의 사용과 관련된 데이터를 기억하고 추적하여 더 나은 접근 경험과 웹 사이트 통계를 제공하는 것입니다.
Request 객체는 쿠키의 속성을 포함하고 있습니다. 이는 클라이언트가 전송한 모든 쿠키 변수 및 값의 딕셔너리 객체입니다. 이 외에도, 쿠키는 만료 시간, 경로 및 사이트 도메인을 저장합니다.
Flask에서 쿠키는 응답 객체에 설정됩니다. 뷰 함수의 반환 값에서 make_response() 함수를 사용하여 응답 객체를 가져옵니다. 그런 다음, 응답 객체의 set_cookie() 함수를 사용하여 쿠키를 저장합니다.
쿠키를 다시 읽기 쉽습니다. request.cookies 속성의 get() 메서드를 사용하여 쿠키를 읽을 수 있습니다.
다음 Flask 애플리케이션에서 URL =>에 접근할 때, / 이 경우 간단한 양식이 열립니다.
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : ko.oldtoolbag.com # Date : 2020-08-08 @app.route('/) def index(): return render_template('index.html')
이 HTML 페이지는 텍스트 입력을 포함하고 있으며, 전체 코드는 다음과 같습니다. -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : ko.oldtoolbag.com # Date : 2020-08-08 <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Flask 쿠키 예제</title> </head> <body> <form action = "/setcookie" method = "POST"> <p><h3>userID 입력</h3></p> <p><input type = 'text' name = 'name'/></p> <p><input type = 'submit' value = '로그인'/></p> </form> </body> </html>
URL에 제출된 양식 => /setcookie. 관련된 뷰 함수는 'userID'라는 쿠키 이름을 설정하고 다른 페이지에서 표시합니다.
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : ko.oldtoolbag.com # Date : 2020-08-08 @app.route('/setcookie', methods=['POST', 'GET']) def setcookie(): if request.method == 'POST': user = request.form['name'] resp = make_response(render_template('readcookie.html')) resp.set_cookie('userID', user) return resp
readcookie.html 포함한 다른 함수 getcookie()로의 스크립트 링크를 포함하고 있으며, 이 함수는 쿠키 값을 읽어서 브라우저에서 표시합니다.
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : ko.oldtoolbag.com # Date : 2020-08-08 @app.route('/getcookie) def getcookie(): name = request.cookies.get('userID') return '<h1>welcome ''+name+"</h1"
完整的应用程序代码如下 -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : ko.oldtoolbag.com # Date : 2020-08-08 from flask import Flask from flask import render_template from flask import request from flask import make_response app = Flask(__name__) @app.route('/) def index(): return render_template('index.html') @app.route('/setcookie', methods=['POST', 'GET']) def setcookie(): if request.method == 'POST': user = request.form['name'] resp = make_response(render_template('readcookie.html')) resp.set_cookie('userID', user) return resp @app.route('/getcookie) def getcookie(): name = request.cookies.get('userID') print(name) return '<h1> 환영합니다, '+name+"</h1" if __name__ == '__main__': app.run(debug=True)
이 애플리케이션을 실행하고 URL에 접근하십시오 => http://localhost:5000/쿠키 설정 결과는 다음과 같습니다 -
쿠키 재읽기 출력은 다음과 같습니다 -