File size: 1,932 Bytes
66452cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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

@app.route("/")
def index():
    return jsonify({"message": "Welcome to the free API service website!"})

@app.route("/post", methods=["POST"])
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

@app.route("/view/<int:uid>")
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)