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.

101 lines
2.7 KiB

  1. import os
  2. import json
  3. from flask import Flask, request
  4. from flask_restful import Resource, Api, abort
  5. app = Flask(__name__)
  6. api = Api(app)
  7. with open(os.path.join(app.root_path, 'votings.json'), 'r') as f:
  8. votings = json.load(f)
  9. class Votings(Resource):
  10. def get(self):
  11. voting = [
  12. {
  13. 'id' : v['id'],
  14. 'name': v['name'],
  15. 'desc': v['desc'],
  16. 'img' : v['img']
  17. }
  18. for v in votings
  19. ]
  20. return voting
  21. def post(self):
  22. """
  23. Example POST Data:
  24. name=<voting_name>&
  25. desc=<voting_desc>& # OPTIONAL
  26. img=<voting_img>& # OPTIONAL
  27. votes=[
  28. {
  29. "name": "<vote_name>",
  30. "desc": "<vote_desc>" # OPTIONAL
  31. },
  32. (...)
  33. ]
  34. """
  35. args = request.form
  36. voting_id = len(votings) + 1
  37. voting = {
  38. 'id': voting_id,
  39. 'name': args['name'],
  40. 'desc': args.get('desc'),
  41. 'img' : args.get('img'),
  42. 'votes': [
  43. {
  44. 'id' : k + 1,
  45. 'name': vote['name'],
  46. 'desc': vote.get('desc'),
  47. 'votes': 0
  48. }
  49. for k, vote in enumerate(json.loads(args['votes']))
  50. ]
  51. }
  52. votings.append(voting)
  53. with open(os.path.join(app.root_path, 'votings.json'), 'w') as f:
  54. json.dump(votings, f, indent=4)
  55. return voting
  56. class Voting(Resource):
  57. def get(self, voting_id):
  58. try:
  59. return votings[voting_id - 1]
  60. except:
  61. abort(404, error="Voting {} doesn't exist".format(voting_id))
  62. class Vote(Resource):
  63. def get(self):
  64. """
  65. Example URL Query:
  66. /vote?voting_id=<voting_id>&vote_id=<vote_id>&voter_id=<voter_id>
  67. """
  68. voting_id = int(request.args['voting_id'])
  69. vote_id = int(request.args['vote_id'])
  70. voter_id = int(request.args['voter_id'])
  71. error = False
  72. for i in range(votings[voting_id]["votes"]):
  73. if(voter_id in votings[voting_id]["votes"][i]["votes"]):
  74. error = True
  75. if error:
  76. return "An error occured"
  77. votings[voting_id]["votes"][vote_id]["votes"].append(voter_id)
  78. with open(os.path.join(app.root_path, 'votings.json'), 'w') as f:
  79. json.dump(votings, f, indent=4)
  80. return votings[voting_id - 1]
  81. if __name__ == '__main__':
  82. api.add_resource(Votings, '/votings', '/votings/')
  83. api.add_resource(Voting, '/votings/<int:voting_id>', '/votings/<int:voting_id>/')
  84. api.add_resource(Vote, '/vote', '/vote/')
  85. app.run(host='0.0.0.0', port=5000)