upgraded entrypoint

This commit is contained in:
mpabi 2024-06-24 14:03:44 +00:00
parent 770bb13add
commit 2ed560f13a
6 changed files with 134 additions and 146 deletions

View File

@ -1,21 +1,15 @@
# app/main.py # app/main.py
from fastapi import FastAPI, HTTPException
# ---
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from fastapi import Depends
from app.database import SessionLocal, engine
from app import models, schemas
from app.database import SessionLocal models.Base.metadata.create_all(bind=engine)
from app.models import PassportData
from fastapi.staticfiles import StaticFiles
from typing import List, Optional
app = FastAPI() app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
# Dependency to get DB session # Dependency
def get_db(): def get_db():
db = SessionLocal() db = SessionLocal()
try: try:
@ -23,24 +17,17 @@ def get_db():
finally: finally:
db.close() db.close()
class PassportDataRequest(BaseModel): @app.post("/passport/", response_model=schemas.PassportData)
number: str def create_passport_data(passport_data: schemas.PassportDataCreate, db: Session = Depends(get_db)):
name: str db_passport_data = models.PassportData(**passport_data.dict())
surname: str db.add(db_passport_data)
gender: str
@app.post("/passport_data/")
def create_passport_data(request: PassportDataRequest, db: Session = Depends(get_db)):
db_passport = PassportData(number=request.number, name=request.name, surname=request.surname, gender=request.gender)
db.add(db_passport)
db.commit() db.commit()
db.refresh(db_passport) db.refresh(db_passport_data)
return db_passport return db_passport_data
@app.get("/passport_data/{passport_number}") @app.get("/passport/{passport_id}", response_model=schemas.PassportData)
def read_passport_data(passport_number: str, db: Session = Depends(get_db)): def read_passport_data(passport_id: int, db: Session = Depends(get_db)):
db_passport = db.query(PassportData).filter(PassportData.number == passport_number).first() db_passport_data = db.query(models.PassportData).filter(models.PassportData.id == passport_id).first()
if db_passport is None: if db_passport_data is None:
raise HTTPException(status_code=404, detail="Passport data not found") raise HTTPException(status_code=404, detail="Passport data not found")
return db_passport return db_passport_data

View File

@ -1,13 +1,13 @@
# app/models.py # app/models.py
from sqlalchemy import Column, Integer, String, ForeignKey from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import relationship
from app.database import Base from app.database import Base
class PassportData(Base): class PassportData(Base):
__tablename__ = 'passport_data' __tablename__ = 'passport_data'
id = Column(Integer, primary_key=True, autoincrement=True) id = Column(Integer, primary_key=True, autoincrement=True)
number = Column(String(255), unique=True, nullable=False) number = Column(String(255), unique=True, nullable=False)
name = Column(String(255), nullable=False) name = Column(String(255), nullable=True)
surname = Column(String(255), nullable=False) surname = Column(String(255), nullable=True)
gender = Column(String(255), nullable=False) gender = Column(String(255), nullable=True)
fingerprint_url = Column(String(255), nullable=True) # New field for fingerprint image URL
photo_url = Column(String(255), nullable=True) # New field for photo image URL

View File

@ -0,0 +1,19 @@
# app/schemas.py
from pydantic import BaseModel
class PassportDataBase(BaseModel):
number: str
name: str
surname: str
gender: str
fingerprint_url: str
photo_url: str
class PassportDataCreate(PassportDataBase):
pass
class PassportData(PassportDataBase):
id: int
class Config:
orm_mode: True

View File

@ -1,25 +1,76 @@
from app.database import engine # entrypoint.py
from app.models import Base #%%
from app.database import engine, SessionLocal
from app.models import Base, PassportData
import argparse import argparse
import uvicorn import uvicorn
import os
def main(port): #%%
# Create the database def load_data_from_directory(directory_path: str, db_session):
files = os.listdir(directory_path)
passport_data = {}
for file in files:
file_parts = file.split('-')
if len(file_parts) != 2:
continue
passport_number = file_parts[0]
file_type = file_parts[1].split('.')[0]
if passport_number not in passport_data:
passport_data[passport_number] = {
"fingerprint_url": None,
"photo_url": None
}
file_path = os.path.join(directory_path, file)
if file_type == 'odcisk':
passport_data[passport_number]["fingerprint_url"] = file_path
elif file_type == 'zdjecie':
passport_data[passport_number]["photo_url"] = file_path
for number, data in passport_data.items():
passport_entry = PassportData(
number=number,
name=None,
surname=None,
gender=None,
fingerprint_url=data["fingerprint_url"],
photo_url=data["photo_url"]
)
db_session.add(passport_entry)
print (passport_entry)
db_session.commit()
#%%
def main(port, data_dir):
print("Creating database tables...") print("Creating database tables...")
Base.metadata.create_all(bind=engine) Base.metadata.create_all(bind=engine)
print("Database tables created.") print("Database tables created.")
# Run the FastAPI app using uvicorn db_session = SessionLocal()
# uvicorn.run("app.main:app", host="0.0.0.0", port=port, reload=True) try:
print(f"Loading data from directory: {data_dir}")
load_data_from_directory(data_dir, db_session)
print("Data loaded into database.")
finally:
db_session.close()
# uvicorn.run("app.main:app", host="0.0.0.0", port=port, reload=True)
#%% main(9999,"data")
#%%
if __name__ == "__main__": if __name__ == "__main__":
# Create argument parser
parser = argparse.ArgumentParser(description="Run the FastAPI app") parser = argparse.ArgumentParser(description="Run the FastAPI app")
# Add port argument, default is 9999
parser.add_argument("--port", type=int, default=9999, help="Port to run the FastAPI app on") parser.add_argument("--port", type=int, default=9999, help="Port to run the FastAPI app on")
# Parse arguments parser.add_argument("--data-dir", type=str, default="data", help="Directory containing passport data files")
args = parser.parse_args() args = parser.parse_args()
main(args.port) main(args.port, args.data_dir)

View File

@ -1,40 +1,23 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Library Management</title> <title>Passport Form App</title>
<link rel="stylesheet" href="style.css"> <style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
</head> </head>
<body> <body>
<header>Library Management</header> <div id="app"></div>
<div class="container"> <script type="module" src="./script.js"></script>
<aside class="sidebar">
<h2>Add Author</h2>
<form id="addAuthorForm">
<input type="text" id="authorName" placeholder="Author Name" required>
<button type="submit">Add Author</button>
</form>
<h2>Add Book</h2>
<form id="addBookForm">
<input type="text" id="bookTitle" placeholder="Book Title" required>
<select id="bookAuthorId">
<!-- Autorzy będą dodawani tutaj dynamicznie -->
</select>
<button type="submit">Add Book</button>
</form>
</aside>
<main class="content">
<h2>Authors</h2>
<ul id="authorsList"></ul>
<h2>Books</h2>
<ul id="booksList"></ul>
<button id="loadBooksWithAuthors">Load Books with Authors</button>
<ul id="booksWithAuthorsList"></ul>
</main>
</div>
<footer>2024 Library Management System</footer>
<script src="script.js"></script>
</body> </body>
</html> </html>

View File

@ -1,69 +1,17 @@
const BASE_URL = 'http://qstack.pl:1111'; // Zaktualizuj zgodnie z konfiguracją Twojego serwera import { createApp } from './js/vue.esm-browser.js';
import PassportForm from './components/PassportForm.js';
document.addEventListener('DOMContentLoaded', function() { const App = {
loadAuthors(); name: 'App',
loadBooks(); components: {
}); PassportForm
},
template: `
<div id="app">
<PassportForm />
</div>
`,
};
document.getElementById('addAuthorForm').addEventListener('submit', function(e) { createApp(App).mount('#app');
e.preventDefault();
const authorName = document.getElementById('authorName').value;
fetch(`${BASE_URL}/authors/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: authorName }),
})
.then(response => response.json())
.then(() => {
loadAuthors(); // Ponowne ładowanie listy autorów po dodaniu nowego autora
})
.catch(error => console.error('Error:', error));
});
document.getElementById('addBookForm').addEventListener('submit', function(e) {
e.preventDefault();
const bookTitle = document.getElementById('bookTitle').value;
const bookAuthorId = document.getElementById('bookAuthorId').value;
fetch(`${BASE_URL}/books/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: bookTitle, author_id: parseInt(bookAuthorId, 10) }),
})
.then(response => response.json())
.then(() => {
loadBooks(); // Ponowne ładowanie listy książek po dodaniu nowej książki
})
.catch(error => console.error('Error:', error));
});
function loadAuthors() {
fetch(`${BASE_URL}/authors/`)
.then(response => response.json())
.then(data => {
const authorsSelect = document.getElementById('bookAuthorId');
authorsSelect.innerHTML = '<option value="">Select an Author</option>'; // Dodaj domyślną opcję
data.forEach(author => {
const option = document.createElement('option');
option.value = author.id;
option.textContent = author.name;
authorsSelect.appendChild(option);
});
})
.catch(error => console.error('Error:', error));
}
function loadBooks() {
fetch(`${BASE_URL}/books/`)
.then(response => response.json())
.then(data => {
const booksList = document.getElementById('booksList');
booksList.innerHTML = '';
data.forEach(book => {
const listItem = document.createElement('li');
listItem.textContent = `${book.title} - Author ID: ${book.author_id}`;
booksList.appendChild(listItem);
});
})
.catch(error => console.error('Error:', error));
}