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.

100 lines
2.7 KiB

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