Advertisement
fkudinov

Python Framework: Sanic

Nov 18th, 2024 (edited)
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.03 KB | Source Code | 0 0
  1. # file name:        main.py
  2. # install:          pip install sanic[ext]
  3. # run server:       sanic main
  4. # host, port:       http://127.0.0.1:8000
  5.  
  6. from dataclasses import dataclass, asdict
  7.  
  8. from sanic import Sanic, json
  9. from sanic_ext import validate
  10.  
  11.  
  12. app = Sanic(__name__)
  13.  
  14. # in memory db
  15. BOOKS_DB = [{"book_id": 0, "book_name": "Hi there"},
  16.             {"book_id": 1, "book_name": "How are you?"}]
  17.  
  18.  
  19. @app.route("/book")
  20. async def show_books(request):
  21.     count = request.args.get("count")
  22.     count = int(count) if count else None
  23.     return json({"books": BOOKS_DB[:count]})
  24.  
  25.  
  26. @app.route('/book/<book_id:int>', methods=["GET"])
  27. async def show_book(request, book_id):
  28.     return json({book["book_id"]: book for book in BOOKS_DB}[book_id])
  29.  
  30.  
  31. @dataclass
  32. class Book:
  33.     book_name: str
  34.     book_id: int | None = None
  35.  
  36.  
  37. @app.post('/book')
  38. @validate(json=Book)
  39. async def create_book(request, body: Book):
  40.     data = asdict(body)
  41.     data["book_id"] = int(len(BOOKS_DB))
  42.     BOOKS_DB.append(data)
  43.     return json(data)
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement