Self Code Review/(sparta) WEB plus - 나만의 단어장
[나만의 단어장] 10. 목록페이지 - 사전에 없는 단어일 때
밍굥잉
2022. 5. 4. 14:33
✅ API에서 단어 뜻 찾아서 detail.html로 결과 보내는 서버 함수 內
r = requests.get(f"<https://owlbot.info/api/v4/dictionary/{keyword}>", headers={"Authorization": "Token [내토큰]"})
result = r.json()
print(result)
- detail.html에 보내지는 result라는 값을 사전 API에서 찾을 수 없어서
- ‘정의를 찾을 수 없다’는 메시지 즉, 다른 형태의 데이터를 주기 때문에 처리하지 못해서 에러 발생 !
- 이 때 에러를 보여주지 않고 단어 목록 페이지로 리다이렉팅 해야함
✅ 값을 잘 받아왔을 때의 상태코드가 200이므로 200이 아닐 때 메인페이지로 리다이렉팅 시키고 ‘단어를 찾을 수 없다’는 메시지 남겨주기
if r.status_code != 200:
return redirect(url_for("main", msg="Word not found in dictionary; Try another word"))
✅ ⬆️ detail 함수 완성
@app.route('/detail/')
def detail(keyword):
status_receive = request.args.get("status_give", "old")
r = requests.get(f"<https://owlbot.info/api/v4/dictionary/{keyword}>",
headers={"Authorization": "Token fa94f4b391cbaf92d16b54ca28dc8ea4b09dc478"})
if r.status_code != 200:
return redirect(url_for("main", msg="Word not found in dictionary; Try another word"))
result = r.json()
print(result)
return render_template("detail.html", word=keyword, result=result, status=status_receive)
✅ ⬆️ main 함수 완성
- main 사전에 없는 단어일 경우, 메인 페이지를 띄워야하기 때문에 메인 페이지에서 ‘단어를 찾을 수 없다’는 메시지를 보여줘야함.
@app.route('/')
def main():
msg = request.args.get("msg") //msg를 파라미터로 받음
# DB에서 저장된 단어 찾아서 HTML에 나타내기
words = list(db.words.find({}, {"_id": False}))
return render_template("index.html", words=words, msg=msg)
✅ msg가 None이 아니면 alert을 띄움
{% if msg %}
alert("{{ msg }}")
{% endif %}