main, detail, save_word, delete_word
# index - find_word
# detail - get_definition, save_word, delete_word
# OWlbot 요청 API flask
r = requests.get(f"https://owlbot.info/api/v4/dictionary/{keyword}",\
headers={"Authorization": "Token [내토큰]"})
result = r.json()
print(result)
# 결과 jinja2로 표시
<div class="container">
<div class="d-flex justify-content-between align-items-end">
<div>
<h1 id="word" style="display: inline;">{{ result.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 %}
<div style="padding:10px">
<i>{{ definition.type }}</i>
<br>{{ definition.definition }}<br>
<span class="example">{{ definition.example }}</span>
</div>
{% endfor %}
</div>
</div>
status_receive = request.args.get['status_give','new']
return render_template("detail.html", word=keyword, result=result,\
status=status_receive)
# app.py 저장
@app.route('/api/save_word', methods=['POST'])
def save_word():
# 단어 저장하기
word_receive = request.form['word_give']
definition_receive = request.form['definition_give']
doc = {
'word': word_receive,
'definition': definition_receive,
}
db.words.insert_one(doc)
return jsonify({'result': 'success', 'msg': f'단어 {word_receive} 저장'})
# detail.html 저장
function save_word() {
$.ajax({
type: "POST",
url: `/api/save_word`,
data: {
word_give: "{{ word }}",
definition_give: "{{ result.definitions[0].definition }}"
},
success: function (response) {
alert(response["msg"])
window.location.href = "/detail/{{ word }}?status_give=old"
}
});
}
# app.py 삭제
@app.route('/api/delete_word', methods=['POST'])
def delete_word():
# 단어 삭제하기
word_receive = request.form['word_give']
db.words.delete_one({"word":word_receive})
return jsonify({'result': 'success', 'msg': f'word "{word_receive}" deleted'})
# detail.html 삭제
function delete_word() {
$.ajax({
type: "POST",
url: `/api/delete_word`,
data: {
word_give: '{{ word }}',
},
success: function (response) {
alert(response["msg"])
window.location.href = "/"
}
});
}
# app.py
@app.route('/')
def main():
# DB에서 저장된 단어 찾기
words = list(db.words.find({}, {"_id": False}))
return render_template("index.html", words=words)
# html
<tbody id="tbody-box">
{% for word in words %}
<tr id="word-{{ word }}">
<td><a href="/detail{{ word.word }}?status_give=old">{{ word.word }}</td>
<td>{{ word.definition }}</td>
</tr>
{% endfor %}
</tbody>
# html
<script>
# 단어 리스트 만들어 놓기
let words = {{ words|tojson }}; # "같은 것들이 진짜 데이터로 인식하게끔
let word_list = [];
for (let i = 0; i < words.length; i++) {
word_list.push(words[i]["word"])
}
fucntion find_word() {
let word = $("#input-word").val().toLowerCase();
if (word == "") {
alert("please write something first :)")
return
}
if (word_list.includes(word)) {
// 리스트에 있으면 하이라이트
$(`#word-${word}`).addClass('highlight').siblings().removeClass('highlight');
$(`#word-${word}`).siblings().removeClass("highlight")
$(`#word-${word}`)[0].scrollIntoView();
} else {
window.locaion.href="/detail/${word}?status_give=new"
}
}
</script>
# 결과를 못받아와서 상태 코드가 200이 아닌경우
@app.route('/detail/<keyword>')
def detail(keyword):
status_receive = request.args.get('status_give')
r = requests.get(f"https://owlbot.info/api/v4/dictionary/{keyword}",\
headers={"Authorization": "Token 내토큰"})
if r.status_code != 200: # 상태코드가 200이 아닌경우, 메세지도 함께
return redirect(url_for("main", msg="잘못된 단어입니다."))
result = r.json()
print(result)
return render_template("detail.html", word=keyword, result=result, status=status_receive)
# main에서 메시지를 받아 템플릿에 보내주기
@app.route('/')
def main():
msg = request.args.get("msg")
words = list(db.words.find({}, {'_id': False}))
return render_template("index.html", words=words, msg=msg)
# msg가 있을 때 얼럿 띄우기, index.html에서
<script>
{% if msg %}
alert("{{ msg }}")
{% endif %}
</script>