on
210817 - TIL
210817 - TIL
# 한 것
## 'Hacker News' API 이용해서 게시글 데이터 가져오기(Python, Flask)
https://news.ycombinator.com/
※ 사용한 api
https://hn.algolia.com/api/v1/search?tags=story
https://hn.algolia.com/api/v1/search_by_date?tags=story
https://hn.algolia.com/api/v1/search?tags=comment,story_
ex) https://hn.algolia.com/api/v1/search?tags=comment,story_16582136
https://hn.algolia.com/api/v1/items/
ex) https://hn.algolia.com/api/v1/items/16582136
# 배운 것
## json()
There’s also a builtin JSON decoder, in case you’re dealing with JSON data:
>>> import requests >>> r = requests.get('https://api.github.com/events') >>> r.json() [{'repository': {'open_issues': 0, 'url': 'https://github.com/...
※
https://docs.python-requests.org/en/master/user/quickstart/#json-response-content
+
크롬 확장 프로그램인 JSON Viewer를 사용하면 편하게 볼 수 있다.
https://github.com/tulios/json-viewer
## Query string
- Query string
A query string is a part of a uniform resource locator (URL) that assigns values to specified parameters. A query string commonly includes fields added to a base URL by a Web browser or other client application, for example as part of an HTML form.
※
https://en.wikipedia.org/wiki/Query_string
- URL Parameter at @app.route
URL parameter is a way to pass information about a click through its URL.
※
https://support.google.com/google-ads/answer/6277564?hl=en
즉, URL에서 ? 이후로는 query string이라고 한다.
이는 @app.route에 영향을 주지 않는다.
따라서 Flask @app.route를 통한 함수에서 query string을 이용하기 위해서는 request.args를 사용해야 한다.
## flask.request.args
request.args는 URL파라미터의 값을 key=value 쌍으로 가지고 있는 딕셔너리이다.
request.args.get("key") 를 통해 해당 key의 value값을 얻을 수 있다.
## dict.get("key") 와 dict["key"]의 차이
dict.get("key") -> 이 경우에 "key"가 없으면 NoneType이 return 된다.
>>> db = {} >>> db.get("popular") >>> print(db.get("popular")) None
dict["key"] -> 이 경우에 "key"가 없으면 KeyError가 raise 된다.
File "main.py", line 31, in get_popular popular_list = db["popular"] KeyError: 'popular'
✅ 작성한 코드(Python with Flask)
import requests from flask import Flask, render_template, request base_url = "http://hn.algolia.com/api/v1" new = f"{base_url}/search_by_date?tags=story" popular = f"{base_url}/search?tags=story" def make_detail_url(id): return f"{base_url}/items/{id}" db = {} app = Flask("DayNine") def find_info_by_id(id): for pop in db["popular"]: if pop["id"] == id: return pop for new in db["new"]: if new["id"] == id: return new @app.route("/") def get_id_comments(id): id_info = find_info_by_id(id) r_comments = requests.get(f"{base_url}/search?tags=comment,story_{id}") json_comments = r_comments.json() hits_comments = json_comments["hits"] list_comments = [] for hit in hits_comments: author = hit.get("author") comment_text = hit.get("comment_text") list_comments.append({"author":author, "comment_text":comment_text}) return render_template("detail.html", info=id_info, comments=list_comments) def get_new(): r_new = requests.get(new) json_new = r_new.json() hits_new = json_new["hits"] new_list = db.get("new") if not new_list: new_list = [] for hit in hits_new: new_list.append({"title":hit["title"], "url":hit["url"], "points":hit["points"], "author":hit["author"], "num_comments":hit["num_comments"], "id":hit["objectID"]}) db["new"] = new_list return render_template("index.html", new=True, hits=new_list) def get_popular(): r_popular = requests.get(popular) json_popular = r_popular.json() hits_popular = json_popular["hits"] popular_list = db.get("popular") if not popular_list: popular_list = [] for hit in hits_popular: popular_list.append({"title":hit["title"], "url":hit["url"], "points":hit["points"], "author":hit["author"], "num_comments":hit["num_comments"], "id":hit["objectID"]}) db["popular"] = popular_list return render_template("index.html", popular=True, hits=popular_list) @app.route("/") def home(): order_by = request.args.get("order_by") if order_by == "popular": return get_popular() elif order_by == "new": return get_new() elif not order_by: return get_popular() app.run(host="0.0.0.0")
from http://refigo.tistory.com/24 by ccl(A) rewrite - 2021-08-20 20:00:23