Skip to content

Commit 6243b56

Browse files
committed
flask실습
1 parent 12ac427 commit 6243b56

File tree

3 files changed

+146
-0
lines changed

3 files changed

+146
-0
lines changed

detail.html

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<!DOCTYPE html>
2+
<html>
3+
4+
<head>
5+
<title>
6+
Nomad News | {{result.title}}
7+
</title>
8+
<link href="https://andybrewer.github.io/mvp/mvp.css" rel="stylesheet"></link>
9+
</head>
10+
11+
<body>
12+
<header>
13+
<h1>{{result.title}}</h1>
14+
<div>
15+
{{result.points}} points | By {{result.author}} | <a href="{{result.url}}" target="_blank">{{result.url}}</a>
16+
</div>
17+
</header>
18+
<main>
19+
{% for comment in result.children %}
20+
<div>
21+
{% if comment.author == None%}
22+
[deleted]
23+
{% else %}
24+
<strong>{{comment.author}}:</strong>
25+
<p>{{comment.text | safe}}</p>
26+
{% endif %}
27+
</div>
28+
<hr />
29+
{% endfor %}
30+
</main>
31+
</body>
32+
33+
</html>

homework7.py

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import requests
2+
from flask import Flask, render_template, request
3+
4+
base_url = "http://hn.algolia.com/api/v1"
5+
new = f"{base_url}/search_by_date?tags=story"
6+
popular = f"{base_url}/search?tags=story"
7+
8+
def make_detail_url(id):
9+
return f"{base_url}/items/{id}"
10+
11+
db = {}
12+
app = Flask("DayNine")
13+
14+
@app.route("/")
15+
def home():
16+
order_by = request.args.get('order_by', 'popular')
17+
if order_by not in db:
18+
print("Requesting")
19+
if order_by == 'popular':
20+
news = requests.get(popular)
21+
elif order_by == 'new':
22+
news = requests.get(new)
23+
results = news.json()['hits']
24+
db[order_by] = results
25+
results = db[order_by]
26+
return render_template("index.html", order_by=order_by, results=results)
27+
28+
29+
@app.route("/<id>")
30+
def detail(id):
31+
detail_request = requests.get(make_detail_url(id))
32+
result = detail_request.json()
33+
return render_template("detail.html",result=result)
34+
35+
app.run(host="0.0.0.0")
36+
37+
# 이번 챌린지는 requests 라이브러리를 이용하여 api에 요청을 보내 정보를 가져온 뒤, 웹 프레임워크인 flask 를 이용하여 웹사이트를 만듭니다.
38+
39+
# API URL 설정 & fake DB (Line 4 ~ 12)
40+
# flask로 만든 홈페이지에 뿌려줘야 될 정보는 인기순과 최신순으로 정렬된 데이터들 입니다.
41+
# Line 4 ~ 6 : base_url 을 기본으로 하여 최신순 데이터들의 api는 new에 인기순 데이터들의 api는 popular에 저장합니다.
42+
# make_detail_url(id) 함수 : 이 함수는 각 기사에 해당하는 코멘트들을 얻기 위한 api를 id값을 이용해 호출합니다.
43+
# Line 11 ~ 12 : 로딩속도를 줄여주기 위한 빈 fakeDB를 만들어주고 플라스크 애플리케이션을 생성해주는 코드인 app = Flask("DayNine") 를 입력해줍니다.
44+
# 루트패스 "/" 구현 (Line 14 ~ 26, index.html)
45+
# 한 페이지 내에서 popular, new로 왔다갔다 하려면 URL 파라미터로 값을 넘겨 받아야 됩니다.
46+
# 참고문서 : request.args.get()
47+
# Line 17 ~ Line 22 : 만약 fakeDB에 해당 파라미터에 대한 정보가 저장되어 있지 않다면 requests 라이브러리를 이용하여 해당하는 api에 요청을 보내서 그 결과를 해당 변수에 저장해야 됩니다.
48+
# Line 23 : 요청해서 받아 온 api를 읽어오기 위해 requests 라이브러리의 .json() 을 사용합니다.
49+
# 참고문서 : .json()
50+
# Line 25 : 받아 온 데이터를 fakeDB에 저장합니다.
51+
# Line 26 : index.html 로 order_by 값과 results 값을 보내줍니다.
52+
# index.html의 Line 19 ~ Line 32 : 조건문을 활용하여 사용자가 new 를 클릭하면 popular에 popular로 이동할 수 있는 링크를 생성해 주고 사용자가 popular를 클릭하면 new에 new로 이동할 수 있는 링크를 생성해 줍니다.
53+
# index.html의 Line 35 ~ Line 48 : 사용자가 선택한 order_by 값을 토대로 해당하는 정보들을 뿌려줍니다.
54+
# "/<id>" 패스 구현 (Line 29 ~ 33, detail.html)
55+
# index.html에서 타이틀을 클릭하면 해당 페이지로 이동하여 코멘트들을 보여줍니다.
56+
# index.html 파일에서 title 부분에 해당하는 코드를 보면 <a href="/{{result.objectID}} 를 사용하여 링크가 걸려있는 것을 확인할 수 있습니다.
57+
# 저 링크를 클릭하면 주소가 nomadNews/123456 와 같은 페이지로 이동하게됩니다.
58+
# Line 31 : 위의 페이지에 코멘트를 뿌려주기 위해 make_detail_url(id) 함수를 호출하여 해당하는 api 주소를 얻고 그 주소를 requests 라이브러리를 사용하여 HTTP요청을 합니다.
59+
# Line 32 : 그리고나서 .json() 을 사용하여 api를 읽어옵니다.
60+
# Line 33 : detail.html 로 result 값을 보내줍니다.
61+
# detail.html : 조건문과 반복문을 이용하여 result에 저장된 정보를 필요한 것만 꺼내어 뿌려줍니다.

index.html

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
<!DOCTYPE html>
2+
<html>
3+
4+
<head>
5+
<title>
6+
Nomad News |
7+
{% if order_by == 'new' %}
8+
New
9+
{% elif order_by == 'popular'%}
10+
Popular
11+
{% endif %}
12+
</title>
13+
<link href="https://andybrewer.github.io/mvp/mvp.css" rel="stylesheet"></link>
14+
</head>
15+
16+
<body>
17+
<header>
18+
<h1>Nomad News</h1>
19+
<div>
20+
Order by:
21+
{% if order_by == 'new' %}
22+
<a href="/?order_by=popular">Popular</a>
23+
{% else %}
24+
<strong>Popular</strong>
25+
{% endif %}
26+
|
27+
{% if order_by == 'popular' %}
28+
<a href="/?order_by=new">New</a>
29+
{% else %}
30+
<strong>New</strong>
31+
{% endif %}
32+
</div>
33+
</header>
34+
<main>
35+
{% for result in results %}
36+
<div>
37+
<div>
38+
<a href="/{{result.objectID}}">
39+
<h3>{{result.title}}</h3>
40+
</a>
41+
(<a href="{{result.url}}" target="_blanl">{{result.url}}</a>)
42+
</div>
43+
<div>
44+
{{result.points}} points | By: {{result.author}} | {{result.num_comments}} comments
45+
</div>
46+
</div>
47+
<hr />
48+
{% endfor %}
49+
</main>
50+
</body>
51+
52+
</html>

0 commit comments

Comments
 (0)