SpringBoot를 사용하여 DB에 저장한 데이터를 Python Flask를 활용하여 requests 모듈로 SpringBoot API서버를 호출하여 시각화 해보자
전송 받는 데이터의 형식
json
{
"code" : int,
"msg" : string,
"data" : [
{"_id" : string, "title": string, "time" : string},
{"_id" : string, "title": string, "time" : string}
]
}
1) News_Api 작성
import requests
import json
def getNewsApi():
url = "http://localhost:8080/news"
response = requests.get(url)
newsDto = response.json()
if newsDto["code"] == 1:
return newsDto["data"]
else:
print(newsDto["msg"])
- url 은 스프링부트로 크롤링한 데이터가 있는 페이지이다. 이를 받을 때 text 형식이 아닌 json형식으로 받아서 객체를 사용할 수 있도록 하였다.
2) router.py - flask를 이용한 시각화
from flask import Flask
from flask.templating import render_template
import news_api as na
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html", newsList=na.getNewsApi())
if __name__ == "__main__":
app.run(debug=True, port=5000)
- news_api.py에서 함수 getNewsApi()를 가져온다.
- port 번호 는 5000
3) Flask 시각화 화면 (html) - bootstrap card 사용
<!DOCTYPE html>
<html lang="en">
<head>
<title>신문리스트</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<style>
.m_box {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-gap: 10px;
}
.m_tm_20 {
margin-top: 20px;
}
</style>
</head>
<body>
</div>
<div class="container m_box m_tm_20">
{% for news in newsList %}
<!-- 신문 카드 시작 -->
<div class="card">
<div class="card-body">
<h4 class="card-title">{{news.company}}</h4>
<p class="card-text">{{news.title}}</p>
<p class="card-text">{{news.createdAt}}</p>
</div>
</div>
<!— 신문 카드 끝 —>
{% endfor %}
</div>
</div>
<script>
function myPolling(){
location.reload();
}
setInterval(myPolling, 1000*60);
</script>
</body>
</html>
추가적으로 DB에 데이터가 추가 될 시 주기적으로 자동으로 새로고침되게 하는 방법에 대해서 찾아볼것
* poling
- 주기적인 시간마다 클라이언트가 서버로 요청을 동기적으로 호출해서 사용 가능한 정보가 있는지 알아낸다. 요청을 주기적인 간격으로 이뤄 지며 클라이언트는 정보가 있든 없든 응답을 받는다. 구체적으로 말해, 정보가 있으면 서버는 그 정보를 송신하고 정보가 없으면 서버는 부정적인 응답을 반환하고 클라이언트는 연결을 닫는다.
- 폴링은 메시지가 전달되는 간격을 정확히 알고 있을 때 적절한 해결책이다. 왜냐하면 서버에 정보가 있음을 알고 있어야만 클라이언트를 동기화해서 요청을 전송할 수 있기때문이다. 다만, 실시간 데이터는 대체로 그렇게 예측 가능하지도 않고 불필요한 요청을 보낼 수도 있어서 과다한 연결이 불가피하다. 그래서 결국 메시지 비율은 적은데도 수많은 연결을 불필요하게 여 닫아야 할 수도 있다.
리얼타임 웹을 위한 기법으로 일정한 주기(특정한 시간)를 가지고 서버와 응답을 주고받는 방식이 폴링 방식이다.
setInterval 설명
setInterval(PrintTime, 1000);
자바스크립트 함수는 1급 객체! → 익명함수로 바로 넘기기 가능!!!
1분 간격으로 Polling
<script>
function myPolling(){
location.reload();
}
setInterval(myPolling, 1000*60);
<script>
'Programming > Python' 카테고리의 다른 글
Python Numpy 2강 - Slicing (0) | 2021.10.20 |
---|---|
Python Numpy 1강 - 배열 (0) | 2021.10.20 |
Python 7강 - HTML Parsing (0) | 2021.09.22 |
Python 6강 - Crawling (0) | 2021.09.20 |
Python 5강 - Web에서 구동 (0) | 2021.09.13 |