Advertisement
Guest User

Untitled

a guest
Dec 12th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.65 KB | None | 0 0
  1. @router.post("/", response_model=UserBook)
  2. async def add_book(book: Book, user: User = Depends(active_user)) -> UserBook:
  3.     async def validate(con, user_id: int, book: Book) -> None:
  4.         count = await con.fetchval(
  5.             "SELECT count(*) FROM user_book WHERE user_id=$1", user_id
  6.         )
  7.         if count > 1000:
  8.             raise HTTPException(
  9.                 400,
  10.                 "You already have too many books added, "
  11.                 "please contact our support",
  12.             )
  13.         if book.google_id and (
  14.             await con.fetchrow(
  15.                 "SELECT 1 FROM user_book WHERE user_id=$1 AND google_id=$2",
  16.                 user_id,
  17.                 book.google_id,
  18.             )
  19.         ):
  20.             raise HTTPException(400, "You have already added this book")
  21.  
  22.     async def insert_book(con, user_id: int, book: Book) -> UserBook:
  23.         data = book.dict()
  24.         data["user_id"] = user_id
  25.         sql, params = insert_sql("user_book", data)
  26.         data["id"] = await con.fetchval(sql, *params)
  27.         return UserBook(**data)
  28.  
  29.     async def update_head(con, user_id: int, book_id: int) -> None:
  30.         sql = """
  31.            UPDATE user_book
  32.            SET prev_id = $1
  33.            WHERE id != $1
  34.              AND user_id = $2
  35.              AND prev_id is NULL
  36.        """
  37.         await con.execute(sql, book_id, user_id)
  38.  
  39.     user_id = user["id"]
  40.     async with db.acquire() as con:
  41.         await validate(con, user_id, book)
  42.         async with con.transaction():
  43.             user_book = await insert_book(con, user_id, book)
  44.             await update_head(con, user_id, user_book.id)
  45.     return user_book
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement