Chương 13 — Dự án Dashboard thời tiết và tin tức

Google Antigravity · NIE · cập nhật 02/10/2026

1. Lý thuyết và mục tiêu

Dashboard kết hợp dữ liệu ngoài với giao diện và cần xử lí độ trễ, lỗi, thời điểm cập nhật cùng nguồn. Bắt đầu bằng dữ liệu giả định giúp kiểm chứng giao diện và các trạng thái trước kết nối API. Khi dùng API thật, kiểm tra điều khoản, schema, hạn mức, đơn vị và cách bảo vệ key; không đặt bí mật backend vào JavaScript công khai. Tin tức và thời tiết thay đổi theo thời gian, nên dữ liệu cũ phải được gắn thời điểm, không trình bày như hiện tại.

  • Các trạng thái: đang tải, có dữ liệu, rỗng, lỗi và dữ liệu cũ.
  • Schema và đơn vị cần kiểm tra trước hiển thị.
  • Frontend công khai không bảo vệ được key chỉ bằng đổi tên biến.

2. Quy trình thực hành

  1. Tạo dữ liệu mẫu và các trạng thái giao diện.
  2. Chuẩn hóa dữ liệu, ghi nguồn và thời điểm.
  3. Thử lỗi và giá trị biên trước chọn API thật.

3. Ví dụ và cách giải quyết

Tình huống: Mẫu không có nhiệt độ hoặc có chuỗi lỗi thay số. Dashboard nên xử lí thế nào?

  1. Kiểm tra trường và kiểu dữ liệu trước định dạng.
  2. Hiển thị trạng thái thiếu/không hợp lệ, không tự đặt nhiệt độ 0.
  3. Giữ nguồn, thời điểm và thông báo phù hợp; chỉ nối API khi cách xử lí đã được kiểm tra.

4. Lỗi thường gặp

Không gọi dữ liệu giả định là thời tiết hiện tại hoặc đưa API key riêng vào trang công khai.

5. Tự kiểm tra

Đây là câu hỏi tự học có đáp án, không tự cộng điểm LMS.

Thiếu nhiệt độ có nên mặc định thành 0°C không?

Xem đáp án

Không.

Dữ liệu mẫu có giúp thử giao diện trước API thật không?

Xem đáp án

Có.

Mã mẫu: dashboard.html

Sao chép đúng tên file và thử trong thư mục thực hành. Mã HTML mở bằng trình duyệt; Python chạy bằng Python 3. SDK cần cài google-antigravity và xác thực theo tài liệu Google; ví dụ SDK chỉ được kiểm tra cú pháp, chưa chạy API thực.

<!doctype html>
<html lang="vi">
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Dashboard dữ liệu mẫu — NIE</title>
<style>body{font:18px system-ui;max-width:800px;margin:32px auto;padding:16px}button{font:inherit;margin:4px;padding:8px}section{border:1px solid #bbb;padding:20px;margin-top:20px;border-radius:12px}</style>
<h1>Dashboard thời tiết và tin tức</h1>
<p><strong>DỮ LIỆU GIẢ ĐỊNH.</strong> Bài học không gọi API và không phản ánh thời tiết hiện tại.</p>
<button id="valid">Dữ liệu hợp lệ</button><button id="empty">Danh sách tin trống</button><button id="error">Dữ liệu lỗi</button><button id="loading">Đang tải (mô phỏng)</button>
<p id="status" role="status"></p><section id="weather" aria-label="Thời tiết mẫu"></section><ul id="news"></ul>
<script>
const fixture={city:'Thành phố mẫu',temperature:28,observed_at:'2026-10-02T09:00:00+07:00',source:'NIE — dữ liệu giả định',news:['Bài thực hành: kiểm tra dữ liệu đầu vào','Bài thực hành: đọc thay đổi trước khi bàn giao']};
const status=document.getElementById('status'), weather=document.getElementById('weather'), news=document.getElementById('news');
function show(data){
  weather.replaceChildren();news.replaceChildren();
  if(!data || typeof data.temperature!=='number' || !Number.isFinite(data.temperature) ||
     !['city','source','observed_at'].every(k=>typeof data[k]==='string'&&data[k].trim()) ||
     !/(Z|[+-]\d{2}:\d{2})$/.test(data.observed_at) || !Number.isFinite(Date.parse(data.observed_at)) ||
     !Array.isArray(data.news) || data.news.some(t=>typeof t!=='string'||!t.trim())){
    status.textContent='Không hiển thị: dữ liệu chưa hợp lệ. Không thay bằng số 0.';return;
  }
  status.textContent=data.news.length?'Đã đọc dữ liệu mẫu.':'Đã đọc thời tiết mẫu; chưa có tin tức.';
  for(const text of [data.city,`${data.temperature} °C`,data.observed_at,data.source]){
    const p=document.createElement('p');p.textContent=text;weather.append(p);
  }
  for(const text of data.news){const li=document.createElement('li');li.textContent=text;news.append(li);}
}
document.getElementById('valid').addEventListener('click',()=>show(fixture));
document.getElementById('empty').addEventListener('click',()=>show({...fixture,news:[]}));
document.getElementById('error').addEventListener('click',()=>show({...fixture,temperature:null}));
document.getElementById('loading').addEventListener('click',()=>{weather.replaceChildren();news.replaceChildren();status.textContent='Đang tải — trạng thái mô phỏng, không có yêu cầu mạng.';});
show(fixture);
</script>
</html>

Mã mẫu: dashboard_data.py

Sao chép đúng tên file và thử trong thư mục thực hành. Mã HTML mở bằng trình duyệt; Python chạy bằng Python 3. SDK cần cài google-antigravity và xác thực theo tài liệu Google; ví dụ SDK chỉ được kiểm tra cú pháp, chưa chạy API thực.

"""Teaching example: validate fixture data, without calling a live API."""
import math
import json
from datetime import datetime

def normalize(data):
    temperature = data.get('temperature_c')
    if isinstance(temperature, bool) or not isinstance(temperature, (int, float)) or not math.isfinite(temperature):
        raise ValueError('temperature_c must be a finite number')
    for key in ['city', 'source', 'observed_at']:
        if not isinstance(data.get(key), str) or not data[key].strip():
            raise ValueError(f'{key} is required')
    timestamp = datetime.fromisoformat(data['observed_at'].replace('Z', '+00:00'))
    if timestamp.tzinfo is None:
        raise ValueError('observed_at must include a timezone')
    raw_news = data.get('news', [])
    if not isinstance(raw_news, list) or any(not isinstance(n, str) or not n.strip() for n in raw_news):
        raise ValueError('news must be a list of nonempty text titles')
    return {'city': data['city'].strip(), 'temperature_c': float(temperature),
            'source': data['source'].strip(), 'observed_at': timestamp.isoformat(),
            'news': [n.strip() for n in raw_news], 'is_fixture': True}

if __name__ == '__main__':
    fixture = {'city': 'Thành phố mẫu', 'temperature_c': 28,
               'source': 'DỮ LIỆU GIẢ ĐỊNH — không phải thời tiết/tin tức hiện tại',
               'observed_at': '2026-10-02T09:00:00+07:00',
               'news': ['Tin mẫu để thử trạng thái giao diện']}
    print(json.dumps(normalize(fixture), ensure_ascii=False, indent=2))

Mở dashboard.html để thử giao diện với các trạng thái hợp lệ, trống, lỗi và đang tải. python dashboard_data.py minh họa kiểm tra dữ liệu phía Python. Cả hai dùng dữ liệu giả định, chưa kết nối API thời tiết thật.

6. Tài liệu đối chiếu

Tài liệu Google Antigravity chính thức — permissions. Đối chiếu ngày 02/10/2026. Quy trình thực hành và bài tập do NIE biên soạn; các khả năng phụ thuộc giao diện, phiên bản và tài khoản.

Mục lục khóa học · Về khóa học