Ananserver / main.py
abdullahalioo's picture
Update main.py
39e2f00 verified
from flask import Flask, render_template, request, jsonify, send_file
import json
import os
from datetime import datetime
import csv
from io import StringIO
app = Flask(__name__)
# Ensure data directory exists
os.makedirs('data', exist_ok=True)
# JSON file path
DATA_FILE = 'tickets.json'
def load_data():
try:
with open(DATA_FILE, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
return {"tickets": []}
def save_data(data):
with open(DATA_FILE, 'w') as f:
json.dump(data, f, indent=2)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/add_data/<email>/<phone>/<name>/<tickets_count>/<ticket_number>/<country>/<region>')
def add_data(email, phone, name, tickets_count, ticket_number, country, region):
data = load_data()
# Create new ticket entry
new_ticket = {
"email": email,
"phone": phone,
"name": name,
"tickets_count": int(tickets_count),
"ticket_number": ticket_number,
"country": country,
"region": region,
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
data["tickets"].append(new_ticket)
save_data(data)
return jsonify({"status": "success", "message": "Ticket data added successfully"})
@app.route('/get_tickets')
def get_tickets():
data = load_data()
return jsonify(data)
@app.route('/download_csv')
def download_csv():
data = load_data()
# Create CSV in memory
output = StringIO()
writer = csv.writer(output)
# Write header
writer.writerow(["Email", "Phone", "Name", "Tickets Count", "Ticket Number", "Country", "Region", "Timestamp"])
# Write data
for ticket in data["tickets"]:
writer.writerow([
ticket["email"],
ticket["phone"],
ticket["name"],
ticket["tickets_count"],
ticket["ticket_number"],
ticket["country"],
ticket["region"],
ticket["timestamp"]
])
output.seek(0)
return send_file(
StringIO(output.getvalue()),
mimetype="text/csv",
as_attachment=True,
download_name="tickets_data.csv"
)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860, debug=True)