Notice
Recent Posts
Recent Comments
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
Tags
- 애플
- Espressif
- ConnectedHomeIP
- Python
- esp32
- 티스토리챌린지
- 홈네트워크
- 배당
- 힐스테이트 광교산
- MQTT
- 파이썬
- 매터
- 마이크로소프트
- 해외주식
- matter
- Apple
- homebridge
- 미국주식
- RS-485
- 나스닥
- 취미생활
- 국내주식
- 공모주
- 오블완
- 라즈베리파이
- raspberry pi
- Home Assistant
- 현대통신
- Bestin
- 월패드
Archives
- Today
- Total
YOGYUI
Flask - Dynamic Page Update (Ajax) 본문
반응형
Ajax (Asynchronous JavaScript and XML)
Ajax - 위키백과, 우리 모두의 백과사전
위키백과, 우리 모두의 백과사전. 다른 뜻에 대해서는 에이젝스 문서를 참조하십시오. 다른 뜻에 대해서는 아이아스 문서를 참조하십시오. Ajax(Asynchronous JavaScript and XML, 에이잭스)는 비동기적인
ko.wikipedia.org
Flask 자체의 기술적 내용에 해당하는 포스팅은 아니다
Ajax 사용에 대한 예시 (page update에 대한 요청은 페이지가 수행하고, 서버는 라우팅만 잘 구현해주면 된다)
[Structure]
+ proj
+ templates
- index.html
- app.py
index.html에서 1초에 한번씩 update POST 호출하여 현재 시간을 서버로부터 문자열로 받아 동적으로 업데이트 (page refresh 없이) 하는 코드를 구현해보자
<!-- index.html -->
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a>Current Time</a>
<h1 id="time"></h1>
<script>
setInterval(function(){$.ajax({
url: '/update',
type: 'POST',
success: function(response) {
console.log(response);
$("#time").html(response["time"]);
},
error: function(error) {
console.log(error);
}
})}, 1000);
</script>
</body>
# app.py
import datetime
from flask import Flask, render_template, jsonify
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/update', methods=['POST'])
def update():
now = datetime.datetime.now()
return jsonify({
'time': now.strftime('%Y-%d-%m %H:%M:%S'),
})
if __name__ == '__main__':
app.run(host='127.0.0.1', port=9999, debug=True)
크롬에서 127.0.0.1:9999로 접속하니 잘 동작한다 (브라우저 콘솔 로그 및 파이참 콘솔 로그 확인)


참고:
stackoverflow.com/questions/40963401/flask-dynamic-data-update-without-reload-page/40964086
반응형
'Software > Python' 카테고리의 다른 글
Python::구조적 패턴 매칭 - 파이썬에서 switch/case문을?! (0) | 2021.03.21 |
---|---|
Python으로 순서도 그리기 (schemdraw) (0) | 2021.01.27 |
Flask - extension을 이용한 HTTP 인증 절차 구현 (0) | 2021.01.08 |
PyQt Serial Port List (0) | 2021.01.07 |
Pyserial 시리얼 통신 모듈 커스터마이징 (0) | 2021.01.01 |