Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

67 lines
2.0KB

  1. # @name: api.py
  2. # @creation_date: 2023-01-12
  3. # @license: The MIT License <https://opensource.org/licenses/MIT>
  4. # @author: Simon Bowie <ad7588@coventry.ac.uk>
  5. # @purpose: Exposes database data as exportable JSON for a RESTful API
  6. # @acknowledgements:
  7. # https://auth0.com/blog/developing-restful-apis-with-python-and-flask/
  8. # https://stackoverflow.com/questions/59721478/serializing-sqlalchemy-with-marshmallow
  9. from flask import Blueprint, render_template, request, flash, redirect, url_for, jsonify
  10. from flask_login import login_required, current_user
  11. from .models import Resource, User
  12. from .schemas import UserSchema, ToolSchema, PracticeSchema, BookSchema
  13. api = Blueprint('api', __name__)
  14. # function to get different types from the Resource database table
  15. def get_resource_json(type):
  16. resources = Resource.query.filter_by(type=type)
  17. if (type=='tool'):
  18. resources_schema = ToolSchema(many=True)
  19. elif (type=='practice'):
  20. resources_schema = PracticeSchema(many=True)
  21. elif (type=='book'):
  22. resources_schema = BookSchema(many=True)
  23. result = resources_schema.dump(resources)
  24. # return all rows as a JSON array of objects
  25. result = jsonify(result)
  26. return result
  27. # route for api page
  28. @api.route('/api')
  29. def api_page():
  30. return render_template('api.html')
  31. # route for exporting all users in database
  32. @api.route('/api/users')
  33. @login_required
  34. def get_users():
  35. users = User.query.all()
  36. users_schema = UserSchema(many=True)
  37. result = users_schema.dump(users)
  38. # return all rows as a JSON array of objects
  39. return jsonify(result)
  40. # route for exporting all tools in database
  41. @api.route('/api/tools')
  42. def get_tools():
  43. type = 'tool'
  44. output = get_resource_json(type)
  45. return output
  46. # route for exporting all practices in database
  47. @api.route('/api/practices')
  48. def get_practices():
  49. type = 'practice'
  50. output = get_resource_json(type)
  51. return output
  52. # route for exporting all books in database
  53. @api.route('/api/books')
  54. def get_books():
  55. type = 'book'
  56. output = get_resource_json(type)
  57. return output