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.

85 lines
2.0 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. import os
  2. import ssl
  3. import json
  4. from flask import Flask, send_from_directory
  5. from flask_restful import Resource, Api, abort, reqparse
  6. app = Flask(__name__)
  7. api = Api(app)
  8. parser = reqparse.RequestParser()
  9. parser.add_argument('name', required=True)
  10. parser.add_argument('desc')
  11. parser.add_argument('img')
  12. parser.add_argument('votes', required=True)
  13. with open(os.path.join(app.root_path, 'votings.json'), 'r') as f:
  14. votings = 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. return voting
  27. def post(self):
  28. args = parser.parse_args()
  29. voting_id = max(len(votings)) + 1
  30. voting = {
  31. 'id': voting_id,
  32. 'name': args['name'],
  33. 'desc': args['desc'],
  34. 'img' : args['img'],
  35. 'votes': [
  36. {
  37. 'id': k,
  38. 'name': vote['name'],
  39. 'desc': vote['desc'],
  40. 'votes': 0
  41. }
  42. for k, vote in enumerate(json.loads(args['votes']))
  43. ]
  44. }
  45. votings.append(voting)
  46. with open(os.path.join(app.root_path, 'votings.json'), 'w') as f:
  47. json.dump(votings, f, indent=4)
  48. return voting
  49. class Voting(Resource):
  50. def get(self, voting_id):
  51. try:
  52. return votings[voting_id - 1]
  53. except:
  54. abort(404, error="Voting {} doesn't exist".format(voting_id))
  55. class Vote(Resource):
  56. def get(self, voting_id, vote_id):
  57. votings[voting_id - 1]['votes'][vote_id - 1]['votes'] += 1
  58. with open(os.path.join(app.root_path, 'votings.json'), 'w') as f:
  59. json.dump(votings, f, indent=4)
  60. return votings[voting_id - 1]
  61. api.add_resource(Votings, '/votings', '/votings/')
  62. api.add_resource(Voting, '/votings/<int:voting_id>')
  63. api.add_resource(Vote, '/vote/<int:voting_id>/<int:vote_id>')
  64. @app.route('/img/<path:path>')
  65. def send_img(path):
  66. return send_from_directory('images', path)
  67. if __name__ == '__main__':
  68. app.run(host='0.0.0.0', port=5000, debug=True)