python-jinja2

백종석·2022년 5월 10일
0

python-jinja2

목록 보기
1/3
post-thumbnail

실시간 서울시 미세먼지 api를 이용해 데이터를 받아서 화면에 출력하는 기존 ajax 코드는

   $(document).ready(function () {
       get_list()
   })

   function get_list() {
       $('#gu-list').empty()
       $.ajax({
           type: "GET",
           url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
           data: {},
           success: function (response) {
               let rows = response["RealtimeCityAir"]["row"];

               for (let i = 0; i < rows.length; i++) {
                   let gu_name = rows[i]["MSRSTE_NM"]
                   let gu_mise = rows[i]["IDEX_MVL"]

                   if (gu_mise > 60) {
                       let temp_html = `<li>${gu_name} : ${gu_mise}</li>`
                       $('#gu-list').append(temp_html)
                   }
               }
           }
       })
   }

이런식으로 temp_html을 설정하고 append(temp_html)을 이용해 붙여 주었다면,

파이썬 패키지 jinja2를 이용하였을 때는 html body 본문에

<h3>받은 단어는 {{ word }}</h3>
<ul id="gu-list">
    {% for row in rows %}
        {% set gu_name=row["MSRSTE_NM"] %}
        {% set gu_mise=row["IDEX_MVL"] %}
        {% if gu_mise>=60 %}
            <li>{{ gu_name }} : {{ gu_mise|int }}</li>
        {% endif %}
    {% endfor %}
</ul>

형식으로 {% %}를 이용하여 나타낼 수 있고,

서버부분 app.py 파일의 페이지를 가져오는 코드에

    r = requests.get('http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99')
    response = r.json()
    rows = response['RealtimeCityAir']['row']

코드를 추가하여 작성하는 식으로 사용할 수 있다.

app.py의 코드를 추가한 api 부분의 전체 코드는

@app.route('/detail/<keyword>')
def detail (keyword):
    r = requests.get('http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99')
    response = r.json()
    rows = response['RealtimeCityAir']['row']
    return render_template("detail.html", rows=rows, word=keyword)

이런 식으로 작성된다.

profile
항해중인 우당탕탕 코린이

0개의 댓글