Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, jsonify, request, render_template, redirect, url_for
|
2 |
+
import os
|
3 |
+
from pymongo import MongoClient
|
4 |
+
from pymongo.errors import ConnectionFailure
|
5 |
+
import logging
|
6 |
+
|
7 |
+
# Configure logging
|
8 |
+
logging.basicConfig(level=logging.INFO)
|
9 |
+
logger = logging.getLogger(__name__)
|
10 |
+
|
11 |
+
app = Flask(__name__)
|
12 |
+
|
13 |
+
# MongoDB Configuration
|
14 |
+
MONGODB_URI = os.getenv('MONGODB_URI', 'mongodb://localhost:27017/')
|
15 |
+
DATABASE_NAME = 'code_snippets'
|
16 |
+
COLLECTION_NAME = 'snippets'
|
17 |
+
|
18 |
+
def get_db_connection():
|
19 |
+
"""Get MongoDB connection"""
|
20 |
+
try:
|
21 |
+
client = MongoClient(MONGODB_URI)
|
22 |
+
# Test connection
|
23 |
+
client.admin.command('ping')
|
24 |
+
db = client[DATABASE_NAME]
|
25 |
+
return db
|
26 |
+
except ConnectionFailure as e:
|
27 |
+
logger.error(f"MongoDB connection failed: {e}")
|
28 |
+
return None
|
29 |
+
|
30 |
+
def initialize_db():
|
31 |
+
"""Initialize database with default entries"""
|
32 |
+
db = get_db_connection()
|
33 |
+
if not db:
|
34 |
+
return False
|
35 |
+
|
36 |
+
collection = db[COLLECTION_NAME]
|
37 |
+
|
38 |
+
# Check if entries already exist
|
39 |
+
if collection.count_documents({}) > 0:
|
40 |
+
return True
|
41 |
+
|
42 |
+
# Default entries with proper indentation examples (multiple languages)
|
43 |
+
default_entries = [
|
44 |
+
{"endpoint": "navn1", "text": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint main() {\n vector<int> nums = {1, 2, 3, 4, 5};\n \n for(int i = 0; i < nums.size(); i++) {\n cout << \"Number: \" << nums[i] << endl;\n }\n \n return 0;\n}"},
|
45 |
+
{"endpoint": "navn2", "text": "def python_function():\n data = {\n 'name': 'python',\n 'values': [1, 2, 3, 4, 5]\n }\n for key, value in data.items():\n print(f'{key}: {value}')"},
|
46 |
+
{"endpoint": "navn3", "text": "class MyClass {\npublic:\n int value;\n \n MyClass(int v) : value(v) {}\n \n void display() {\n if (value > 0) {\n cout << \"Value: \" << value << endl;\n } else {\n cout << \"Invalid value\" << endl;\n }\n }\n};"},
|
47 |
+
{"endpoint": "navn4", "text": "function calculateSum(arr) {\n let sum = 0;\n \n for (let i = 0; i < arr.length; i++) {\n if (arr[i] > 0) {\n sum += arr[i];\n }\n }\n \n return sum;\n}"},
|
48 |
+
{"endpoint": "chiku1", "text": "#include <algorithm>\n#include <functional>\n\ntemplate<typename T>\nclass SmartPointer {\nprivate:\n T* ptr;\n \npublic:\n SmartPointer(T* p = nullptr) : ptr(p) {}\n \n ~SmartPointer() {\n delete ptr;\n }\n \n T& operator*() {\n return *ptr;\n }\n};"},
|
49 |
+
{"endpoint": "chiku2", "text": "try {\n int* arr = new int[100];\n \n for(int i = 0; i < 100; i++) {\n arr[i] = i * i;\n \n if(i % 10 == 0) {\n cout << \"Progress: \" << i << \"%\" << endl;\n }\n }\n \n delete[] arr;\n} catch(const exception& e) {\n cerr << \"Error: \" << e.what() << endl;\n}"},
|
50 |
+
{"endpoint": "chiku3", "text": "struct Node {\n int data;\n Node* next;\n \n Node(int val) {\n data = val;\n next = nullptr;\n }\n};\n\nvoid printList(Node* head) {\n while(head != nullptr) {\n cout << head->data << \" -> \";\n head = head->next;\n }\n cout << \"NULL\" << endl;\n}"},
|
51 |
+
{"endpoint": "chiku4", "text": "public class JavaExample {\n private List<String> items;\n \n public JavaExample() {\n this.items = new ArrayList<>();\n }\n \n public void addItem(String item) {\n if (item != null && !item.isEmpty()) {\n items.add(item);\n System.out.println(\"Added: \" + item);\n }\n }\n}"},
|
52 |
+
]
|
53 |
+
|
54 |
+
try:
|
55 |
+
collection.insert_many(default_entries)
|
56 |
+
logger.info("Database initialized with default entries")
|
57 |
+
return True
|
58 |
+
except Exception as e:
|
59 |
+
logger.error(f"Failed to initialize database: {e}")
|
60 |
+
return False
|
61 |
+
|
62 |
+
# Initialize database on startup
|
63 |
+
initialize_db()
|
64 |
+
|
65 |
+
@app.route('/')
|
66 |
+
def index():
|
67 |
+
"""Main page with admin interface"""
|
68 |
+
return render_template('index.html')
|
69 |
+
|
70 |
+
@app.route('/admin')
|
71 |
+
def admin():
|
72 |
+
"""Admin page to manage snippets"""
|
73 |
+
db = get_db_connection()
|
74 |
+
if not db:
|
75 |
+
return "Database connection failed", 500
|
76 |
+
|
77 |
+
collection = db[COLLECTION_NAME]
|
78 |
+
snippets = list(collection.find({}, {"_id": 0}).sort("endpoint", 1))
|
79 |
+
return render_template('admin.html', snippets=snippets)
|
80 |
+
|
81 |
+
@app.route('/update_snippet', methods=['POST'])
|
82 |
+
def update_snippet():
|
83 |
+
"""Update a code snippet"""
|
84 |
+
endpoint = request.form.get('endpoint')
|
85 |
+
text = request.form.get('text')
|
86 |
+
|
87 |
+
if not endpoint or text is None:
|
88 |
+
return "Missing endpoint or text", 400
|
89 |
+
|
90 |
+
db = get_db_connection()
|
91 |
+
if not db:
|
92 |
+
return "Database connection failed", 500
|
93 |
+
|
94 |
+
collection = db[COLLECTION_NAME]
|
95 |
+
|
96 |
+
try:
|
97 |
+
result = collection.update_one(
|
98 |
+
{"endpoint": endpoint},
|
99 |
+
{"$set": {"text": text}},
|
100 |
+
upsert=True
|
101 |
+
)
|
102 |
+
logger.info(f"Updated {endpoint}: {result.modified_count} documents modified")
|
103 |
+
return redirect(url_for('admin'))
|
104 |
+
except Exception as e:
|
105 |
+
logger.error(f"Failed to update snippet: {e}")
|
106 |
+
return f"Failed to update snippet: {e}", 500
|
107 |
+
|
108 |
+
# navn endpoints
|
109 |
+
@app.route('/navn1')
|
110 |
+
def navn1():
|
111 |
+
return get_snippet_response('navn1')
|
112 |
+
|
113 |
+
@app.route('/navn2')
|
114 |
+
def navn2():
|
115 |
+
return get_snippet_response('navn2')
|
116 |
+
|
117 |
+
@app.route('/navn3')
|
118 |
+
def navn3():
|
119 |
+
return get_snippet_response('navn3')
|
120 |
+
|
121 |
+
@app.route('/navn4')
|
122 |
+
def navn4():
|
123 |
+
return get_snippet_response('navn4')
|
124 |
+
|
125 |
+
# chiku endpoints
|
126 |
+
@app.route('/chiku1')
|
127 |
+
def chiku1():
|
128 |
+
return get_snippet_response('chiku1')
|
129 |
+
|
130 |
+
@app.route('/chiku2')
|
131 |
+
def chiku2():
|
132 |
+
return get_snippet_response('chiku2')
|
133 |
+
|
134 |
+
@app.route('/chiku3')
|
135 |
+
def chiku3():
|
136 |
+
return get_snippet_response('chiku3')
|
137 |
+
|
138 |
+
@app.route('/chiku4')
|
139 |
+
def chiku4():
|
140 |
+
return get_snippet_response('chiku4')
|
141 |
+
|
142 |
+
def get_snippet_response(endpoint):
|
143 |
+
"""Get snippet from database for given endpoint"""
|
144 |
+
db = get_db_connection()
|
145 |
+
if not db:
|
146 |
+
return jsonify({"error": "Database connection failed"}), 500
|
147 |
+
|
148 |
+
collection = db[COLLECTION_NAME]
|
149 |
+
|
150 |
+
try:
|
151 |
+
snippet = collection.find_one({"endpoint": endpoint}, {"_id": 0})
|
152 |
+
if snippet:
|
153 |
+
return jsonify({"text": snippet["text"]})
|
154 |
+
else:
|
155 |
+
return jsonify({"error": f"Snippet not found for {endpoint}"}), 404
|
156 |
+
except Exception as e:
|
157 |
+
logger.error(f"Failed to fetch snippet: {e}")
|
158 |
+
return jsonify({"error": f"Failed to fetch snippet: {e}"}), 500
|
159 |
+
|
160 |
+
# Keep original /replacement endpoint for backward compatibility
|
161 |
+
@app.route('/replacement')
|
162 |
+
def replacement():
|
163 |
+
return get_snippet_response('navn1') # Default to navn1
|
164 |
+
|
165 |
+
@app.route('/health')
|
166 |
+
def health():
|
167 |
+
"""Health check endpoint"""
|
168 |
+
db = get_db_connection()
|
169 |
+
if db:
|
170 |
+
return jsonify({"status": "healthy", "database": "connected"})
|
171 |
+
else:
|
172 |
+
return jsonify({"status": "unhealthy", "database": "disconnected"}), 500
|
173 |
+
|
174 |
+
if __name__ == '__main__':
|
175 |
+
port = int(os.environ.get('PORT', 7860))
|
176 |
+
app.run(host='0.0.0.0', port=port, debug=True)
|