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.

90 lines
2.7 KiB

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 post(self):
  17. """
  18. Example URL Query:
  19. latitude=<latitude>&
  20. longitude=<longitude>
  21. """
  22. latitude = float(request.form['latitude'])
  23. longitude = float(request.form['longitude'])
  24. ret_data = []
  25. for rating in ratings:
  26. diff = rating['location']['diff']
  27. rating_latitude = rating['location']['latitude']
  28. rating_longitude = rating['location']['longitude']
  29. if (rating_latitude - diff) < latitude < (rating_latitude + diff) and \
  30. (rating_longitude - diff) < longitude < (rating_longitude + diff):
  31. ret_data.append({
  32. 'id': rating['id'],
  33. 'name': rating['name'],
  34. 'desc': rating['desc'],
  35. 'img': rating['img']
  36. })
  37. return ret_data
  38. class Rating(Resource):
  39. def get(self, rating_id):
  40. try:
  41. rating = copy.deepcopy(ratings[rating_id - 1])
  42. del rating['rates']
  43. return rating
  44. except:
  45. abort(404, error="Rating {} doesn't exist".format(rating_id))
  46. class Rate(Resource):
  47. def post(self):
  48. """
  49. Example POST Data:
  50. rating_id=<rating_id>&
  51. score=<score>&
  52. note=<note>& # ADDITIONAL
  53. rater_id=<user_id>
  54. """
  55. if utils.find_by_id( users.values(), request.form[ 'rater_id' ] ):
  56. rating_id = int(request.form['rating_id'])
  57. score = int(request.form['score'])
  58. if 0 >= score >= 10:
  59. abort(500, 'Score should be between 0 and 10')
  60. note = request.form.get('note')
  61. ratings[rating_id - 1]['rates'].append({
  62. 'id': len(ratings[rating_id - 1]['rates']) + 1,
  63. 'rater': request.form['rater_id'],
  64. 'score': score,
  65. 'note': note
  66. })
  67. with open(db_path, 'w') as f:
  68. json.dump(ratings, f, indent=4)
  69. return {'message': 'Success'}
  70. return {'error': 'User doesn\'t exists'}
  71. if __name__ == '__main__':
  72. api.add_resource(Ratings, '/ratings', '/ratings/')
  73. api.add_resource(Rating, '/ratings/<int:rating_id>', '/ratings/<int:rating_id>/')
  74. api.add_resource(Rate, '/rate', '/rate/')
  75. app.run(host='0.0.0.0', port=5000)