Self Code Review/(sparta) WEB plus - 나만의 단어장

[나만의 단어장] 6. 상세페이지 - jinja2로 단어 뜻 가져오기

밍굥잉 2022. 5. 4. 14:10

Jinja2 템플릿 언어

  • Flask 프레임워크에서 사용하는 템플릿 언어.
  • ‘템플릿’이 되는 Html 문서에 데이터가 들어갈 곳을 표시해놓는 역할을 합니다.
  • 파이참 > setting > Template Languages > Jinja2 설정

 

✅ Owlbot API 요청 Flask

r = requests.get(f"<https://owlbot.info/api/v4/dictionary/{keyword}>", headers={"Authorization": "Token [내토큰]"})
result = r.json()
print(result)

 

 jinja2를 이용해서 detail.html에 값을 채워 넣어주기 위해 detil.html과 연결되어 있는 detail 함수 안에
사전 API에 요청을 보내고 값을 받아오는 부분이 필요.

@app.route('/detail/')
def detail(keyword):
    # API에서 단어 뜻 찾아서 결과 보내기
    r = requests.get(f"<https://owlbot.info/api/v4/dictionary/{keyword}>", headers={"Authorization": "Token [내 토큰]"})
    # 1. url의 일부를 받아서 keyword라는 변수로 저장해서 요청을 보내는 url 뒤에다가 넣어줌
    # 2. header 정보 안에 내 토큰을 넣어서 허가를 받음
    result = r.json()
    # 받아온 결과는 json 형태이고, result라는 변수에 넣음
    print(result)
    return render_template("detail.html", word=keyword, result=result)
    # reult를 detail.html에 result라는 이름으로 보내주세요
<div class="container">
    <div class="d-flex justify-content-between align-items-end">
        <div>
            <h1 id="word" style="display: inline;">{{ word }}</h1> <!-- 단어 -->
            <h5 id="pronunciation" style="display: inline;">/{{ result.pronunciation }}/</h5>  <!-- 발음 -->
        </div>
        <button id="btn-save" class="btn btn-outline-sparta btn-lg">save</button>
        <button id="btn-delete" class="btn btn-sparta btn-lg" style="display:none;">delete</button>
    </div>
    <hr>
    <div id="definitions">
        {% for definition in result.definitions %} <!--result 안에 definitions 라고 들어있는 만큼 반복 -->
            <div style="padding:10px">
                <i>{{ definition.type }}</i>  <!-- 품사 -->
                <br>{{ definition.definition }}<br>  <!-- 뜻 -->
                <span class="example">{{ definition.example }}</span>  <!-- 예문 -->
            </div>
        {% endfor %} <!-- 반복문은 여기까지 -->
    </div>
</div>
{{ result[”word”] }} = {{ result.word }}

발음이 있는 경우에만 보여주도록 예외처리

{% if result.pronunciation %} <!-- {% if result.pronunciation != None %}와 같음. [result의 pronunciation이 None이 아니다 = 값이 있다 = true] -->
    <h5 id="pronunciation" style="display: inline;">/{{ result.pronunciation }}/</h5>
{% endif %}

 

 예문이 있는 경우에만 보여주도록 예외처리

{% if definition.example %}
    <span class="example">{{ definition.example }}</span>
{% endif %}

 

 예문에 HTML 태그 쓰는 것을 허용

<span class="example">{{ definition.example|safe }}</span>
  • definition.example이 html일 수도 있는데 이상한 것을 시도하는 것이 아니라 그냥 꾸며주는 거라 안전하니까
    그대로 표시하세요.

 

 정의와 예문에서 깨진 글자를 없앰

<br>{{ definition.definition.encode('ascii', 'ignore').decode('utf-8') }}<br> <!--뜻 부분의 깨진 글자 없앰-->
{% if definition.example %}
    <span class="example">{{ definition.example.encode('ascii', 'ignore').decode('utf-8')|safe }}</span> <!--예문 부분의 깨진 글자 없앰-->
{% endif %}

 

 definition의 example의 문자열을 ascii 코드의 형태로 인코딩을 해줄건데,
ascii 코드로 표현할 수 없는 것들은 무시하고 바뀌는 것들은 다시 문자열로 바꿔주세요.

<div class="container">
    <div class="d-flex justify-content-between align-items-end">
        <div>
            <h1 id="word" style="display: inline;">{{ word }}</h1> 
            {% if result.pronunciation %}
                <h5 id="pronunciation" style="display: inline;">/{{ result.pronunciation }}/</h5>
            {% endif %}
        </div>
        <button id="btn-save" class="btn btn-outline-sparta btn-lg">save</button>
        <button id="btn-delete" class="btn btn-sparta btn-lg" style="display:none;">delete</button>
    </div>
    <hr>
    <div id="definitions">
        {% for definition in result.definitions %} 
		        <div style="padding:10px">
		            <i>{{ definition.type }}</i>  
		            <br>{{ definition.definition.encode('ascii', 'ignore').decode('utf-8') }}<br> 
                    {% if definition.example %}
                        <span class="example">{{ definition.example.encode('ascii', 'ignore').decode('utf-8')|safe }}</span> 
                    {% endif %}
		        </div>
        {% endfor %} 
    </div>
</div>