Spaces:
Sleeping
Sleeping
File size: 5,398 Bytes
fa3a1a9 c0f64c7 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 |
from flask import Flask, render_template, request, jsonify
import gspread
from google.oauth2.credentials import Credentials
from google.oauth2.service_account import Credentials
from oauth2client.service_account import ServiceAccountCredentials
import io
import datetime
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseUpload
app = Flask(__name__)
# Your Google Sheet and Drive settings
SPREADSHEET_ID = '1FfqnS2ThmTo8QDryimD86VHI1zGyET9c3vbaiRAcaPg'
FOLDER_ID = '17gS_4w0fjOeyod6Vz6LgDK15KrQqMC-M' # Your Google Drive folder ID
# HTML template as a string
HTML_TEMPLATE = '''
<!DOCTYPE html>
<html>
<head>
<title>Purchase Record Form</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; max-width: 600px; margin: 0 auto; }
.form-group { margin-bottom: 15px; }
label { display: block; margin-bottom: 5px; }
input { width: 100%; padding: 8px; margin-bottom: 10px; border: 1px solid #ddd; border-radius: 4px; }
button { background-color: #4CAF50; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; }
button:hover { background-color: #45a049; }
#status { margin-top: 20px; padding: 10px; 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" 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 HTML_TEMPLATE
@app.route('/submit', methods=['POST'])
def submit():
try:
# Get form data
name = request.form['name']
student_id = request.form['studentId']
product = request.form['product']
cost = request.form['cost']
file = request.files['receipt']
# Initialize gspread client (using your credentials)
gc = gspread.service_account(filename='credentials.json')
sheet = gc.open_by_key(SPREADSHEET_ID).sheet1
# Upload file to Drive (using your credentials)
creds = ServiceAccountCredentials.from_json_keyfile_name('credentials.json')
drive_service = build('drive', 'v3', credentials=creds)
file_metadata = {
'name': 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', '')
# Append to sheet
timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
ip_address = request.remote_addr
sheet.append_row([name, student_id, product, cost, file_url, timestamp, ip_address])
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) |