最後活躍 10 months ago

這段程式碼使用 pydantic 來定義使用者模型,並且透過 Streamlit 在網頁上顯示使用者資訊,同時 pretty_errors 提供美觀的錯誤訊息格式。

user_information_display.py 原始檔案
1from datetime import date
2
3import pretty_errors
4import streamlit as st
5from pydantic import BaseModel, Field
6
7
8class User(BaseModel):
9 id: int
10 name: str
11 dob: date = Field(title="Date of Birth")
12
13 def __str__(self):
14 return f"User(id={self.id}, name={self.name}, dob={self.dob})"
15
16
17# 設定 pretty_errors 的顯示配置
18pretty_errors.configure(
19 line_number_first=True, # 顯示行號在前面
20 lines_before=5, # 顯示錯誤行之前的行數
21 lines_after=2, # 顯示錯誤行之後的行數
22 line_color=pretty_errors.RED
23 + "> "
24 + pretty_errors.default_config.line_color, # 自訂錯誤行的顏色
25 display_locals=True, # 顯示局部變數
26)
27
28
29# 定義一些使用者
30users = [
31 User(id=1, name="John", dob=date(1990, 1, 1)),
32 User(id=2, name="Jack", dob=date(1991, 1, 1)),
33 User(id=3, name="Jill", dob=date(1992, 1, 1)),
34 User(id=4, name="Jane", dob=date(1993, 1, 1)),
35]
36
37# 在 Streamlit 應用程式中展示使用者資訊
38st.title("User Information")
39for user in users:
40 st.write(f"ID: {user.id}, Name: {user.name}, Date of Birth: {user.dob}")
41