Upload files to "/"

This commit is contained in:
s490122 2024-06-22 21:23:17 +02:00
parent 8a2433d487
commit f301c6c131

77
serwer.py Normal file
View File

@ -0,0 +1,77 @@
from wsgiref.simple_server import make_server
import json
import pyodbc
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'
#LAMBDA
get_request_body = lambda environ: environ['wsgi.input'].read(int(environ.get('CONTENT_LENGTH', 0)))
parse_task_id_from_path = lambda path: int(path.split('/')[-1]) if path.count('/') > 1 else None
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 = get_request_body(environ)
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 = parse_task_id_from_path(path)
if task_id is not None:
response, status = delete_task(cursor, task_id)
else:
response, status = {'message': 'Invalid task ID'}, '400 Bad Request'
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()