'update
This commit is contained in:
61
main.py
Normal file
61
main.py
Normal file
@@ -0,0 +1,61 @@
|
||||
from fastapi import FastAPI, HTTPException, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
# from . import models, schemas, crud
|
||||
import models
|
||||
import schemas
|
||||
import crud
|
||||
|
||||
# from .database import SessionLocal, engine
|
||||
from database import SessionLocal, engine
|
||||
|
||||
|
||||
# 创建数据库表
|
||||
models.Base.metadata.create_all(bind=engine)
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
# 依赖项,用于获取数据库会话
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
# 创建新的城市天气记录
|
||||
@app.post("/city_weather/", response_model=schemas.CityWeather)
|
||||
def create_city_weather(city_weather: schemas.CityWeatherCreate, db: Session = Depends(get_db)):
|
||||
db_city = crud.get_city_weather_by_name(db, city_name=city_weather.city_name)
|
||||
if db_city:
|
||||
raise HTTPException(status_code=400, detail="City already registered")
|
||||
return crud.create_city_weather(db=db, city_weather=city_weather)
|
||||
|
||||
# 获取城市天气记录
|
||||
@app.get("/city_weather/{city_id}", response_model=schemas.CityWeather)
|
||||
def read_city_weather(city_id: int, db: Session = Depends(get_db)):
|
||||
db_city_weather = crud.get_city_weather(db, city_id=city_id)
|
||||
if db_city_weather is None:
|
||||
raise HTTPException(status_code=404, detail="City not found")
|
||||
return db_city_weather
|
||||
|
||||
# 获取多个城市天气记录
|
||||
@app.get("/city_weather/", response_model=list[schemas.CityWeather])
|
||||
def read_city_weathers(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
|
||||
cities = crud.get_city_weathers(db, skip=skip, limit=limit)
|
||||
return cities
|
||||
|
||||
# 更新城市天气记录
|
||||
@app.put("/city_weather/{city_id}", response_model=schemas.CityWeather)
|
||||
def update_city_weather(city_id: int, city_weather: schemas.CityWeatherCreate, db: Session = Depends(get_db)):
|
||||
db_city = crud.update_city_weather(db=db, city_id=city_id, city_weather=city_weather)
|
||||
if db_city is None:
|
||||
raise HTTPException(status_code=404, detail="City not found")
|
||||
return db_city
|
||||
|
||||
# 删除城市天气记录
|
||||
@app.delete("/city_weather/{city_id}", response_model=schemas.CityWeather)
|
||||
def delete_city_weather(city_id: int, db: Session = Depends(get_db)):
|
||||
db_city = crud.delete_city_weather(db=db, city_id=city_id)
|
||||
if db_city is None:
|
||||
raise HTTPException(status_code=404, detail="City not found")
|
||||
return db_city
|
||||
Reference in New Issue
Block a user