웹개발 플러스 2주차

귀찮Lee·2022년 3월 28일
0

□ 웹개발 플러스 (1주차)

22.03.28(월)

◎ 플라스크로 멀티페이지 사이트 만들기

from flask import Flask, render_template
import requests

@app.route('/')
def main():
    return render_template("index.html")
    
@app.route('/detail')
def detail():
    return render_template("detail.html")

app = Flask(__name__)
  • 일반 주소를 치면 'index.html'이, 뒤에 /detail을 붙이면 'detail.html'이 랜더링됨.
  • Client에서 window.location.href 등을 이용하여 페이지 이동 가능

◎ Jinja2

  • Pycharm에서 Setting > Template Languages 에서 Jinja2로 설정시 용이하게 코딩할 수 있음.

  • html body 부분에서도 반복문, 조건문을 사용할 수 있음.

  • app.py

from flask import Flask, render_template, request
import requests

app = Flask(__name__)

@app.route('/')
def detail(keyword):
    rows =[
      {
      "MSRDT": "202203282100",
      "MSRRGN_NM": "도심권",
      "MSRSTE_NM": "중구",
      "PM10": 35.0,
      "PM25": 15.0,
      "O3": 0.033,
      "NO2": 0.028,
      "CO": 0.4,
      "SO2": 0.007,
      "IDEX_NM": "보통",
      "IDEX_MVL": 53.0,
      "ARPLT_MAIN": "PM10"
      },
      {
      "MSRDT": "202203282100",
      "MSRRGN_NM": "도심권",
      "MSRSTE_NM": "종로구",
      "PM10": 46.0,
      "PM25": 20.0,
      "O3": 0.032,
      "NO2": 0.027,
      "CO": 0.4,
      "SO2": 0.006,
      "IDEX_NM": "보통",
      "IDEX_MVL": 59.0,
      "ARPLT_MAIN": "PM10"
      }]
    return render_template("detail.html", rows=rows)
  • detail.html // for문 if문을 python 언어와 유사하게 사용가능
<body>
    <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>{{ rows[0]['MSRSTE_NM'] }} : {{ gu_mise|int }}</li>
            {% endif %}
        {% endfor %}
    </ul>
</body>
// 평소에 사용하지 않는 원치 않는 문자를 거를때 사용.
// ascii 인코딩 / 안되는 문자 무시 / 다시 디코딩
{{ definition.example.encode('ascii','ignore').decode('utf-8')|safe }}

//json 형태로 전환 / 기본 : html형식
var words = {{ words|tojson }}; 

Owlbot API

  • app.py
from flask import Flask, render_template, request, jsonify, redirect, url_for
import requests

@app.route('/detail/<keyword>')
def detail(keyword):
    status_receive = request.args.get('status_give')
    # API에서 단어 뜻 찾아서 결과 보내기
    r = requests.get(f"https://owlbot.info/api/v4/dictionary/{keyword}", headers={"Authorization": "Token 토큰값"})
    if r.status_code != 200:
        return redirect("/", msg="단어가 이상해요 ㅠㅠ")
    result = r.json()
    return render_template("detail.html", word=keyword, result=result, status=status_receive)
  • print(result)
{'definitions': 
 [{'type': 'pronoun',
   'definition': 'used to refer to a man, boy, or male animal previously mentioned or easily identified.',
   'example': 'everyone liked my fatherâ\x80\x94he was the perfect gentleman',
   'image_url': None,
   'emoji': None}],
'word': 'he',
'pronunciation': None}

◎ url을 이용하여 데이터 받기 / GET 요청

# url : /detail?word_give=banana

@app.route('/detail/<keyword>')
def detail(keyword):
    word_receive = request.args.get("word_give")
    print(word_receive)  # banana
    return render_template("detail.html", word=word_receive)
# url : /detail/apple

@app.route('/detail/<keyword>')
def detail(keyword):
	print(keyword) # apple
    return render_template("detail.html")

◎ CSS 파일 분리

<!-- project02/templates/index.html에서 -->
<!-- project02/static/mystyle.css 를 가져옴 -->

<!-- import CSS -->
<link href='{{ url_for("static", filename="mystyle.css") }}' rel="stylesheet">
profile
배운 것은 기록하자! / 오류 지적은 언제나 환영!

0개의 댓글