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

  1. import os
  2. import json
  3. from api.modules import utils
  4. from flask import Flask, request
  5. from flask_restful import Resource, Api, abort
  6. app = Flask(__name__)
  7. api = Api(app)
  8. db_path = os.path.join(app.root_path, 'databases', 'ratings.json')
  9. user_db = os.path.join(app.root_path, 'databases', 'users.json')
  10. with open(db_path, 'r') as f:
  11. ratings = json.load(f)
  12. with open(user_db, 'r') as f:
  13. users = json.load(f)
  14. class Ratings(Resource):
  15. def get(self):
  16. rating = [
  17. {
  18. 'id' : v['id'],
  19. 'name': v['name'],
  20. 'desc': v['desc'],
  21. 'img' : v['img']
  22. }
  23. for v in ratings
  24. ]
  25. return rating
  26. def post(self):
  27. """
  28. Example POST Data:
  29. name=<rating_name>&
  30. desc=<rating_desc>& # OPTIONAL
  31. img=<rating_img>& # OPTIONAL
  32. """
  33. args = request.form
  34. rating_id = len(ratings) + 1
  35. rating = {
  36. 'id': rating_id,
  37. 'name': args['name'],
  38. 'desc': args.get('desc'),
  39. 'img' : args.get('img'),
  40. 'rates': []
  41. }
  42. ratings.append(rating)
  43. with open(db_path, 'w') as f:
  44. json.dump(ratings, f, indent=4)
  45. return rating
  46. class Rating(Resource):
  47. def get(self, rating_id):
  48. try:
  49. rating = ratings[rating_id - 1]
  50. del rating['rates']
  51. del rating['raters']
  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, 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)