Advertisement
varun1729

Untitled

Apr 15th, 2023
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. from flask import Flask, request, jsonify
  2.  
  3. app = Flask(__name__)
  4.  
  5. current_term = 0
  6. voted_for = None
  7. log = []
  8.  
  9. @app.route('/requestVote', methods=['POST'])
  10. def request_vote():
  11. try:
  12. global current_term, voted_for
  13. data = request.get_json()
  14. if data["term"] > current_term:
  15. current_term = data["term"]
  16. voted_for = None
  17. if voted_for is None or voted_for == data["candidateId"]:
  18. last_log_index = len(log) - 1
  19. last_log_term = log[-1]["term"] if log else 0
  20. if data["lastLogTerm"] > last_log_term or (data["lastLogTerm"] == last_log_term and data["lastLogIndex"] >= last_log_index):
  21. voted_for = data["candidateId"]
  22. response = {
  23. "term": current_term,
  24. "voteGranted": True
  25. }
  26. else:
  27. response = {
  28. "term": current_term,
  29. "voteGranted": False
  30. }
  31. else:
  32. response = {
  33. "term": current_term,
  34. "voteGranted": False
  35. }
  36. return jsonify(response), 200
  37. except:
  38. return jsonify({"message": "Error processing request"}), 400
  39.  
  40. @app.route('/appendEntries', methods=['POST'])
  41. def append_entries():
  42. try:
  43. global current_term, log
  44. data = request.get_json()
  45. if data["term"] >= current_term:
  46. current_term = data["term"]
  47. if not log or data["prevLogIndex"] == len(log) - 1 and log[-1]["term"] == data["prevLogTerm"]:
  48. log = log[:data["prevLogIndex"] + 1] + data["entries"]
  49. response = {
  50. "term": current_term,
  51. "success": True
  52. }
  53. else:
  54. response = {
  55. "term": current_term,
  56. "success": False
  57. }
  58. else:
  59. response = {
  60. "term": current_term,
  61. "success": False
  62. }
  63. return jsonify(response), 200
  64. except:
  65. return jsonify({"message": "Error processing request"}), 400
  66.  
  67. if __name__ == '__main__':
  68. app.run(debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement