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.

121 lines
3.3 KiB

6 years ago
  1. import os
  2. import copy
  3. import json
  4. from modules import utils
  5. from flask import Flask, request,Response
  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', 'votings.json')
  10. user_db = os.path.join(app.root_path, 'databases', 'users.json')
  11. with open(db_path, 'r') as f:
  12. votings = json.load(f)
  13. with open(user_db, 'r') as f:
  14. users = json.load(f)
  15. class Votings(Resource):
  16. def get(self):
  17. voting = [
  18. {
  19. 'id' : v['id'],
  20. 'name': v['name'],
  21. 'desc': v['desc'],
  22. 'img' : v['img']
  23. }
  24. for v in votings
  25. ]
  26. resp = Response(json.dumps(voting))
  27. resp.headers['Access-Control-Allow-Origin'] = '*'
  28. return resp
  29. def post(self):
  30. """
  31. Example POST Data:
  32. name=<voting_name>&
  33. desc=<voting_desc>& # OPTIONAL
  34. img=<voting_img>& # OPTIONAL
  35. votes=[
  36. {
  37. "name": "<vote_name>",
  38. "desc": "<vote_desc>" # OPTIONAL
  39. },
  40. (...)
  41. ]
  42. """
  43. args = request.form
  44. voting_id = len(votings) + 1
  45. voting = {
  46. 'id': voting_id,
  47. 'name': args['name'],
  48. 'desc': args.get('desc'),
  49. 'img' : args.get('img'),
  50. 'voters': [],
  51. 'votes': [
  52. {
  53. 'id' : k + 1,
  54. 'name': vote['name'],
  55. 'desc': vote.get('desc'),
  56. 'votes': 0
  57. }
  58. for k, vote in enumerate(json.loads(args['votes']))
  59. ]
  60. }
  61. votings.append(voting)
  62. with open(db_path, 'w') as f:
  63. json.dump(votings, f, indent=2)
  64. return {'message': 'Success'}
  65. class Voting(Resource):
  66. def get(self, voting_id):
  67. try:
  68. voting = copy.deepcopy(votings[voting_id - 1])
  69. del voting['voters']
  70. resp = Response(json.dumps(voting))
  71. resp.headers['Access-Control-Allow-Origin'] = '*'
  72. return resp
  73. except:
  74. abort(404, error="Voting {} doesn't exist".format(voting_id))
  75. class Vote(Resource):
  76. def post(self):
  77. """
  78. Example URL Query:
  79. /vote?voting_id=<voting_id>&vote_id=<vote_id>&voter_id=<user_id>
  80. """
  81. voter_id = request.form['voter_id']
  82. voting_id = int(request.form['voting_id']) - 1
  83. if utils.find_by_id(users.values(), voter_id):
  84. if voter_id not in votings[voting_id]['voters']:
  85. vote_id = int(request.form['vote_id'])
  86. votings[voting_id]['votes'][str(vote_id)]['votes'] += 1
  87. votings[voting_id]['voters'].append(voter_id)
  88. with open(db_path, 'w') as f:
  89. json.dump(votings, f, indent=2)
  90. return {'message': 'Success'}
  91. return {'error': 'Already voted'}
  92. return {'error': 'User doesn\'t exists'}
  93. if __name__ == '__main__':
  94. api.add_resource(Votings, '/votings', '/votings/')
  95. api.add_resource(Voting, '/votings/<int:voting_id>', '/votings/<int:voting_id>/')
  96. api.add_resource(Vote, '/vote', '/vote/')
  97. app.run(host='0.0.0.0', port=5000)