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.

81 lines
1.7 KiB

  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')
  10. parser.add_argument('desc')
  11. parser.add_argument('img')
  12. parser.add_argument('votes')
  13. with open(os.path.join(app.root_path, 'votings.json'), 'r') as f:
  14. votings_json = json.load(f)
  15. votings = {
  16. v['id']: v
  17. for v in votings_json
  18. }
  19. class Votings(Resource):
  20. def get(self):
  21. voting = [
  22. {
  23. 'id' : v['id'],
  24. 'name': v['name'],
  25. 'desc': v['desc'],
  26. 'img' : v['img']
  27. }
  28. for k, v in votings.items()
  29. ]
  30. return voting
  31. def post(self):
  32. args = parser.parse_args()
  33. voting_id = max(votings.keys()) + 1
  34. voting = {
  35. 'id': voting_id,
  36. 'name': args['name'],
  37. 'desc': args['desc'],
  38. 'img' : args['img'],
  39. 'votes': [
  40. {
  41. 'id': k,
  42. 'name': vote['name'],
  43. 'desc': vote['desc'],
  44. 'votes': 0
  45. }
  46. for k, vote in enumerate(json.loads(args['votes']))
  47. ]
  48. }
  49. votings[voting_id] = voting
  50. votings_json.append(voting)
  51. with open(os.path.join(app.root_path, 'votings.json'), 'w') as f:
  52. json.dump(votings_json, f, indent=4)
  53. return voting
  54. class Voting(Resource):
  55. def get(self, voting_id):
  56. try:
  57. return votings[voting_id]
  58. except:
  59. abort(404, error="Voting {} doesn't exist".format(voting_id))
  60. api.add_resource(Votings, '/votings', '/votings/')
  61. api.add_resource(Voting, '/votings/<int:voting_id>')
  62. @app.route('/img/<path:path>')
  63. def send_img(path):
  64. return send_from_directory('images', path)
  65. if __name__ == '__main__':
  66. app.run(host='0.0.0.0', port=5000, debug=True)