facebookv4 commited on
Commit
66452cc
·
verified ·
1 Parent(s): 8c3a6e8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -0
app.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify
2
+ import sqlite3 as sql
3
+ import json
4
+
5
+ app = Flask(__name__)
6
+
7
+ def getDb():
8
+ """Establish a database connection and create the table if not exists."""
9
+ try:
10
+ conn = sql.connect("db.sqlite3", check_same_thread=False)
11
+ c = conn.cursor()
12
+ c.execute("""CREATE TABLE IF NOT EXISTS jsons(
13
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
14
+ data TEXT,
15
+ added_at DATETIME DEFAULT CURRENT_TIMESTAMP
16
+ )""")
17
+ conn.commit()
18
+ return conn
19
+ except Exception as e:
20
+ print(f"Database Error: {e}")
21
+ return None
22
+
23
+ @app.route("/")
24
+ def index():
25
+ return jsonify({"message": "Welcome to the free API service website!"})
26
+
27
+ @app.route("/post", methods=["POST"])
28
+ def post():
29
+ try:
30
+ data = request.get_json()
31
+ if data is None:
32
+ return jsonify({"error": "Invalid JSON data"}), 400
33
+
34
+ conn = getDb()
35
+ if not conn:
36
+ return jsonify({"error": "Database connection failed"}), 500
37
+
38
+ c = conn.cursor()
39
+ c.execute("INSERT INTO jsons (data) VALUES (?)", (json.dumps(data),))
40
+ conn.commit()
41
+ conn.close()
42
+
43
+ return jsonify({"message": "Mission Successful!.."})
44
+ except Exception as e:
45
+ return jsonify({"error": str(e)}), 500
46
+
47
+ @app.route("/view/<int:uid>")
48
+ def get_data(uid):
49
+ try:
50
+ conn = getDb()
51
+ if not conn:
52
+ return jsonify({"error": "Database connection failed"}), 500
53
+
54
+ c = conn.cursor()
55
+ c.execute("SELECT data FROM jsons WHERE id = ?", (uid,))
56
+ data = c.fetchone()
57
+ conn.close()
58
+
59
+ if data:
60
+ return jsonify(json.loads(data[0]))
61
+ else:
62
+ return jsonify({"error": "Data not found"}), 404
63
+ except Exception as e:
64
+ return jsonify({"error": str(e)}), 500
65
+
66
+ if __name__ == "__main__":
67
+ app.run(host="0.0.0.0", debug=True)