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.

63 lines
1.6 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, 'users.json'), 'r') as f:
  8. users = json.load(f)
  9. class Users(Resource):
  10. def get(self):
  11. user = [
  12. {
  13. 'id' : v['id'],
  14. 'username': v['username']
  15. }
  16. for v in users
  17. ]
  18. return user
  19. def post(self):
  20. """
  21. Example POST Data:
  22. username=<username>&
  23. realname=<realname>& # OPTIONAL
  24. avatar=<avatar_url>& # OPTIONAL
  25. """
  26. args = request.form
  27. user_id = len(users) + 1
  28. user = {
  29. 'id': user_id,
  30. 'username': args['username'],
  31. 'realname': args.get('realname'),
  32. 'avatar' : args.get('avatar'),
  33. 'stats': {
  34. 'bus_usage_week': 0,
  35. 'bus_usage_month': 0,
  36. 'bus_usage_year': 0
  37. },
  38. 'points': 0
  39. }
  40. users.append(user)
  41. with open(os.path.join(app.root_path, 'users.json'), 'w') as f:
  42. json.dump(users, f, indent=4)
  43. return user
  44. class User(Resource):
  45. def get(self, user_id):
  46. try:
  47. return users[user_id - 1]
  48. except:
  49. abort(404, error="User {} doesn't exist".format(voting_id))
  50. if __name__ == '__main__':
  51. api.add_resource(Users, '/users', '/users/')
  52. api.add_resource(User, '/users/<int:user_id>', '/users/<int:user_id>/')
  53. app.run(host='0.0.0.0', port=5000)