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 = ''' Purchase Record Form

Purchase Record Form

''' @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)