๐Ÿ‘ฉ‍๐Ÿ’ป Learn programming

[๋‚˜๋งŒ์˜ ๋‹จ์–ด์žฅ] 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 %}

 

๋ฐ˜์‘ํ˜•