Skip to content
Snippets Groups Projects
Commit 6b56fff7 authored by Aymeric Chaumont's avatar Aymeric Chaumont
Browse files

changed some model types and made the waiting_time route time-dependent

parent 363be2ef
No related branches found
No related tags found
2 merge requests!29Time dependence,!28improve front
...@@ -13,14 +13,38 @@ from db import models, schemas ...@@ -13,14 +13,38 @@ from db import models, schemas
def get_waiting_time(place: str, db: Session): def get_waiting_time(place: str, db: Session):
""" Get the last estimated waiting time for the given place """ """ Get the last estimated waiting time for the given place """
db_record = db.query(models.Records).filter(models.Records.place == place).order_by(models.Records.date.desc()).first() date = datetime.now(tz=pytz.timezone("Europe/Paris"))
if db_record.waiting_time is not None: weekday, current_time = date.weekday(), date.time()
return db_record.waiting_time first_timeslot = get_timeslot(place, weekday, True, db)
else: if first_timeslot and current_time < first_timeslot[0]:
raise Exception return first_timeslot[0].hour, first_timeslot[0].minute
elif first_timeslot and current_time <= first_timeslot[1]:
waiting_time = db.query(
models.Records.waiting_time
).filter(
models.Records.place == place
).order_by(
models.Records.date.desc()
).first()
waiting_time_minutes = round(waiting_time[0].total_seconds() / 60)
return waiting_time_minutes, None
second_timeslot = get_timeslot(place, weekday, False, db)
if second_timeslot and current_time < second_timeslot[0]:
return second_timeslot[0].hour, second_timeslot[0].minute
elif second_timeslot and current_time <= second_timeslot[1]:
waiting_time = db.query(
models.Records.waiting_time
).filter(
models.Records.place == place
).order_by(
models.Records.date.desc()
).first()
waiting_time_minutes = round(waiting_time[0].total_seconds() / 60)
return waiting_time_minutes, None
return None, None
def get_stats(place: str, weekday: int, min_time_hour: int, min_time_mn: int, max_time_hour: int, max_time_mn: int, interval: timedelta, db: Session): def get_stats(place: str, weekday: int, min_time: time, max_time: time, interval: timedelta, db: Session):
""" Get the average waiting time for each interval between two time steps """ """ Get the average waiting time for each interval between two time steps """
def shift_time(t: time, delta: timedelta): def shift_time(t: time, delta: timedelta):
...@@ -54,7 +78,6 @@ def get_stats(place: str, weekday: int, min_time_hour: int, min_time_mn: int, ma ...@@ -54,7 +78,6 @@ def get_stats(place: str, weekday: int, min_time_hour: int, min_time_mn: int, ma
name = f'{start_time.hour:02}h{start_time.minute:02}' name = f'{start_time.hour:02}h{start_time.minute:02}'
slots_list.append({'name': name, 'time': average_waiting_time}) slots_list.append({'name': name, 'time': average_waiting_time})
min_time, max_time = time(min_time_hour, min_time_mn), time(max_time_hour, max_time_mn)
stats = [] stats = []
start_time, end_time = min_time, shift_time(min_time, interval) start_time, end_time = min_time, shift_time(min_time, interval)
while start_time < max_time: while start_time < max_time:
...@@ -135,7 +158,10 @@ def delete_news(id: int, db: Session): ...@@ -135,7 +158,10 @@ def delete_news(id: int, db: Session):
def get_opening_hours(place: str, db: Session): def get_opening_hours(place: str, db: Session):
""" Get the opening hours for the given place """ """ Get the opening hours for the given place """
opening_hours = db.query( opening_hours = db.query(
models.OpeningHours models.OpeningHours.day,
models.OpeningHours.timeslot,
models.OpeningHours.open_time,
models.OpeningHours.close_time,
).filter( ).filter(
models.OpeningHours.place == place models.OpeningHours.place == place
).order_by( ).order_by(
...@@ -146,16 +172,20 @@ def get_opening_hours(place: str, db: Session): ...@@ -146,16 +172,20 @@ def get_opening_hours(place: str, db: Session):
def get_timeslot(place: str, day: int, timeslot: bool, db: Session): def get_timeslot(place: str, day: int, timeslot: bool, db: Session):
""" Get the opening hours for the given place and timeslot""" """ Get the opening hours for the given place and timeslot"""
opening_hours = db.query(models.OpeningHours).filter( opening_hours = db.query(
models.OpeningHours.open_time,
models.OpeningHours.close_time,
).filter(
models.OpeningHours.place == place, models.OpeningHours.place == place,
models.OpeningHours.day == day, models.OpeningHours.day == day,
models.OpeningHours.timeslot == timeslot).first() models.OpeningHours.timeslot == timeslot
).first()
return opening_hours return opening_hours
def create_opening_hours(new_opening_hours: schemas.OpeningHoursBase, db: Session): def create_opening_hours(new_opening_hours: schemas.OpeningHoursBase, db: Session):
""" Add opening hours to the database """ """ Add opening hours to the database """
db_opening_hours = models.News(**new_opening_hours.dict()) db_opening_hours = models.OpeningHours(**new_opening_hours.dict())
db.add(db_opening_hours) db.add(db_opening_hours)
db.commit() db.commit()
db.refresh(db_opening_hours) db.refresh(db_opening_hours)
......
<<<<<<< HEAD
""" """
Models of the database for magasin app Models of the database for magasin app
""" """
from sqlalchemy import Column, Integer, DateTime, Float, Interval, String, Text from sqlalchemy import Column, Integer, DateTime, Float, Interval, String, Text, Boolean, Time
from db.database import Base from db.database import Base
...@@ -28,46 +27,6 @@ class Comments(Base): ...@@ -28,46 +27,6 @@ class Comments(Base):
place = Column(String(10)) place = Column(String(10))
class News(Base):
"""News sql table model"""
__tablename__ = "news"
id = Column(Integer, primary_key=True, index=True)
title = Column(String(50))
content = Column(Text)
published_at = Column(DateTime)
end_date = Column(DateTime)
place = Column(String(10))
=======
"""
Models of the database for magasin app
"""
from sqlalchemy import Column, Integer, DateTime, Float, Interval, String, Text, Boolean
from db.database import Base
class Records(Base):
"""Records sql table model"""
__tablename__ = "records"
id = Column(Integer, primary_key=True, index=True)
place = Column(String(10))
date = Column(DateTime)
density = Column(Float)
waiting_time = Column(Interval)
class Comments(Base):
"""Comments sql table model"""
__tablename__ = "comments"
id = Column(Integer, primary_key=True, index=True)
comment = Column(Text)
date = Column(DateTime)
place = Column(String(10))
class News(Base): class News(Base):
"""News sql table model""" """News sql table model"""
__tablename__ = "news" __tablename__ = "news"
...@@ -88,8 +47,5 @@ class OpeningHours(Base): ...@@ -88,8 +47,5 @@ class OpeningHours(Base):
place = Column(String(10)) place = Column(String(10))
day = Column(Integer) day = Column(Integer)
timeslot = Column(Boolean) timeslot = Column(Boolean)
open_hour = Column(Integer) open_time = Column(Time)
open_minute = Column(Integer) close_time = Column(Time)
close_hour = Column(Integer) \ No newline at end of file
close_minute = Column(Integer)
>>>>>>> db and back routes for restaurants opening hours
<<<<<<< HEAD
""" """
Pydantic schemas for the magasin app Pydantic schemas for the magasin app
""" """
from typing import Optional from typing import Optional
from datetime import datetime, timedelta from datetime import datetime, timedelta, time
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
...@@ -46,61 +45,6 @@ class NewsBase(BaseModel): ...@@ -46,61 +45,6 @@ class NewsBase(BaseModel):
place: str = Field(..., title="Name of the RU corresponding the news") place: str = Field(..., title="Name of the RU corresponding the news")
class News(NewsBase):
"""Database news base schema"""
id: int
published_at: datetime = Field(..., title="Publication date of the news")
class Config:
orm_mode = True
=======
"""
Pydantic schemas for the magasin app
"""
from typing import Optional
from datetime import datetime, timedelta
from pydantic import BaseModel, Field
class RecordBase(BaseModel):
"""Records base schema"""
place: str = Field(..., title="Name of the RU corresponding the given record")
date: datetime = Field(..., title="Date of the record")
density: float = Field(..., title="Estimated density of people")
waiting_time: Optional[timedelta] = Field(title="Estimated waiting time for people coming at this date")
class Record(RecordBase):
"""Database records base schema"""
id: int
class Config:
orm_mode = True
class CommentBase(BaseModel):
"""Comments base schema"""
comment: str = Field(..., title="Content of the comment posted")
class Comment(CommentBase):
"""Database comments base schema"""
id: int
date: datetime = Field(..., title="Publication date of the comment")
place: str = Field(..., title="Name of the RU corresponding the comment")
class Config:
orm_mode = True
class NewsBase(BaseModel):
"""News sql table model"""
title: str = Field(..., title="Title of the news")
content: str = Field(..., title="Content of the news")
end_date: datetime = Field(..., title="End date to display the news")
place: str = Field(..., title="Name of the RU corresponding the news")
class News(NewsBase): class News(NewsBase):
"""Database news base schema""" """Database news base schema"""
id: int id: int
...@@ -115,10 +59,8 @@ class OpeningHoursBase(BaseModel): ...@@ -115,10 +59,8 @@ class OpeningHoursBase(BaseModel):
place: str = Field(..., title="Name of the RU corresponding the given record") place: str = Field(..., title="Name of the RU corresponding the given record")
day: int = Field(..., title="Day of the week") day: int = Field(..., title="Day of the week")
timeslot: bool = Field(..., title="Service slot (True for midday, False for evening)") timeslot: bool = Field(..., title="Service slot (True for midday, False for evening)")
open_hour: int = Field(..., title="Hour of the opening time") open_time: time = Field(..., title="Opening time")
open_minute: int = Field(..., title="Minute of the opening time") close_time: time = Field(..., title="Closing time")
close_hour: int = Field(..., title="Hour of the closing time")
close_minute: int = Field(..., title="Minute of the closing time")
class OpeningHours(OpeningHoursBase): class OpeningHours(OpeningHoursBase):
...@@ -127,4 +69,3 @@ class OpeningHours(OpeningHoursBase): ...@@ -127,4 +69,3 @@ class OpeningHours(OpeningHoursBase):
class Config: class Config:
orm_mode = True orm_mode = True
>>>>>>> db and back routes for restaurants opening hours
...@@ -19,9 +19,9 @@ async def get_timeslot(place: str, day: int, timeslot: bool, db: Session = Depen ...@@ -19,9 +19,9 @@ async def get_timeslot(place: str, day: int, timeslot: bool, db: Session = Depen
return crud.get_timeslot(place, day, timeslot, db) return crud.get_timeslot(place, day, timeslot, db)
@router.post('/{place}/opening_hours', response_model=schemas.OpeningHours) @router.post('/opening_hours', response_model=schemas.OpeningHours)
async def create_opening_hours(place: str, opening_hours: schemas.OpeningHoursBase, db: Session = Depends(get_db)): async def create_opening_hours(opening_hours: schemas.OpeningHoursBase, db: Session = Depends(get_db)):
return crud.create_opening_hours(place, opening_hours, db) return crud.create_opening_hours(opening_hours, db)
@router.delete('/opening_hours/{id}', response_model=None) @router.delete('/opening_hours/{id}', response_model=None)
......
from fastapi import APIRouter, Depends from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from datetime import timedelta from datetime import timedelta, time
from typing import List
from db import crud from db import crud
from db.database import get_db from db.database import get_db
...@@ -10,12 +9,11 @@ from db.database import get_db ...@@ -10,12 +9,11 @@ from db.database import get_db
router = APIRouter(prefix="/api", tags=["stats"]) router = APIRouter(prefix="/api", tags=["stats"])
@router.get('/{place}/waiting_time', response_model=timedelta) @router.get('/{place}/waiting_time', response_model=tuple)
async def waiting_time(place: str, db: Session = Depends(get_db)): async def waiting_time(place: str, db: Session = Depends(get_db)):
return crud.get_waiting_time(place, db) return crud.get_waiting_time(place, db)
@router.get('/{place}/stats/{day}/{min_time_hour}/{min_time_mn}/{max_time_hour}/{max_time_mn}/{interval}', response_model=list) @router.get('/{place}/stats/{day}/{min_time}/{max_time}/{interval}', response_model=list)
async def stats(place: str, day: int, min_time_hour: int, min_time_mn: int, async def stats(place: str, day: int, min_time: time, max_time: time, interval: timedelta, db: Session = Depends(get_db)):
max_time_hour: int, max_time_mn: int, interval: timedelta, db: Session = Depends(get_db)): return crud.get_stats(place, day, min_time, max_time, interval, db)
return crud.get_stats(place, day, min_time_hour, min_time_mn, max_time_hour, max_time_mn, interval, db)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment