2022.3.30 개발일지 javascript

정성우·2022년 3월 30일
0

1.학습한 내용

flask 사용하기

from flask import Flask

app = Flask(__name__)

topics = [
  {"id":1, "title":"html", "body":"html is ...."},
  {"id":2, "title":"css", "body":"css is ...."},
  {"id":3, "title":"js", "body":"js is ...."}
]
# topics란 이름을 가진 배열 만들기 배열의 각각의 값은 id, title, body값을 가진다.

def template(content):
  liTags = ''
  for topic in topics:
    liTags = liTags + f'<li><a href="/read/{topic["id"]}/">{topic["title"]}</a></li>'
  return f'''
  <html>
    <body>
      <h1><a href="/">WEB</a></h1>
      <ol>
        {liTags}
      </ol>
      {content}
      <ul>
        <li><a href="/create/">create</a></li>
      </ul>
    </body>
  </html>
  '''
# template란 함수 정의하기 parameter는 content 빈litag를 생성한후 반복문을 통해 topic의 title의 글씨에 topic의 id값에 해당하는 하이퍼링크를 누적입력
# "/"는 더 세부적인 주소없이 들어올때(홈페이지)를 말한다
# liTags ,content 출력 /create/주소로 링크된 create값 출력

@app.route("/")
def index():
  return template('<h2>Welcome</h2>Hello, WEB!')
# "/" 홈페이지로 접속시에 index라는 함수를 실행 template(content)를 return 
# 위의 template(content)함수의 content자리에 '<h2>Welcome</h2>Hello, WEB!'를 넣어서 실행   
  
@app.route("/read/<int:id>/")
def read(id):
  title = ''
  body = ''  
  for topic in topics :
    if topic['id'] == id:
      title = topic['title']
      body = topic['body']
      break;
  return template(f'<h2>{title}</h2>{body}')
# ex) "/read/1/" 로 접속시에 read(1)이라는 함수 실행
# title과 body에 공백입력
# 반복문을 통해 topic의 id값과 입력한1이 같으면 topic의 title과 body를 입력
# 위의 template(content)함수의 content자리에 f'<h2>{title}</h2>{body}'를 넣어서 실행

@app.route('/create/')
def create():
  content = '''
    <form action="/content/">
      <p><input type="text" name="title" placeholder="title"></p>
      <p><textarea name="body" placeholder="body"></textarea></p>
      <p><input type="submit" value="create"></p>
    </form>
  '''
  return template(content)
# "/create/"로 접속시에 create()함수 실행
# content에 text를 적을수있는 박스를 생성
# submit 타입의 버튼을 생성
# submit 시에 /content/주소로 이동

@app.route("/content/")
def content():
    return 'hi'

app.run()

실행결과

학습한 내용 중 어려웠던 점 또는 해결못한 것들

f'<h2>{title}</h2>{body}'

f같이 아직 이해못하고 그냥 쓰고있는 코드들이있다

해결방법 작성
검색해서 공부해야겠다.

학습 소감
중복된코드를 하나의 함수로 만들어 parameter를 통해 약간의 값 수정을 이용하여 간단하고 수정하기 쉽게 만들었음재미있었다.

0개의 댓글