
API可觀察性對于現代應用程序的最大好處
正題: python 調用三方API實現實時查詢油價查詢窗口(GUI)
import tkinter as tk
from tkinter import ttk
import requests
from datetime import datetime
tkinter
和 ttk
用于創建 GUI 界面。requests
用于進行 HTTP 請求,從 API 獲取數據。datetime
用于處理日期時間。def fetch_oil_price():
selected_province = province_var.get()
uid = ''
appkey = ''
url = 'http://oil.ylapi.cn/todayoil/info.u'
params = {
'uid': uid,
'appkey': appkey,
'prov': selected_province
}
response = requests.post(url, data=params)
print(response.text) # 打印響應內容
data = response.json()
if 'code' in data:
if data['code'] == '1000':
oil_prices = data['data']
update_time_str = oil_prices['ct']
update_time = datetime.strptime(update_time_str, '%Y-%m-%d %H:%M:%S.%f')
update_time_formatted = update_time.strftime('%Y-%m-%d')
update_time_label.config(text=f"數據更新時間:{update_time_formatted}")
for widget in oil_price_frame.winfo_children():
widget.destroy()
ttk.Label(oil_price_frame, text="類型").grid(row=0, column=0)
ttk.Label(oil_price_frame, text="油價(元/升)").grid(row=0, column=1)
row_num = 1
for key, value in oil_prices.items():
if key.startswith('p'):
type_name = key.replace('p', '') + "號" + ("柴油" if key == 'p0' else "汽油")
ttk.Label(oil_price_frame, text=type_name).grid(row=row_num, column=0)
ttk.Label(oil_price_frame, text=value).grid(row=row_num, column=1)
row_num += 1
else:
error_label.config(text=f"獲取油價失敗:{data['msg']}")
else:
error_label.config(text="獲取油價失敗:未收到有效的響應。")
fetch_oil_price()
函數用于從 API 獲取油價數據,并更新 GUI 界面。'code'
鍵,判斷是否為成功狀態碼 '1000'
。root = tk.Tk()
root.title("今日油價查詢")
main_frame = ttk.Frame(root)
main_frame.pack(padx=20, pady=20)
ttk
框架。province_label = ttk.Label(main_frame, text="選擇省份:")
province_label.grid(row=0, column=0, padx=10, pady=10)
provinces = [
"北京", "天津", "河北", "山西", "內蒙古", "遼寧", "吉林", "黑龍江",
"上海", "江蘇", "浙江", "安徽", "福建", "江西", "山東", "河南",
"湖北", "湖南", "廣東", "廣西", "海南", "重慶", "四川", "貴州",
"云南", "西藏", "陜西", "甘肅", "青海", "寧夏", "新疆", "臺灣",
"香港", "澳門"
]
province_var = tk.StringVar()
province_combobox = ttk.Combobox(main_frame, textvariable=province_var, values=provinces)
province_combobox.grid(row=0, column=1, padx=10, pady=10)
province_combobox.current(0)
fetch_button = ttk.Button(main_frame, text="查詢", command=fetch_oil_price)
fetch_button.grid(row=0, column=2, padx=10, pady=10)
update_time_label = ttk.Label(main_frame, text="")
update_time_label.grid(row=1, column=0, columnspan=3)
oil_price_frame = ttk.Frame(main_frame)
oil_price_frame.grid(row=2, column=0, columnspan=3, padx=10, pady=10)
error_label = ttk.Label(main_frame, text="")
error_label.grid(row=3, column=0, columnspan=3)
root.mainloop()
import tkinter as tk
from tkinter import ttk
import requests
from datetime import datetime
def fetch_oil_price():
selected_province = province_var.get()
uid = ''
appkey = ''
url = 'http://oil.ylapi.cn/todayoil/info.u'
params = {
'uid': uid,
'appkey': appkey,
'prov': selected_province
}
response = requests.post(url, data=params)
print(response.text) # 打印響應內容
data = response.json()
if 'code' in data:
if data['code'] == '1000':
oil_prices = data['data']
update_time_str = oil_prices['ct']
update_time = datetime.strptime(update_time_str, '%Y-%m-%d %H:%M:%S.%f')
update_time_formatted = update_time.strftime('%Y-%m-%d')
update_time_label.config(text=f"數據更新時間:{update_time_formatted}")
for widget in oil_price_frame.winfo_children():
widget.destroy()
ttk.Label(oil_price_frame, text="類型").grid(row=0, column=0)
ttk.Label(oil_price_frame, text="油價(元/升)").grid(row=0, column=1)
row_num = 1
for key, value in oil_prices.items():
if key.startswith('p'):
type_name = key.replace('p', '') + "號" + ("柴油" if key == 'p0' else "汽油")
ttk.Label(oil_price_frame, text=type_name).grid(row=row_num, column=0)
ttk.Label(oil_price_frame, text=value).grid(row=row_num, column=1)
row_num += 1
else:
error_label.config(text=f"獲取油價失敗:{data['msg']}")
else:
error_label.config(text="獲取油價失敗:未收到有效的響應。")
root = tk.Tk()
root.title("今日油價查詢")
main_frame = ttk.Frame(root)
main_frame.pack(padx=20, pady=20)
province_label = ttk.Label(main_frame, text="選擇省份:")
province_label.grid(row=0, column=0, padx=10, pady=10)
provinces = [
"北京", "天津", "河北", "山西", "內蒙古", "遼寧", "吉林", "黑龍江",
"上海", "江蘇", "浙江", "安徽", "福建", "江西", "山東", "河南",
"湖北", "湖南", "廣東", "廣西", "海南", "重慶", "四川", "貴州",
"云南", "西藏", "陜西", "甘肅", "青海", "寧夏", "新疆", "臺灣",
"香港", "澳門"
]
province_var = tk.StringVar()
province_combobox = ttk.Combobox(main_frame, textvariable=province_var, values=provinces)
province_combobox.grid(row=0, column=1, padx=10, pady=10)
province_combobox.current(0)
fetch_button = ttk.Button(main_frame, text="查詢", command=fetch_oil_price)
fetch_button.grid(row=0, column=2, padx=10, pady=10)
update_time_label = ttk.Label(main_frame, text="")
update_time_label.grid(row=1, column=0, columnspan=3)
oil_price_frame = ttk.Frame(main_frame)
oil_price_frame.grid(row=2, column=0, columnspan=3, padx=10, pady=10)
error_label = ttk.Label(main_frame, text="")
error_label.grid(row=3, column=0, columnspan=3)
root.mainloop()
最后可以使用?pip3 install pyinstaller
?打包成exe格式.
使用 Oilprice API 和 Python,我們可以輕松地獲取實時和歷史油價數據。這些數據對于金融分析師、投資者以及其他需要實時油價信息的人士來說是非常寶貴的資源。通過簡單的腳本,你可以快速整合這些數據到你的項目中。