You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.3 KiB

  1. import os
  2. import json
  3. from flask import Flask, request
  4. from flask_restful import Resource, Api, abort
  5. app = Flask(__name__)
  6. api = Api(app)
  7. with open(os.path.join(app.root_path, 'ratings.json'), 'r') as f:
  8. ratings = json.load(f)
  9. class Ratings(Resource):
  10. def get(self):
  11. rating = [
  12. {
  13. 'id' : v['id'],
  14. 'name': v['name'],
  15. 'desc': v['desc'],
  16. 'img' : v['img']
  17. }
  18. for v in ratings
  19. ]
  20. return rating
  21. def post(self):
  22. """
  23. Example POST Data:
  24. name=<rating_name>&
  25. desc=<rating_desc>& # OPTIONAL
  26. img=<rating_img>& # OPTIONAL
  27. """
  28. args = request.form
  29. rating_id = len(ratings) + 1
  30. rating = {
  31. 'id': rating_id,
  32. 'name': args['name'],
  33. 'desc': args.get('desc'),
  34. 'img' : args.get('img'),
  35. 'rates': []
  36. }
  37. ratings.append(rating)
  38. with open(os.path.join(app.root_path, 'ratings.json'), 'w') as f:
  39. json.dump(ratings, f, indent=4)
  40. return rating
  41. class Rating(Resource):
  42. def get(self, rating_id):
  43. try:
  44. return ratings[rating_id - 1]
  45. except:
  46. abort(404, error="Rating {} doesn't exist".format(rating_id))
  47. class Rate(Resource):
  48. def get(self):
  49. """
  50. Example URL Query:
  51. /rate?
  52. rating_id=<rating_id>>&
  53. score=<score>&
  54. note=<note> # ADDITIONAL
  55. """
  56. rating_id = int(request.args['rating_id'])
  57. score = int(request.args['score'])
  58. if 0 >= score >= 10:
  59. abort(500, 'Score should be between 0 and 10')
  60. note = request.args.get('note')
  61. ratings[rating_id - 1]['rates'].append({
  62. 'id': len(ratings[rating_id - 1]['rates']) + 1,
  63. 'score': score,
  64. 'note': note
  65. })
  66. with open(os.path.join(app.root_path, 'ratings.json'), 'w') as f:
  67. json.dump(ratings, f, indent=4)
  68. return ratings[rating_id - 1]
  69. if __name__ == '__main__':
  70. api.add_resource(Ratings, '/ratings', '/ratings/')
  71. api.add_resource(Rating, '/ratings/<int:rating_id>', '/ratings/<int:rating_id>/')
  72. api.add_resource(Rate, '/rate', '/rate/')
  73. app.run(host='0.0.0.0', port=5000)