728x90
반응형
Jinja (template engine)
Jinja는 Python용 웹 템플릿 엔진이다.
Jinja는 Flask의 기본 템플릿 엔진이며 Ansible, Trac, Salt에서도 사용된다.
텍스트 기반 템플릿 언어이므로 모든 마크업 소스 코드를 생성하는 데 사용할 수 있다.
즉 간단한 문법으로 html에서 {}
, {{}}
등의 규칙을 이용하여 python 프로그래밍이 가능한 템플릿이다.
데이터를 담은 변수를 return 값으로 html에 넘겨준 뒤 html에서 jinja 템플릿 규칙에 따라 화면에 표현이 가능하다.
Jinja 템플릿 html에서 주석은 {# 내용 #}
이다.
Jinja 특징
- (XSS 공격 방지를 위한) 자동 HTML escape
- 템플릿 상속
- Python 코드로 컴파일
- 쉬운 디버깅
Jinja 예시
변수 사용하기
Jinja template은 flask에서 제공하는 엔진이므로 html을 렌더링 할 때 변수를 전달하면 해당 html에서 전달된 변수를 사용할 수 있다.
- Python에서 Jinja2 template 변수 넘기기
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/hello/<user>') # <user> 생성
def hello_name(user): # <user> 변수값을 함수로 넘김
return render_template('variable.html', name1=user, name2='This is Jinja2 template') # 변수들을 html로 넘김
if __name__ == '__main__':
app.run(host="0.0.0.0", port="8080")
- HTML에서 Jinja2 template 변수 활용하기
<!DOCTYPE html>
<html>
<body>
<h1>Hello {{ name1 }}</h1>
<h2>{{ name2 }}</h2>
<h2>URL : http://127.0.0.1:8080/hello/{{ name1 }}</h2>
</body>
</html>
반복문 사용하기
Jinja에서 사용하는 반복문(for문)의 문법은 다음과 같다.
- Python에서 반복문에 사용할 list 변수 할당하기
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/hello_loop')
def hello_name():
value_list = ['list1', 'list2', 'list3'] # 리스트를 변수에 담아 html로 return
return render_template('loop.html', values=value_list)
if __name__ == '__main__':
app.run(host="0.0.0.0", port="8080")
- HTML에서 Jinja2 template으로 for문 활용하기
- loop.index를 통해 번호를 매길 수 있다.
<html>
<body>
<ol>
{% for value in values %}
<li>{{ value }}</li>
{% endfor %}
</ol>
<ul>
{% for i in range(values | length) %}
<li>{{ values[i] }} : {{ loop.index }}번째</li>
{% endfor %}
</ul>
</body>
</html>
사용 사례
매개변수화된 쿼리
ETL 작업을 하다보면 긴 쿼리문을 실행하는 경우가 많다.
이때 긴 쿼리문을 python script에 같이 작성하게 되면 코드가 길어지고, 디버깅이나 프로세싱 수정에 어려움이 많다.
이럴 경우에 jinja 템플릿을 이용하여 프로세싱 스크립트와 sql query 스크립트를 분리시켜 관리할 수 있다.
import jinja2
# Get a script path
script_dir = os.path.dirname(os.path.realpath(__file__))
temp_dir = os.path.realpath(os.path.join(script_dir, "temp"))
# Set timestamp
timestamp: str = datetime.datetime.now().strftime("%Y-%m-%d_%H%M%S")
# Execute data processing query by using jinja template
env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.join(script_dir, "query_templates")))
template = env.get_template(f"data_processing_query.sql")
sql = template.render(target_date=target_date, target_datetime=target_datetime)
# Logging executed queries for debugging
sql_filename = f"data_processing_query.{timestamp}.sql"
sql_filepath = f"{temp_dir}/{sql_filename}"
with open(sql_filepath, "w", encoding="utf-8") as f:
f.write(sql)
Reference
반응형
'Programming Language > [Python]' 카테고리의 다른 글
[Python] pandas dataframe 행/열 count (0) | 2023.07.12 |
---|---|
[Python] pymysql connection option (0) | 2023.06.21 |
[Python] datetime format (0) | 2023.04.18 |
[Python] sqlalchemy - text (0) | 2023.04.18 |
[Python] Redis connection (0) | 2023.04.15 |