Upload files to "/"

This commit is contained in:
s490122 2024-06-21 21:59:11 +02:00
parent 6e895d7def
commit 5c4b79b15b
5 changed files with 375 additions and 0 deletions

76
TaskManager Normal file
View File

@ -0,0 +1,76 @@
// Funkcyjny
import java.util.*;
import java.util.stream.Collectors;
class Task {
private int id;
private String description;
public Task(int id, String description) {
this.id = id;
this.description = description;
}
public int getId() {
return id;
}
public String getDescription() {
return description;
}
@Override
public String toString() {
return "Task{" +
"id=" + id +
", description='" + description + '\'' +
'}';
}
}
class TaskManager {
private List<Task> tasks;
private int nextId;
public TaskManager() {
tasks = new ArrayList<>();
nextId = 1;
}
public Task addTask(String description) {
Task newTask = new Task(nextId++, description);
tasks.add(newTask);
return newTask;
}
public boolean deleteTask(int id) {
return tasks.removeIf(task -> task.getId() == id);
}
public List<Task> getTasks() {
return new ArrayList<>(tasks);
}
public Optional<Task> getTaskById(int id) {
return tasks.stream().filter(task -> task.getId() == id).findFirst();
}
public void printTasks() {
tasks.forEach(System.out::println);
}
public static void main(String[] args) {
TaskManager taskManager = new TaskManager();
taskManager.addTask("Finish homework");
taskManager.addTask("Read book");
System.out.println("All tasks:");
taskManager.printTasks();
taskManager.deleteTask(1);
System.out.println("Tasks after deletion:");
taskManager.printTasks();
}
}

83
app.js Normal file
View File

@ -0,0 +1,83 @@
// Nowe zadanie
async function addTask() {
const taskDescription = document.getElementById('new-task').value;
if (!taskDescription) {
alert('Opis zadania nie może być pusty!');
return;
}
try {
const response = await fetch('http://localhost:8000/add_task', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ task_description: taskDescription })
});
if (!response.ok) {
throw new Error('Odpowiedź sieci nie była OK');
}
const result = await response.json();
console.log('Zadanie dodane:', result);
document.getElementById('new-task').value = '';
loadTasks();
} catch (error) {
console.error('Błąd podczas dodawania zadania:', error);
}
}
// Ładowanie zadania
async function loadTasks() {
try {
const response = await fetch('http://localhost:8000/get_tasks');
if (!response.ok) {
throw new Error('Odpowiedź sieci nie była OK');
}
const tasks = await response.json();
const taskList = document.getElementById('task-list');
taskList.innerHTML = '';
tasks.forEach(task => {
const listItem = document.createElement('li');
listItem.textContent = task.task_description;
// Przycisk do usuwania zadania
//PARADYGMAT STEROWANIA ZDARZENIAMI
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Usuń';
deleteButton.onclick = () => deleteTask(task.id);
listItem.appendChild(deleteButton);
taskList.appendChild(listItem);
});
} catch (error) {
console.error('Błąd podczas ładowania zadań:', error);
}
}
// Usuwanie zdarzenia
async function deleteTask(taskId) {
try {
const response = await fetch(`http://localhost:8000/delete_task/${taskId}`, {
method: 'DELETE'
});
if (!response.ok) {
throw new Error('Odpowiedź sieci nie była OK');
}
const result = await response.json();
console.log('Zadanie usunięte:', result);
loadTasks();
} catch (error) {
console.error('Błąd podczas usuwania zadania:', error);
}
}
document.addEventListener('DOMContentLoaded', () => {
loadTasks();
});

20
index.html Normal file
View File

@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To-Do App</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1>To-Do List</h1>
<div class="input-container">
<input type="text" id="new-task" placeholder="Enter new task">
<button onclick="addTask()">Add Task</button>
</div>
<ul id="task-list"></ul>
</div>
<script src="app.js"></script>
</body>
</html>

97
serwer.py Normal file
View File

@ -0,0 +1,97 @@
# Imperatywne i Deklaratywne
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 application(environ, start_response):
path = environ.get('PATH_INFO', '') # Pobranie ścieżki
method = environ.get('REQUEST_METHOD', '') # Pobranie HTTP
response_headers = [
('Content-Type', 'application/json'),
('Access-Control-Allow-Origin', '*'),
('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE'),
('Access-Control-Allow-Headers', 'Content-Type')
]
if method == 'OPTIONS':
start_response('200 OK', response_headers)
return [b'']
# Dodawanie zadania
if path == '/add_task' and method == 'POST':
try:
# Parsowanie
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', '')
# Dodanie
if task_description:
cursor.execute("INSERT INTO Tasks (task_description) OUTPUT INSERTED.id VALUES (?)", (task_description,))
task_id = cursor.fetchone()[0]
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)}) # Obsługa błędu
status = '500 Internal Server Error'
# Pobieranie zadań
elif path == '/get_tasks' and method == 'GET':
try:
cursor.execute("SELECT id, task_description FROM Tasks") # Pobranie zadań z bazy danych
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)}) # Obsługa błędu
status = '500 Internal Server Error'
# Usuwanie zadania
elif path.startswith('/delete_task/') and method == 'DELETE':
try:
task_id = int(path.split('/')[-1])
cursor.execute("DELETE FROM Tasks WHERE id = ?", (task_id,)) # Usunięcie zadania z bazy danych
conn.commit()
response = json.dumps({'message': 'Task deleted successfully'})
status = '200 OK'
except Exception as e:
response = json.dumps({'message': str(e)}) # Obsługa błędu
status = '500 Internal Server Error'
else:
response = json.dumps({'message': 'Not Found'})
status = '404 Not Found'
start_response(status, response_headers)
return [response.encode('utf-8')]
if __name__ == "__main__":
httpd = make_server('', 8000, application) # Utworzenie serwera na porcie 8000
print("Serving on port 8000...")
httpd.serve_forever() # Rozpoczęcie obsługi żądań

99
styles.css Normal file
View File

@ -0,0 +1,99 @@
body, h1, ul, li, button, input {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: Arial, sans-serif;
}
body {
background-color: #f4f4f9;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
background: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 300px;
}
h1 {
font-size: 24px;
margin-bottom: 20px;
text-align: center;
color: #333;
}
.input-container {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
}
input[type="text"] {
flex: 1;
padding: 10px;
font-size: 16px;
border: 1px solid #ddd;
border-radius: 5px;
margin-right: 10px;
}
button {
padding: 10px;
font-size: 16px;
border: none;
border-radius: 5px;
background-color: #007bff;
color: #fff;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #0056b3;
}
ul {
list-style: none;
}
li {
background: #f9f9f9;
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
li.completed {
text-decoration: line-through;
color: #999;
}
li button {
margin-left: 10px;
}
li button:first-of-type {
background-color: #28a745;
}
li button:first-of-type:hover {
background-color: #218838;
}
li button:last-of-type {
background-color: #dc3545;
}
li button:last-of-type:hover {
background-color: #c82333;
}