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.responses import HTMLResponse, FileResponse, JSONResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from fastapi.security import OAuth2PasswordRequestForm, OAuth2PasswordBearer from fastapi.security import OAuth2PasswordRequestForm, OAuth2PasswordBearer
@ -14,10 +14,17 @@ from starlette.staticfiles import StaticFiles
import requests import requests
from uuid import uuid4 from uuid import uuid4
import ast
import pathlib
import shutil
import os
from .utils import * from .utils import *
from .models import Announcement, Trashbox, UserDatabase, Base from .models import Announcement, Trashbox, UserDatabase, Base
from .db import engine, SessionLocal from .db import engine, SessionLocal
from . import schema
Base.metadata.create_all(bind=engine) Base.metadata.create_all(bind=engine)
@ -29,7 +36,7 @@ app = FastAPI()
# CORS fix for development # CORS fix for development
app.add_middleware( app.add_middleware(
CORSMiddleware, CORSMiddleware,
allow_origins=["http://localhost:5173"], allow_origins=["http://localhost:5173", "http://localhost:8000"],
allow_credentials=True, allow_credentials=True,
allow_methods=["*"], allow_methods=["*"],
allow_headers=["*"], allow_headers=["*"],
@ -38,6 +45,7 @@ app.add_middleware(
templates = Jinja2Templates(directory="./front/dist") templates = Jinja2Templates(directory="./front/dist")
app.mount("/static", StaticFiles(directory = "./front/dist")) app.mount("/static", StaticFiles(directory = "./front/dist"))
app.mount("/uploads", StaticFiles(directory = "./uploads"))
@app.get("/api/announcements")#адрес объявлений @app.get("/api/announcements")#адрес объявлений
def annoncements_list(user_id: int = None, metro: str = None, category: str = None, booked_by: int = -1): 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")#адрес объявлений @app.put("/api/announcement")#адрес объявлений
def put_in_db(data = Body()): 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: # 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) 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.add(temp_ancmt) # добавляем в бд
db.commit() # сохраняем изменения db.commit() # сохраняем изменения
db.refresh(temp_ancmt) # обновляем состояние объекта db.refresh(temp_ancmt) # обновляем состояние объекта
return {"Answer" : True} return {"Answer" : True}
except: # except:
return {"Answer" : False} # return {"Answer" : False}
# Удалить объявления из базы # Удалить объявления из базы
@ -111,15 +133,19 @@ def delete_from_db(data = Body()):#функция удаления объект
# Забронировать объявление # Забронировать объявление
@app.put("/api/book") @app.post("/api/book")
def change_book_status(data = Body()): def change_book_status(data: schema.Book):
# Получаем id пользователя, который бронирует объявление try:
temp_user_id = 1 # Получаем id пользователя, который бронирует объявление
# Находим объявление по данному id temp_user_id = 1
announcement_to_change = db.query(Announcement).filter(user_id == temp_user_id).first() # Находим объявление по данному id
# Изменяем поле booked_status на полученный id announcement_to_change = db.query(Announcement).filter(id == data.id).first()
announcement_to_change.booked_status = temp_user_id # Изменяем поле booked_status на полученный id
return {"Success": True} announcement_to_change.booked_status = temp_user_id
return {"Success": True}
except:
return {"Success": False}
@app.post("/api/signup") @app.post("/api/signup")
def create_user(data = Body()): def create_user(data = Body()):
@ -172,29 +198,30 @@ def get_trashboxes(lat:float, lng:float):#крутая функция для р
head = {'Authorization': 'Bearer {}'.format(my_token)} head = {'Authorization': 'Bearer {}'.format(my_token)}
my_data={ my_data={
'x' : f"{lat}", 'x' : f"{lng}",
'y' : f"{lng}", 'y' : f"{lat}",
'limit' : '1' 'limit' : '1'
} }
response = requests.post(f"{BASE_URL}/nearest_recycling/get", headers=head, data=my_data) response = requests.post(f"{BASE_URL}/nearest_recycling/get", headers=head, data=my_data)
infos = response.json() infos = response.json()
trashboxes = [] trashboxes = []
for trashbox in infos["results"]: for trashbox in infos["results"]:
temp_dict = {} temp_dict = {}
temp_dict["Category"] = trashbox["Category"]
for obj in trashbox["Objects"]: for obj in trashbox["Objects"]:
coord_list = obj["geometry"] coord_list = obj["geometry"]
temp_dict["Lat"] = coord_list["coordinates"][0] temp_dict["Lat"] = coord_list["coordinates"][1]
temp_dict["Lng"] = coord_list["coordinates"][1] temp_dict["Lng"] = coord_list["coordinates"][0]
properties = obj["properties"] properties = obj["properties"]
temp_dict["Name"] = properties["title"] 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) 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}") @app.get("/{rest_of_path:path}")
async def react_app(req: Request, rest_of_path: str): 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