Advertisement
fkudinov

Python Framework: Flask

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