flask

flask 기본적인 문법과 사용법2(static, render_template에서 변수 사용, 쿠키)

코딩하는logcat 2023. 1. 12. 20:41

1.static 파일

 

 

flask에서 css나 js같은 파일들을 참조할 수 있다.

 

render_template를 사용할때 

 

templates 폴더 안에 저장한 것 처럼

 

css, js같은 정적 파일들은 static 폴더 안에 저장해야 한다

 

 

voca.html

 

<link rel = "stylesheet" href = "{{ url_for('static', filename = 'css/voca.css') }}">

 

위처럼 정적파일을 참조할때는 {{ url_for('static', filename = '파일명') }} 으로 참조한다.

 

css가 성공적으로 들어갔다.

 

2.render_template 에서 변수 사용하기

render_template("html파일", 변수1, 변수2)    처럼 작성하고

{{변수1}}로 render_template 당한 html 파일 안에서 flask의 변수를 참조할 수도 있다.

 

 

3.쿠키

 

쿠키란 서버에서 해당 클라이언트에 저장해 놓는 변수들이다.

 

f12 - Application - cookies 에서 쿠키를 확인할 수 있다.

 

"1주일간 보지 않기" 등의 기능이 쿠키를 활용한다

 

flask에서 쿠키를 사용하려면 

 

make_response 메소드를 사용하여 쿠키를 만들 고

 

request 메소드를 사용하여 쿠키를 읽는다.

 

cookie_test.py

 

from flask import Flask
from flask import render_template
from flask import request
from flask import make_response


app = Flask(__name__)

@app.route('/', methods = ['POST', 'GET'])
def index_page():
c_id = request.cookies.get('id')                //  "id" 라는 이름으로 저장된 쿠키 저장.     
c_pas = request.cookies.get('pass')        //  "pass" 라는 이름으로 저장된 쿠키 저장.   
return render_template('voca_cookie.html', id = c_id, pas = c_pas)    // html에 저장한 쿠키값을 뿌린다.

@app.route('/login', methods = ['POST'])
def login():

id = request.form['id']    // post 로 전송된 form 값을 저장
pas = request.form['pass']  // post 로 전송된 form 값을 저장
resp = make_response("id : "+id+" pass : "+pas)     // make_response 객체 생성, 안에 글자들은 나중에 출력 하려는 내용
resp.set_cookie('id', id)    // 이름이 'id'이고 value가 id인 쿠키 생성 
resp.set_cookie('pass', pas)  // 이름이 'pass'이고 value가 pas인 쿠키 생성 
return resp            // return을 시켜줘야지 쿠키가 생성된다.

if __name__ == '__main__':
    app.run()

 

 

 

voca_cookie.html

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HTML for python flask</title>
<link rel = "stylesheet" href = "{{ url_for('static', filename = 'css/voca.css') }}">
</head>

<body>
<form action="/login" method="post">
​ <p>id : <input type="text" id="id" name="id" value = '{{id}}'></p>
<p>pass : <input type="text" id="pass" name="pass" value = '{{pas}}'></p>
<p>.<input type="submit" value="제출" onclick="alert('제출 완료!')" /></p>
</form>
</body>
</html>

 

 

로그인을 하면 로그인 정보를 쿠키에 저장해서 다음에 다시 로그인 할때 최근 로그인 정보가 띄워지는 예제 이다.

F12를 눌러 쿠키값이 저장된 것을 확인할 수 있디
쿠키 저장값을 불러와서 아이디 비번을 미리 띄워둔다.