Advertisement
VssA

Untitled

May 12th, 2023
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.44 KB | None | 0 0
  1. from flask import Flask, jsonify, abort, request
  2. from datetime import datetime, timedelta
  3. from sqlalchemy import create_engine, Column, Integer, String, Date, Float, Boolean, DateTime
  4. from sqlalchemy.ext.hybrid import hybrid_property
  5. from sqlalchemy.orm import sessionmaker, declarative_base
  6. from sqlalchemy.exc import NoResultFound, MultipleResultsFound
  7.  
  8. app = Flask(__name__)
  9. Base = declarative_base()
  10. engine = create_engine('sqlite:///hw.db')
  11. Session = sessionmaker(bind=engine)
  12. session = Session()
  13.  
  14.  
  15. class Books(Base):
  16.     __tablename__ = 'books'
  17.     id = Column(Integer, primary_key=True)
  18.     name = Column(String(100), nullable=False)
  19.     count = Column(Integer, default=1)
  20.     release_date = Column(DateTime, nullable=False)
  21.     author_id = Column(Integer, nullable=False)
  22.  
  23.     def to_json(self):
  24.         return {c.name: getattr(self, c.name) for c in self.__table__.columns}
  25.  
  26.  
  27. class Author(Base):
  28.     __tablename__ = 'authors'
  29.     id = Column(Integer, primary_key=True)
  30.     name = Column(String(50), nullable=False)
  31.     surname = Column(String(50), nullable=False)
  32.  
  33.     def to_json(self):
  34.         return {c.name: getattr(self, c.name) for c in self.__table__.columns}
  35.  
  36.  
  37. class Students(Base):
  38.     __tablename__ = 'students'
  39.     id = Column(Integer, primary_key=True)
  40.     name = Column(String(50), nullable=False)
  41.     surname = Column(String(50), nullable=False)
  42.     phone = Column(String(11))
  43.     email = Column(String(50))
  44.     average_score = Column(Float, nullable=False)
  45.     scholarship = Column(Boolean, default=False)
  46.  
  47.     def to_json(self):
  48.         return {c.name: getattr(self, c.name) for c in self.__table__.columns}
  49.  
  50.     @classmethod
  51.     def get_scholarship_students(cls):
  52.         return session.query(Students).filter(Students.scholarship == True).all()
  53.  
  54.     @classmethod
  55.     def get_students_with_higher_score(cls, score):
  56.         return session.query(Students).filter(Students.average_score > score).all()
  57.  
  58.  
  59. class ReceivingBook(Base):
  60.     __tablename__ = 'receiving_books'
  61.     id = Column(Integer, primary_key=True)
  62.     book_id = Column(Integer, nullable=False)
  63.     student_id = Column(Integer, nullable=False)
  64.     date_of_issue = Column(DateTime, nullable=False)
  65.     date_of_return = Column(DateTime)
  66.  
  67.     def to_json(self):
  68.         return {c.name: getattr(self, c.name) for c in self.__table__.columns}
  69.  
  70.     @hybrid_property
  71.     def count_date_with_book(self):
  72.         if self.date_of_return:
  73.             return (self.date_of_return - self.date_of_issue).days
  74.         else:
  75.             return (datetime.now() - self.date_of_issue).days
  76.  
  77.  
  78. @app.before_request
  79. def before_request_func():
  80.     Base.metadata.create_all(engine)
  81.  
  82.  
  83. @app.route('/books', methods=['GET'])
  84. def get_books():
  85.     books = session.query(Books).all()
  86.     books_list = []
  87.     for book in books:
  88.         books_list.append(book.to_json())
  89.     return jsonify(books_list=books_list), 200
  90.  
  91.  
  92. @app.route('/debtors', methods=['GET'])
  93. def get_debtors():
  94.     debtors = session.query(ReceivingBook).filter(ReceivingBook.date_of_return == None).all()
  95.     debtors_list = []
  96.     for debtor in debtors:
  97.         if debtor.count_date_with_book > 14:
  98.             debtors_list.append(debtor.to_json())
  99.     return jsonify(debtors_list=debtors_list), 200
  100.  
  101.  
  102. @app.route('/issue_book', methods=['POST'])
  103. def issue_book():
  104.     book_id = request.form.get('book_id', type=int)
  105.     student_id = request.form.get('student_id', type=int)
  106.     new_issue = ReceivingBook(book_id=book_id,
  107.                                 student_id=student_id,
  108.                                 date_of_issue=datetime.now())
  109.     session.add(new_issue)
  110.     session.commit()
  111.     return f"Книга с id {book_id} выдана", 201
  112.  
  113.  
  114. @app.route('/pass_book', methods=['POST'])
  115. def pass_book():
  116.     try:
  117.         book_id = request.form.get('book_id', type=int)
  118.         student_id = request.form.get('student_id', type=int)
  119.         book = session.query(ReceivingBook).filter(ReceivingBook.book_id == book_id, ReceivingBook.student_id == student_id).one()
  120.         book.date_of_return = datetime.now()
  121.         session.commit()
  122.         return f"Книга с id {book_id} сдана"
  123.     except NoResultFound:
  124.         return 'Такой связки book_id и student_id не существует'
  125.     except MultipleResultsFound:
  126.         return 'С такой связкой book_id и student_id найдено несколько записей'
  127.  
  128.  
  129. if __name__ == "__main__":
  130.     app.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement