Files
employee_votes/temp_app.py
91771 314474a682 上傳檔案到「/」
-- 指定專案資料夾
cd /employee_votes

-- gitea 初始化
git init 

-- 建立註解
git add . 
git commit -m "Initial commit" 

-- 切換到 main 分支
git branch -M main

-- 上傳檔案到 gitea
git remote add origin https://github.com/91771/<REPO>.git 
git push -u origin main
2025-09-17 15:18:20 +08:00

301 lines
11 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from flask import Flask, render_template, request, jsonify
import mysql.connector
import requests
from bs4 import BeautifulSoup
import json
from datetime import datetime
import re
import urllib3
# ç¦<C3A7>用SSLè­¦å?
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
app = Flask(__name__)
# Database configuration from DB_connection.txt
DB_CONFIG = {
'host': 'mysql.theaken.com',
'port': 33306,
'database': 'db_A019',
'user': 'A019',
'password': '9wvKEkxBzVca'
}
def get_db_connection():
"""Establish database connection"""
try:
conn = mysql.connector.connect(**DB_CONFIG)
return conn
except mysql.connector.Error as e:
print(f"Database connection error: {e}")
return None
def create_menu_table():
"""Create menu_items table if not exists"""
conn = get_db_connection()
if conn:
try:
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS menu_items (
Id INTEGER AUTO_INCREMENT PRIMARY KEY,
main_course VARCHAR(50) NOT NULL,
side_dish VARCHAR(50),
addon VARCHAR(50),
is_active BOOLEAN NOT NULL
)
""")
conn.commit()
print("Menu table created or already exists")
except mysql.connector.Error as e:
print(f"Error creating table: {e}")
finally:
conn.close()
def scrape_menu_data():
"""Scrape menu data from the target URL"""
url = "https://club.panjit.com.tw/back/menu/menu.php?1672970133&indexselectid=1"
try:
# Bypass SSL verification for the target website
response = requests.get(url, timeout=10, verify=False)
response.raise_for_status()
soup = BeautifulSoup(response.content, 'html.parser')
# ?¹æ?實é?ç¶²ç?çµ<C3A7>æ?è§???œå–®è³‡æ?
menu_items = []
# ?¥æ‰¾?œå–®è¡¨æ ¼?–å?è¡? menu_tables = soup.find_all('table')
menu_lists = soup.find_all(['ul', 'ol'])
# 如æ??¾åˆ°è¡¨æ ¼çµ<C3A7>æ?
if menu_tables:
for table in menu_tables:
rows = table.find_all('tr')
for row in rows:
cells = row.find_all('td')
if len(cells) >= 2: # ?³å??‰å?稱å??¹æ ¼
name = cells[0].get_text(strip=True)
price_text = cells[1].get_text(strip=True)
# ?<3F>å??¹æ ¼?¸å?
price = 0.0
try:
# 從æ?字中?<3F>å??¸å?
price_match = re.search(r'\d+', price_text)
if price_match:
price = float(price_match.group())
except:
pass
if name and price > 0:
menu_items.append({
'name': name,
'category': '主é?',
'price': price,
'description': f'{name} - 美å³é¤<C3A9>é?',
'image_url': f'/static/images/{name.replace(" ", "_").lower()}.jpg'
})
# 如æ??¾åˆ°?—表çµ<C3A7>æ?
elif menu_lists:
for menu_list in menu_lists:
items = menu_list.find_all('li')
for item in items:
text = item.get_text(strip=True)
if text and any(char.isdigit() for char in text):
# ?—試è§???…ç›®?<3F>稱?Œåƒ¹?? # 尋找?¹æ ¼æ¨¡å?
price_match = re.search(r'(\$|NT\$|\$)?\s*(\d+)', text)
if price_match:
price = float(price_match.group(2))
name = re.sub(r'(\$|NT\$|\$)?\s*\d+', '', text).strip()
if name and price > 0:
menu_items.append({
'name': name,
'category': 'é¤<EFBFBD>é?',
'price': price,
'description': f'{name} - ç²¾é<C2BE>¸ç¾Žé?',
'image_url': f'/static/images/{name.replace(" ", "_").lower()}.jpg'
})
# 如æ?以ä??¹æ??½æ??¾åˆ°ï¼Œä½¿?¨å??¨æ–¹æ¡ˆï??œå??…å<E280A6>«?œå–®?‡å??„div?span
if not menu_items:
# 尋找?¯èƒ½?…å<E280A6>«?œå–®?…ç›®?„å?ç´? possible_menu_elements = soup.find_all(['div', 'span', 'p'])
for elem in possible_menu_elements:
text = elem.get_text(strip=True)
if text and len(text) > 3 and any(char.isdigit() for char in text):
price_match = re.search(r'(\$|NT\$|\$)?\s*(\d+)', text)
if price_match:
price = float(price_match.group(2))
name = re.sub(r'(\$|NT\$|\$)?\s*\d+.*', '', text).strip()
if name and price > 0 and len(name) > 1:
menu_items.append({
'name': name,
'category': 'é¤<EFBFBD>é?',
'price': price,
'description': f'{name} - é¤<C3A9>廳?¨è–¦',
'image_url': f'/static/images/{name.replace(" ", "_").lower()}.jpg'
})
# 如æ?ä»<C3A4>ç„¶æ²æ??¾åˆ°?œå–®?…目,使?¨ç?例è??? if not menu_items:
menu_items = [
{
'name': 'ç¶“å…¸?›è?éº?,
'category': '主é?',
'price': 120.00,
'description': '?³çµ±?°ç<C2B0>£?›è?麵ï?湯頭濃é?',
'image_url': '/static/images/beef_noodle.jpg'
},
{
'name': '?žè…¿é£?,
'category': '主é?',
'price': 95.00,
'description': '香ç??žè…¿?<3F>æ???,
'image_url': '/static/images/chicken_rice.jpg'
},
{
'name': '?¬è?æ²™æ?',
'category': '?<3F>è?',
'price': 65.00,
'description': '?°é®®?‚蔬?­é??¹è£½?¬æ?',
'image_url': '/static/images/salad.jpg'
},
{
'name': 'ç´…ç??…å???,
'category': '主é?',
'price': 150.00,
'description': '?³çµ±æ±Ÿæ??œï??‰è³ªé®®å«©',
'image_url': '/static/images/lion_head.jpg'
},
{
'name': '?’é???,
'category': '??',
'price': 60.00,
'description': '?‚令?¬è?清ç?',
'image_url': '/static/images/vegetable.jpg'
}
]
return menu_items
except requests.RequestException as e:
print(f"Error scraping menu data: {e}")
# è¿”å?範ä?資æ?作為?™ç”¨
return [
{
'name': 'ç¶“å…¸?›è?éº?,
'category': '主é?',
'price': 120.00,
'description': '?³çµ±?°ç<C2B0>£?›è?麵ï?湯頭濃é?',
'image_url': '/static/images/beef_noodle.jpg'
},
{
'name': '?žè…¿é£?,
'category': '主é?',
'price': 95.00,
'description': '香ç??žè…¿?<3F>æ???,
'image_url': '/static/images/chicken_rice.jpg'
}
]
def insert_menu_data():
"""Insert sample menu items into database"""
conn = get_db_connection()
if conn:
try:
cursor = conn.cursor()
# Clear existing data
cursor.execute("DELETE FROM menu_items")
# Insert sample data that matches the new table structure
sample_menu_items = [
('ç¶“å…¸?›è?éº?, '?工麵æ?', '?¸è?æ¹?, True),
('香ç??žè…¿é£?, '?令?¬è?', '?米濃湯', True),
('ç´…ç??…å???, '?½é£¯', 'ç´«è??花æ¹?, True),
('?¬è??’麵', None, '?³å?æ¹?, True),
('?¤é®­é­šæ?', '馬鈴?¯æ³¥', '?—ç?æ¹?, True)
]
insert_query = """
INSERT INTO menu_items (main_course, side_dish, addon, is_active)
VALUES (%s, %s, %s, %s)
"""
for item in sample_menu_items:
cursor.execute(insert_query, item)
conn.commit()
print(f"Inserted {len(sample_menu_items)} menu items")
except mysql.connector.Error as e:
print(f"Error inserting menu data: {e}")
finally:
conn.close()
@app.route('/')
def index():
"""Main page - display menu items"""
conn = get_db_connection()
menu_items = []
if conn:
try:
cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT * FROM menu_items ORDER BY category, name")
menu_items = cursor.fetchall()
except mysql.connector.Error as e:
print(f"Error fetching menu items: {e}")
finally:
conn.close()
return render_template('index.html', menu_items=menu_items)
@app.route('/api/menu')
def api_menu():
"""API endpoint to get menu items"""
conn = get_db_connection()
menu_items = []
if conn:
try:
cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT * FROM menu_items ORDER BY category, name")
menu_items = cursor.fetchall()
except mysql.connector.Error as e:
print(f"Error fetching menu items: {e}")
finally:
conn.close()
return jsonify(menu_items)
@app.route('/init')
def initialize():
"""Initialize database with menu data"""
create_menu_table()
insert_menu_data()
return "Database initialized with sample menu data"
if __name__ == '__main__':
# Initialize database on startup
create_menu_table()
# Check if menu items exist, if not, insert sample data
conn = get_db_connection()
if conn:
try:
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM menu_items")
count = cursor.fetchone()[0]
if count == 0:
insert_menu_data()
except mysql.connector.Error as e:
print(f"Error checking menu items: {e}")
finally:
conn.close()
app.run(debug=True, port=5000)