Spaces:
Running
Running
from flask import Flask, request, jsonify | |
import sqlite3 as sql | |
import json | |
app = Flask(__name__) | |
def getDb(): | |
"""Establish a database connection and create the table if not exists.""" | |
try: | |
conn = sql.connect("db.sqlite3", check_same_thread=False) | |
c = conn.cursor() | |
c.execute("""CREATE TABLE IF NOT EXISTS jsons( | |
id INTEGER PRIMARY KEY AUTOINCREMENT, | |
data TEXT, | |
added_at DATETIME DEFAULT CURRENT_TIMESTAMP | |
)""") | |
conn.commit() | |
return conn | |
except Exception as e: | |
print(f"Database Error: {e}") | |
return None | |
def index(): | |
return jsonify({"message": "Welcome to the free API service website!"}) | |
def post(): | |
try: | |
data = request.get_json() | |
if data is None: | |
return jsonify({"error": "Invalid JSON data"}), 400 | |
conn = getDb() | |
if not conn: | |
return jsonify({"error": "Database connection failed"}), 500 | |
c = conn.cursor() | |
c.execute("INSERT INTO jsons (data) VALUES (?)", (json.dumps(data),)) | |
conn.commit() | |
conn.close() | |
return jsonify({"message": "Mission Successful!.."}) | |
except Exception as e: | |
return jsonify({"error": str(e)}), 500 | |
def get_data(uid): | |
try: | |
conn = getDb() | |
if not conn: | |
return jsonify({"error": "Database connection failed"}), 500 | |
c = conn.cursor() | |
c.execute("SELECT data FROM jsons WHERE id = ?", (uid,)) | |
data = c.fetchone() | |
conn.close() | |
if data: | |
return jsonify(json.loads(data[0])) | |
else: | |
return jsonify({"error": "Data not found"}), 404 | |
except Exception as e: | |
return jsonify({"error": str(e)}), 500 | |
if __name__ == "__main__": | |
app.run(host="0.0.0.0", debug=True) |