Updated put announcement, book and trashbox api methods on backend

This commit is contained in:
Dmitriy Shishkov 2023-05-17 10:40:35 +03:00
parent bf043d186c
commit 92a8b9f384
Signed by: dm1sh
GPG Key ID: 027994B0AA357688
2 changed files with 56 additions and 24 deletions

View File

@ -1,5 +1,5 @@
#подключение библиотек
from fastapi import FastAPI, Response, Path, Depends, Body, Query, status, HTTPException, APIRouter
from fastapi import FastAPI, Response, Path, Depends, Body, Form, Query, status, HTTPException, APIRouter, UploadFile, File
from fastapi.responses import HTMLResponse, FileResponse, JSONResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from fastapi.security import OAuth2PasswordRequestForm, OAuth2PasswordBearer
@ -14,10 +14,17 @@ from starlette.staticfiles import StaticFiles
import requests
from uuid import uuid4
import ast
import pathlib
import shutil
import os
from .utils import *
from .models import Announcement, Trashbox, UserDatabase, Base
from .db import engine, SessionLocal
from . import schema
Base.metadata.create_all(bind=engine)
@ -29,7 +36,7 @@ app = FastAPI()
# CORS fix for development
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:5173"],
allow_origins=["http://localhost:5173", "http://localhost:8000"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
@ -38,6 +45,7 @@ app.add_middleware(
templates = Jinja2Templates(directory="./front/dist")
app.mount("/static", StaticFiles(directory = "./front/dist"))
app.mount("/uploads", StaticFiles(directory = "./uploads"))
@app.get("/api/announcements")#адрес объявлений
def annoncements_list(user_id: int = None, metro: str = None, category: str = None, booked_by: int = -1):
@ -88,15 +96,29 @@ def single_annoncement(user_id:int):
# Занести объявление в базу
@app.put("/api/announcement")#адрес объявлений
def put_in_db(data = Body()):
try:
temp_ancmt = Announcement(data.id, data.userId, data.name, data.category, data.bestBy, data.adress, data.longtitude, data.latitude, data.description, data.src, data.metro, data.trashId, data.bookedBy)
def put_in_db(name: Annotated[str, Form()], category: Annotated[str, Form()], bestBy: Annotated[int, Form()], address: Annotated[str, Form()], longtitude: Annotated[float, Form()], latitude: Annotated[float, Form()], description: Annotated[str, Form()], src: Annotated[UploadFile | None, File()], metro: Annotated[str, Form()], trashId: Annotated[int | None, Form()] = -1):
# try:
userId = 1 # temporary
uploaded_name = ""
f = src.file
f.seek(0, os.SEEK_END)
if f.tell() > 0:
f.seek(0)
destination = pathlib.Path("./uploads/" + str(hash(src.file)) + pathlib.Path(src.filename).suffix.lower())
with destination.open('wb') as buffer:
shutil.copyfileobj(src.file, buffer)
uploaded_name = "/uploads/"+destination.name
temp_ancmt = Announcement(user_id=userId, name=name, category=category, best_by=bestBy, adress=address, longtitude=longtitude, latitude=latitude, description=description, src=uploaded_name, metro=metro, trashId=trashId)
db.add(temp_ancmt) # добавляем в бд
db.commit() # сохраняем изменения
db.refresh(temp_ancmt) # обновляем состояние объекта
return {"Answer" : True}
except:
return {"Answer" : False}
# except:
# return {"Answer" : False}
# Удалить объявления из базы
@ -111,15 +133,19 @@ def delete_from_db(data = Body()):#функция удаления объект
# Забронировать объявление
@app.put("/api/book")
def change_book_status(data = Body()):
@app.post("/api/book")
def change_book_status(data: schema.Book):
try:
# Получаем id пользователя, который бронирует объявление
temp_user_id = 1
# Находим объявление по данному id
announcement_to_change = db.query(Announcement).filter(user_id == temp_user_id).first()
announcement_to_change = db.query(Announcement).filter(id == data.id).first()
# Изменяем поле booked_status на полученный id
announcement_to_change.booked_status = temp_user_id
return {"Success": True}
except:
return {"Success": False}
@app.post("/api/signup")
def create_user(data = Body()):
@ -172,29 +198,30 @@ def get_trashboxes(lat:float, lng:float):#крутая функция для р
head = {'Authorization': 'Bearer {}'.format(my_token)}
my_data={
'x' : f"{lat}",
'y' : f"{lng}",
'x' : f"{lng}",
'y' : f"{lat}",
'limit' : '1'
}
response = requests.post(f"{BASE_URL}/nearest_recycling/get", headers=head, data=my_data)
infos = response.json()
trashboxes = []
for trashbox in infos["results"]:
temp_dict = {}
temp_dict["Category"] = trashbox["Category"]
for obj in trashbox["Objects"]:
coord_list = obj["geometry"]
temp_dict["Lat"] = coord_list["coordinates"][0]
temp_dict["Lng"] = coord_list["coordinates"][1]
temp_dict["Lat"] = coord_list["coordinates"][1]
temp_dict["Lng"] = coord_list["coordinates"][0]
properties = obj["properties"]
temp_dict["Name"] = properties["title"]
temp_dict["Adress"] = properties["address"]
temp_dict["Address"] = properties["address"]
temp_dict["Categories"] = properties["content_text"].split(',')
trashboxes.append(temp_dict)
return JSONResponse(trashboxes)
uniq_trashboxes = [ast.literal_eval(el1) for el1 in set([str(el2) for el2 in trashboxes])]
return JSONResponse(uniq_trashboxes)
@app.get("/{rest_of_path:path}")
async def react_app(req: Request, rest_of_path: str):

5
back/schema.py Normal file
View File

@ -0,0 +1,5 @@
from pydantic import BaseModel
class Book(BaseModel):
id: int