Spaces:
Sleeping
Sleeping
File size: 8,157 Bytes
f05f818 fa3a1a9 0059b56 fa3a1a9 f05f818 fa3a1a9 0059b56 fa3a1a9 f05f818 7cf4e47 0059b56 f05f818 fa3a1a9 7af6ed1 f05f818 fa3a1a9 f05f818 fa3a1a9 f05f818 7af6ed1 f05f818 fa3a1a9 f05f818 7af6ed1 f05f818 fa3a1a9 f05f818 fa3a1a9 f05f818 fa3a1a9 f05f818 0059b56 7cf4e47 fa3a1a9 7cf4e47 fa3a1a9 0059b56 7cf4e47 0059b56 fa3a1a9 0059b56 fa3a1a9 0059b56 fa3a1a9 |
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 |
from flask import Flask, request, jsonify, render_template_string, redirect, session
from google_auth_oauthlib.flow import Flow
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseUpload
import os
import io
import datetime
app = Flask(__name__)
app.secret_key = os.environ.get('FLASK_SECRET_KEY')
SCOPES = ['https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive.file']
SPREADSHEET_ID = '1rcIJflbC1VIc70F6dnASLFvGQ90TXHhCx0iyxsXR7Ww'
FOLDER_ID = '1brmLNqOMCvRS0TDY6ECHvIBmlRx8pcPz'
# OAuth configuration
client_config = {
"web": {
"client_id": os.environ.get('GOOGLE_CLIENT_ID'),
"client_secret": os.environ.get('GOOGLE_CLIENT_SECRET'),
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"redirect_uris": ["https://euler314-purchase-record.hf.space/oauth2callback"]
}
}
def credentials_to_dict(credentials):
return {
'token': credentials.token,
'refresh_token': credentials.refresh_token,
'token_uri': credentials.token_uri,
'client_id': credentials.client_id,
'client_secret': credentials.client_secret,
'scopes': credentials.scopes
}
def get_credentials():
if 'credentials' not in session:
return None
return Credentials(**session['credentials'])
@app.route('/authorize')
def authorize():
flow = Flow.from_client_config(
client_config,
scopes=SCOPES,
redirect_uri=client_config['web']['redirect_uris'][0]
)
authorization_url, state = flow.authorization_url(
access_type='offline',
include_granted_scopes='true'
)
session['state'] = state
return redirect(authorization_url)
@app.route('/oauth2callback')
def oauth2callback():
state = session['state']
flow = Flow.from_client_config(
client_config,
scopes=SCOPES,
state=state,
redirect_uri=client_config['web']['redirect_uris'][0]
)
authorization_response = request.url
flow.fetch_token(authorization_response=authorization_response)
credentials = flow.credentials
session['credentials'] = credentials_to_dict(credentials)
return redirect('/')
@app.route('/')
def index():
if not get_credentials():
return redirect('/authorize')
return render_template_string(HTML_TEMPLATE)
HTML_TEMPLATE = '''
<!DOCTYPE html>
<html>
<head>
<title>Purchase Record Form</title>
<meta charset="UTF-8">
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 20px auto;
padding: 20px;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 8px;
font-weight: bold;
}
input {
width: 100%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 16px;
}
button {
background-color: #4CAF50;
color: white;
padding: 12px 24px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
width: 100%;
}
button:hover {
background-color: #45a049;
}
#status {
margin-top: 20px;
padding: 15px;
border-radius: 4px;
display: none;
}
.success {
background-color: #dff0d8;
color: #3c763d;
}
.error {
background-color: #f2dede;
color: #a94442;
}
</style>
</head>
<body>
<h2>購買記錄表單 Purchase Record Form</h2>
<form id="purchaseForm">
<div class="form-group">
<label for="name">姓名 Name:</label>
<input type="text" id="name" name="name" required>
</div>
<div class="form-group">
<label for="studentId">學號 Student ID:</label>
<input type="text" id="studentId" name="studentId" required>
</div>
<div class="form-group">
<label for="product">購買商品 Product:</label>
<input type="text" id="product" name="product" required>
</div>
<div class="form-group">
<label for="cost">金額 Cost:</label>
<input type="number" id="cost" name="cost" required>
</div>
<div class="form-group">
<label for="receipt">發票 Receipt:</label>
<input type="file" id="receipt" name="receipt" accept="image/*,.pdf" required>
</div>
<button type="submit">提交 Submit</button>
</form>
<div id="status"></div>
<script>
document.getElementById('purchaseForm').addEventListener('submit', async (e) => {
e.preventDefault();
const status = document.getElementById('status');
status.style.display = 'block';
status.textContent = '提交中... Submitting...';
status.className = '';
const formData = new FormData(e.target);
try {
const response = await fetch('/submit', {
method: 'POST',
body: formData
});
const result = await response.json();
if (result.success) {
status.className = 'success';
status.textContent = '提交成功! ' + result.message;
e.target.reset();
} else {
status.className = 'error';
status.textContent = '錯誤:' + result.message;
}
} catch (error) {
status.className = 'error';
status.textContent = '提交錯誤 Error submitting form';
}
});
</script>
</body>
</html>
'''
@app.route('/')
def index():
return render_template_string(HTML_TEMPLATE)
@app.route('/submit', methods=['POST'])
def submit():
try:
name = request.form['name']
student_id = request.form['studentId']
product = request.form['product']
cost = request.form['cost']
file = request.files['receipt']
credentials = Credentials.from_authorized_user_info(CREDENTIALS)
# Upload file to Drive
drive_service = build('drive', 'v3', credentials=credentials)
file_metadata = {
'name': f"{student_id}_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}_{file.filename}",
'parents': [FOLDER_ID]
}
media = MediaIoBaseUpload(
io.BytesIO(file.read()),
mimetype=file.content_type,
resumable=True
)
uploaded_file = drive_service.files().create(
body=file_metadata,
media_body=media,
fields='id,webViewLink'
).execute()
file_url = uploaded_file.get('webViewLink', '')
# Update Google Sheet
sheets_service = build('sheets', 'v4', credentials=credentials)
timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
ip_address = request.remote_addr
values = [[name, student_id, product, cost, file_url, timestamp, ip_address]]
body = {'values': values}
sheets_service.spreadsheets().values().append(
spreadsheetId=SPREADSHEET_ID,
range='Sheet1!A:G',
valueInputOption='USER_ENTERED',
body=body
).execute()
return jsonify({'success': True, 'message': 'Data submitted successfully!'})
except Exception as e:
return jsonify({'success': False, 'message': f'Error: {str(e)}'})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860) |