Ramesh-vani commited on
Commit
d202864
·
1 Parent(s): 6583dab

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -12
app.py CHANGED
@@ -1,15 +1,51 @@
1
  from http.server import HTTPServer, BaseHTTPRequestHandler
2
  import json
3
- import subprocess
4
-
5
- def server():
6
- process = subprocess.Popen('gunicorn -w 4 -b 0.0.0.0:7860 app:server', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
7
- output, error = process.communicate()
8
- if process.returncode == 0:
9
- result = output.decode('utf-8')
10
- return result
11
- else:
12
- result = error.decode('utf-8')
13
- return result
14
- server()
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from http.server import HTTPServer, BaseHTTPRequestHandler
2
  import json
3
+ from socketserver import ThreadingMixIn
 
 
 
 
 
 
 
 
 
 
 
4
 
5
+ class MyHandler(BaseHTTPRequestHandler):
6
+ API_KEY = "123" # Replace with your actual API key
7
+
8
+ def do_GET(self):
9
+ # Extract the API key from the request headers
10
+ api_key = self.headers.get('API-Key')
11
+
12
+ if api_key == self.API_KEY:
13
+ # API key is valid, process the request
14
+ if self.path == '/api/data':
15
+ response_data = {'message': 'Hello, this is your API response!'}
16
+ self.send_response(200)
17
+ self.send_header('Content-type', 'application/json')
18
+ self.end_headers()
19
+ self.wfile.write(bytes(json.dumps(response_data), 'utf8'))
20
+ else:
21
+ # Serve HTML file for other requests
22
+ try:
23
+ with open('templates/index.html', 'r') as f:
24
+ content = f.read()
25
+ self.send_response(200)
26
+ self.send_header('Content-type', 'text/html')
27
+ self.end_headers()
28
+ self.wfile.write(bytes(content, 'utf8'))
29
+ except FileNotFoundError:
30
+ self.send_response(404)
31
+ self.send_header('Content-type', 'text/html')
32
+ self.end_headers()
33
+ self.wfile.write(b'404: File not found')
34
+ except Exception as e:
35
+ self.send_response(500)
36
+ self.send_header('Content-type', 'text/html')
37
+ self.end_headers()
38
+ self.wfile.write(f'500: Internal Server Error - {str(e)}'.encode('utf-8'))
39
+ else:
40
+ # Invalid API key
41
+ self.send_response(401)
42
+ self.send_header('Content-type', 'text/html')
43
+ self.end_headers()
44
+ self.wfile.write(b'401: Unauthorized - Invalid API Key')
45
+
46
+ # Create an HTTP server and bind it to a specific host and port
47
+ # Create a threaded HTTP server
48
+ httpd = ThreadedHTTPServer(('0.0.0.0', 7860), MyHandler)
49
+
50
+ # Start serving indefinitely
51
+ httpd.serve_forever()