Projekts490130/server.py

134 lines
5.2 KiB
Python
Raw Normal View History

2024-06-10 16:53:44 +02:00
import subprocess
from wsgiref.simple_server import make_server
import json
import pymssql
import os
# Database configuration
conn = pymssql.connect(
server='mssql-2017.labs.wmi.amu.edu.pl',
user='dbad_s490130',
password='lTk13e45Po',
database='dbad_s490130'
)
cursor = conn.cursor()
def application(environ, start_response):
path = environ.get('PATH_INFO', '')
method = environ.get('REQUEST_METHOD', '')
# CORS Handling
if method == 'OPTIONS':
response_headers = [
('Content-Type', 'application/json'),
('Access-Control-Allow-Origin', '*'),
('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE'),
('Access-Control-Allow-Headers', 'Content-Type')
]
start_response('200 OK', response_headers)
return [b'']
response_headers = [
('Content-Type', 'application/json'),
('Access-Control-Allow-Origin', '*')
]
if path == '/add_task' and method == 'POST':
try:
request_body_size = int(environ.get('CONTENT_LENGTH', 0))
request_body = environ['wsgi.input'].read(request_body_size)
data = json.loads(request_body)
task_description = data.get('task_description', '')
if task_description:
cursor.execute("INSERT INTO Tasks (task_description) OUTPUT INSERTED.id VALUES (%s)", (task_description,))
task_id = cursor.fetchone()[0] # Fetch the newly inserted task ID
conn.commit()
response = json.dumps({'message': 'Task added successfully', 'id': task_id})
status = '200 OK'
else:
response = json.dumps({'message': 'Task description is required'})
status = '400 Bad Request'
except Exception as e:
response = json.dumps({'message': str(e)})
status = '500 Internal Server Error'
elif path == '/get_tasks' and method == 'GET':
try:
cursor.execute("SELECT id, task_description FROM Tasks")
tasks = cursor.fetchall()
tasks_list = [{'id': task[0], 'task_description': task[1]} for task in tasks]
response = json.dumps(tasks_list)
status = '200 OK'
except Exception as e:
response = json.dumps({'message': str(e)})
status = '500 Internal Server Error'
elif path.startswith('/delete_task/') and method == 'DELETE':
try:
task_id = int(path.split('/')[-1])
cursor.execute("DELETE FROM Tasks WHERE id = %s", (task_id,))
conn.commit()
response = json.dumps({'message': 'Task deleted successfully'})
status = '200 OK'
except Exception as e:
response = json.dumps({'message': str(e)})
status = '500 Internal Server Error'
elif path == '/execute_rand2' and method == 'POST':
try:
# Ensure the path to rand2.exe is correct
exe_path = 'j:\\Desktop\\Paradygmaty\\wielki projekt\\primery\\rand2.exe'
print(f"Attempting to execute: {exe_path}")
if not os.path.exists(exe_path):
raise FileNotFoundError(f"File not found: {exe_path}")
result = subprocess.run([exe_path], check=True, capture_output=True, text=True)
response = json.dumps({'message': 'rand2.exe executed successfully', 'output': result.stdout})
status = '200 OK'
except subprocess.CalledProcessError as e:
error_message = f'CalledProcessError: {e.stderr}'
print(error_message)
response = json.dumps({'message': error_message})
status = '500 Internal Server Error'
except Exception as e:
error_message = f'Exception: {str(e)}'
print(error_message)
response = json.dumps({'message': error_message})
status = '500 Internal Server Error'
elif path == '/read_random_number' and method == 'GET':
try:
with open('random_number.txt', 'r') as file:
random_number = file.read().strip()
response = random_number
status = '200 OK'
except Exception as e:
response = json.dumps({'message': str(e)})
status = '500 Internal Server Error'
elif path == '/delete_random_number' and method == 'DELETE':
try:
os.remove('random_number.txt')
response = json.dumps({'message': 'random_number.txt deleted successfully'})
status = '200 OK'
except Exception as e:
response = json.dumps({'message': str(e)})
status = '500 Internal Server Error'
else:
response = json.dumps({'message': 'Not Found'})
status = '404 Not Found'
response_headers.append(('Access-Control-Allow-Headers', 'Content-Type'))
response_headers.append(('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE'))
start_response(status, response_headers)
return [response.encode('utf-8')]
if __name__ == "__main__":
httpd = make_server('', 8000, application)
print("Serving on port 8000...")
httpd.serve_forever()