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.

94 lines
2.4 KiB

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