Delete serwer.py

This commit is contained in:
s490122 2024-06-22 21:22:26 +02:00
parent fbdbfa4798
commit 8a2433d487
1 changed files with 0 additions and 73 deletions

View File

@ -1,73 +0,0 @@
from wsgiref.simple_server import make_server
import json
import pyodbc
from functools import partial
response_headers = [
('Content-Type', 'application/json'),
('Access-Control-Allow-Origin', '*'),
('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE'),
('Access-Control-Allow-Headers', 'Content-Type')
]
conn = pyodbc.connect(
'DRIVER={ODBC Driver 17 for SQL Server};'
'SERVER=mssql-2017.labs.wmi.amu.edu.pl;'
'DATABASE=dbad_s490122;'
'UID=dbad_s490122;'
'PWD=c1Dp8y8iWJ'
)
cursor = conn.cursor()
def add_task(cursor, data):
task_description = data.get('task_description', '')
if task_description:
cursor.execute("INSERT INTO Tasks (task_description) OUTPUT INSERTED.id VALUES (?)", (task_description,))
task_id = cursor.fetchone()[0]
conn.commit()
return {'message': 'Task added successfully', 'id': task_id}, '200 OK'
else:
return {'message': 'Task description is required'}, '400 Bad Request'
def get_tasks(cursor):
cursor.execute("SELECT id, task_description FROM Tasks")
tasks = cursor.fetchall()
tasks_list = [{'id': task[0], 'task_description': task[1]} for task in tasks]
return tasks_list, '200 OK'
def delete_task(cursor, task_id):
cursor.execute("DELETE FROM Tasks WHERE id = ?", (task_id,))
conn.commit()
return {'message': 'Task deleted successfully'}, '200 OK'
def application(environ, start_response):
path = environ.get('PATH_INFO', '')
method = environ.get('REQUEST_METHOD', '')
if method == 'OPTIONS':
start_response('200 OK', response_headers)
return [b'']
try:
if method == 'POST' and path == '/add_task':
request_body_size = int(environ.get('CONTENT_LENGTH', 0))
request_body = environ['wsgi.input'].read(request_body_size)
data = json.loads(request_body)
response, status = add_task(cursor, data)
elif method == 'GET' and path == '/get_tasks':
response, status = get_tasks(cursor)
elif method == 'DELETE' and path.startswith('/delete_task/'):
task_id = int(path.split('/')[-1])
response, status = delete_task(cursor, task_id)
else:
response, status = {'message': 'Not Found'}, '404 Not Found'
except Exception as e:
response, status = {'message': str(e)}, '500 Internal Server Error'
start_response(status, response_headers)
return [json.dumps(response).encode('utf-8')]
if __name__ == "__main__":
httpd = make_server('', 8000, application)
print("Serving on port 8000...")
httpd.serve_forever()