malvika2003's picture
Upload app.py
2ee2c2c verified
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs
from pathlib import Path
# Function to check credentials
def check_credentials(username, password):
# Replace with your authentication logic
return username == 'admin' and password == 'password'
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
parsed_path = urlparse(self.path)
path = parsed_path.path
if path == '/':
self._send_html_response('templates/index.html')
elif path == '/login':
self._send_html_response('templates/login.html')
else:
self.send_error(404, "File not found")
def do_POST(self):
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length).decode('utf-8')
params = parse_qs(post_data)
username = params['username'][0]
password = params['password'][0]
if check_credentials(username, password):
self.send_response(302)
self.send_header('Location', '/index.html')
self.end_headers()
else:
self._send_html_response('templates/login.html')
def _send_html_response(self, page):
path = Path(page)
if path.exists() and path.is_file():
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
with open(page, 'rb') as file:
self.wfile.write(file.read())
else:
self.send_error(404, "File not found")
def run(server_class=HTTPServer, handler_class=RequestHandler, port=8000):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print(f'Starting httpd on port {port}...')
httpd.serve_forever()
if __name__ == '__main__':
run()