Skip to content

Commit

Permalink
add user_list and error page
Browse files Browse the repository at this point in the history
  • Loading branch information
agoktugaydin committed Jul 28, 2023
1 parent d283c04 commit 16ec8c1
Show file tree
Hide file tree
Showing 5 changed files with 318 additions and 22 deletions.
59 changes: 41 additions & 18 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from fastapi import FastAPI, Request, status
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse, RedirectResponse
from .database import DBUser, SessionLocal
import os

Expand All @@ -11,41 +12,63 @@

from .models.user import User

import ptvsd

# Enable ptvsd remote debugging
ptvsd.enable_attach(address=('localhost', 5678))

app = FastAPI()
templates = Jinja2Templates(directory="templates")


@app.get("/", response_class=HTMLResponse)
async def get_home():
html_path = os.path.join(os.path.dirname(__file__), "html/home.html")
with open(html_path, "r") as file:
return file.read()
async def get_home(request: Request):
title = "İzin Yönetim Uygulaması"
description = "Bu uygulama çalışanların izin talep edebilmesini ve yetkililerin izinleri yönetebilmesini sağlar."
return templates.TemplateResponse("home.html",
{
"request": request,
"title": title,
"description": description,
}
)

# Endpoint to get users
@app.get("/users/", response_model=list[User])
def get_users():
@app.get("/users/", response_class=HTMLResponse)
async def get_users(request: Request):
try:
session = SessionLocal()
users = session.query(DBUser).all()
session.close()
# Convert each DBUser object to a dictionary using the to_dict() method
user_dicts = [user.to_dict() for user in users]
except Exception as e:
return {"message": "Error getting users" + str(e)}
return user_dicts
error = "Error getting users" + str(e)
return templates.TemplateResponse("error.html", {"request": request, "error": error})
return templates.TemplateResponse("user_list.html", {"request": request, "users": user_dicts})

# Endpoint to save a new user
@app.post("/users/", status_code=201)
def save_user(user: User):
@app.post("/users/", response_class=HTMLResponse)
async def save_user(request: Request):
try:
db_user = DBUser(name=user.name, email=user.email, company=user.company, title=user.title) # Create a DBUser object from the User model
print(db_user.to_dict())
user_json = await request.json()
# Extract the user data from the JSON request
name = user_json["name"]
email = user_json["email"]
company = user_json["company"]
title = user_json["title"]
# Create a User object from the extracted user data
user = User(name=name, email=email, company=company, title=title)

# Create a DBUser object from the User object
db_user = DBUser(name=user.name, email=user.email, company=user.company, title=user.title)


session = SessionLocal()
session.add(db_user)
session.commit()
session.close()
except Exception as e:
return {"message": "Error saving user" + str(e)}

return {"message": "User created successfully"}

error = "Error creating user" + str(e)
return templates.TemplateResponse("error.html", {"request": request, "error": error})
return RedirectResponse(url="/users", status_code=status.HTTP_303_SEE_OTHER)
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ SQLAlchemy==1.3.23
alembic
uvicorn
psycopg2
python-dotenv
python-dotenv
jinja2
53 changes: 53 additions & 0 deletions templates/error.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<!DOCTYPE html>
<html>

<head>
<title>Error 404 - Page Not Found</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
padding: 50px;
}

h1 {
color: #007BFF;
}

.error-message {
font-size: 24px;
margin-top: 20px;
}

.error-code {
font-size: 64px;
font-weight: bold;
color: #007BFF;
}

.home-link {
margin-top: 20px;
display: inline-block;
padding: 10px 20px;
border: 1px solid #007BFF;
border-radius: 5px;
background-color: #007BFF;
color: white;
text-decoration: none;
}

.home-link:hover {
background-color: #0056b3;
}
</style>
</head>

<body>
<h1>Oops! Something happened.</h1>
<div class="error">
<p>{{errorMessage}}</p>
</div>
<a class="home-link" href="/">Go to Homepage</a>
</body>

</html>
6 changes: 3 additions & 3 deletions app/html/home.html → templates/home.html
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@
</head>

<body>
<h1>İzin Yönetim Uygulaması</h1>
<p>Bu uygulama çalışanların izin talep edebilmesini ve yetkililerin izinleri yönetebilmesini sağlar.</p>
<a class="button" href="https://izin-yonetim-sistemi-0b9ebc70bb90.herokuapp.com/users">All Users</a>
<h1>{{title}}</h1>
<p>{{description}}</p>
<a class="button" href="http://localhost:8000/users">All Users</a>
</body>

</html>
219 changes: 219 additions & 0 deletions templates/user_list.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
<!DOCTYPE html>
<html>

<head>
<title>User List</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
padding: 50px;
}

h1 {
color: #007BFF;
}

table {
width: 100%;
border-collapse: collapse;
}

th,
td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}

tr:hover {
background-color: #f2f2f2;
}

/* Pagination Section */
.pagination {
margin-top: 20px;
}

.pagination a {
color: #007BFF;
padding: 8px 16px;
text-decoration: none;
border: 1px solid #007BFF;
border-radius: 5px;
margin: 0 5px;
transition: background-color 0.3s ease, color 0.3s ease;
}

.pagination a.active {
background-color: #007BFF;
color: white;
}

.pagination a:hover:not(.active) {
background-color: #007BFF;
color: white;
}

.pagination a:hover {
background-color: white;
color: #007BFF;
}

/* Add style to the page numbers container */
#page-numbers {
margin-top: 10px;
}

/* Add CSS for the Navigation Bar (navbar) */
header {
background-color: #007BFF;
padding: 10px 0;
}

.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 20px;
color: white;
}

.navbar-icon {
font-size: 24px;
color: white;
}

.navbar-button {
padding: 8px 16px;
border: 1px solid white;
border-radius: 5px;
background-color: transparent;
color: white;
text-decoration: none;
transition: background-color 0.3s ease, color 0.3s ease;
}

.navbar-button:hover {
background-color: white;
color: #007BFF;
}
</style>
</head>

<body>

<header>
<nav class="navbar">
<span class="navbar-icon">
<i class="fas fa-home"></i>
<a class="navbar-button" href="http://localhost:8000/">Home</a>
</span>

</nav>
</header>


<h1>User List</h1>
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Company</th>
<th>Title</th>
</tr>
{% for user in users %}
<tr>
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
<td>{{ user.company }}</td>
<td>{{ user.title }}</td>
</tr>
{% endfor %}
</table>

<!-- Pagination section -->
<div class="pagination" id="pagination">
<!-- Pagination links will be added here -->
<a href="#" id="id-prev" style="visibility: hidden" onclick="prevPage()">Previous</a>
<span id="page-numbers"></span>
<a href="#" id="id-next" onclick="nextPage()">Next</a>
</div>

<script>
// Variables to track the current page and total number of pages
let currentPage = 1;
const rows = document.querySelectorAll("table tr");
const itemsPerPage = 5; // Set the number of items per page
const pageCount = Math.ceil(rows.length / itemsPerPage);

// Function to handle pagination
function showPage(pageNum) {
currentPage = pageNum;
const startIndex = (pageNum - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage;

rows.forEach((row, index) => {
if (index >= startIndex && index < endIndex) {
row.style.display = "table-row";
} else {
row.style.display = "none";
}
});

// Update the page numbers display
const pageNumbersDiv = document.getElementById("page-numbers");
let paginationHTML = "";
for (let i = 1; i <= pageCount; i++) {
if (i === pageNum) {
paginationHTML += `<a href="#" onclick="showPage(${i})" class="active">${i}</a> `;
} else {
paginationHTML += `<a href="#" onclick="showPage(${i})">${i}</a> `;
}
}
pageNumbersDiv.innerHTML = paginationHTML;

// Set the "active" class on the current page number link
const pageLinks = document.querySelectorAll(".pagination a");
pageLinks.forEach((link) => {
link.classList.remove("active");
});
pageLinks[currentPage].classList.add("active");

// Update visibility of previous and next links
if (currentPage > 1) {
document.getElementById("id-prev").style.visibility = "visible";
} else {
document.getElementById("id-prev").style.visibility = "hidden";
}

if (currentPage == pageCount) {
document.getElementById("id-next").style.visibility = "hidden";
} else {
document.getElementById("id-next").style.visibility = "visible";
}
}

// Function to navigate to the previous page
function prevPage() {
if (currentPage > 1) {
showPage(currentPage - 1);
}
}

// Function to navigate to the next page
function nextPage() {
if (currentPage < pageCount) {
showPage(currentPage + 1);
}
}

// Call the function to create pagination links and show the first page by default
showPage(1);
</script>


</body>

</html>

0 comments on commit 16ec8c1

Please sign in to comment.