Testing
from flask import Flask, request, send_file, render_template_string
import os
import subprocess
import stat
app = Flask(__name__)
# ────────────────────────────────────────
# CONFIGURATION
# ────────────────────────────────────────
UPLOAD_FOLDER = "/var/www/html/uploads"
ALLOWED_EXTENSIONS = {".xlsx", ".xls"}
PROCESS_SCRIPT_PATH = "/var/www/html/process_excel.py" # ← your actual script name
FIXED_INPUT_NAME = "input.xlsx"
FIXED_OUTPUT_NAME = "output.html"
COUNTER_FILE = os.path.join(UPLOAD_FOLDER, "success_count.txt")
PUBLIC_URL_PREFIX = "http://ap-vrahealth0001d.oneadr.net"
# ────────────────────────────────────────
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
# Base HTML template
BASE_HTML = """
<!doctype html>
<title>Excel Processor</title>
<style>
body {font-family: sans-serif; max-width: 800px; margin: 50px auto; line-height: 1.6;}
h1 {color:#2c3e50; text-align:center;}
.container {border:1px solid #ddd; padding:30px; border-radius:10px; background:#f9f9f9;}
input[type=file] {margin:20px 0; display:block;}
button {
padding:12px 32px; font-size:16px; background:#3498db; color:white;
border:none; border-radius:6px; cursor:pointer;
}
button:hover {background:#2980b9;}
.error {color:#c0392b; margin-top:15px; white-space:pre-wrap; font-family:monospace;}
.success-box {background:#e8f5e9; border:1px solid #c8e6c9; border-radius:8px; padding:25px; margin:30px 0; text-align:center;}
.btn {display:inline-block; padding:14px 32px; margin:15px 10px; color:white; text-decoration:none; border-radius:6px; font-size:1.1em; font-weight:bold;}
.open-btn {background:#4caf50;}
.dl-btn {background:#1976d2;}
.open-btn:hover {background:#388e3c;}
.dl-btn:hover {background:#1565c0;}
.note {color:#555; font-size:0.95em; margin-top:25px; word-break:break-all;}
.counter {font-size:1.1em; color:#2e7d32; margin:20px 0; font-weight:bold;}
</style>
<h1>Upload XLSX → Process → Download</h1>
<div class="container">
<form method="post" enctype="multipart/form-data">
<input type="file" name="file" accept=".xlsx,.xls" required>
<button type="submit">Upload & Process</button>
</form>
{% if error %}<p class="error">{{ error }}</p>{% endif %}
</div>
"""
def get_success_count():
if not os.path.exists(COUNTER_FILE):
return 0
try:
with open(COUNTER_FILE, 'r') as f:
return int(f.read().strip())
except:
return 0
def increment_success_count():
count = get_success_count() + 1
try:
with open(COUNTER_FILE, 'w') as f:
f.write(str(count))
except Exception as e:
print(f"Failed to write counter: {e}")
def allowed_file(filename):
return '.' in filename and filename.lower().rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@app.route('/', methods=['GET', 'POST'])
def main():
if request.method == 'POST':
if 'file' not in request.files:
return render_template_string(BASE_HTML, error="No file part")
file = request.files['file']
if file.filename == '':
return render_template_string(BASE_HTML, error="No file selected")
if file and allowed_file(file.filename):
input_path = os.path.join(UPLOAD_FOLDER, FIXED_INPUT_NAME)
file.save(input_path)
output_path = os.path.join(UPLOAD_FOLDER, FIXED_OUTPUT_NAME)
try:
result = subprocess.run(
["python3", PROCESS_SCRIPT_PATH, input_path],
capture_output=True,
text=True,
timeout=180
)
if result.returncode != 0:
error_msg = result.stderr.strip() or f"Exit code {result.returncode}"
return render_template_string(BASE_HTML, error=f"Processing failed:\n{error_msg}")
if not os.path.exists(output_path):
return render_template_string(BASE_HTML, error=(
f"Output file not created\n"
f"Expected: {output_path}\n"
f"Exists: {os.path.exists(output_path)}"
))
os.chmod(output_path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
# Increment counter only on success
increment_success_count()
current_count = get_success_count()
public_url = f"{PUBLIC_URL_PREFIX}/uploads/{FIXED_OUTPUT_NAME}"
success_content = f"""
<div class="success-box">
<h2 style="color:#2e7d32;">Processing completed successfully!</h2>
<p class="counter">Successful processings so far: {current_count}</p>
<p style="font-size:1.1em;">
<strong>output.html</strong> created (777 permissions)
</p>
<a href="/download" target="_blank" class="btn open-btn">
Open in browser
</a>
<a href="/download?force=1" class="btn dl-btn">
Download file
</a>
<div class="note">
Static link (may open in browser):<br>
<strong>{public_url}</strong>
</div>
<p style="margin-top:40px;">
<a href="/" style="color:#555; text-decoration:underline;">← Upload another file</a>
</p>
</div>
"""
return render_template_string(BASE_HTML + success_content)
except subprocess.TimeoutExpired:
return render_template_string(BASE_HTML, error="Processing timed out (> 3 minutes)")
except Exception as e:
return render_template_string(BASE_HTML, error=f"Server error: {str(e)}")
# GET → show form + current count
current_count = get_success_count()
count_display = f'<p class="counter">Successful processings so far: {current_count}</p>' if current_count > 0 else ''
return render_template_string(BASE_HTML + count_display)
@app.route('/download')
def download():
output_path = os.path.join(UPLOAD_FOLDER, FIXED_OUTPUT_NAME)
if not os.path.exists(output_path):
return render_template_string(BASE_HTML, error="output.html not found.")
force_download = 'force' in request.args
return send_file(
output_path,
mimetype='text/html',
as_attachment=force_download,
download_name=FIXED_OUTPUT_NAME
)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=False)
Comments
Post a Comment