Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from flask import Flask, request, jsonify
- app = Flask(__name__)
- current_term = 0
- voted_for = None
- log = []
- @app.route('/requestVote', methods=['POST'])
- def request_vote():
- try:
- global current_term, voted_for
- data = request.get_json()
- if data["term"] > current_term:
- current_term = data["term"]
- voted_for = None
- if voted_for is None or voted_for == data["candidateId"]:
- last_log_index = len(log) - 1
- last_log_term = log[-1]["term"] if log else 0
- if data["lastLogTerm"] > last_log_term or (data["lastLogTerm"] == last_log_term and data["lastLogIndex"] >= last_log_index):
- voted_for = data["candidateId"]
- response = {
- "term": current_term,
- "voteGranted": True
- }
- else:
- response = {
- "term": current_term,
- "voteGranted": False
- }
- else:
- response = {
- "term": current_term,
- "voteGranted": False
- }
- return jsonify(response), 200
- except:
- return jsonify({"message": "Error processing request"}), 400
- @app.route('/appendEntries', methods=['POST'])
- def append_entries():
- try:
- global current_term, log
- data = request.get_json()
- if data["term"] >= current_term:
- current_term = data["term"]
- if not log or data["prevLogIndex"] == len(log) - 1 and log[-1]["term"] == data["prevLogTerm"]:
- log = log[:data["prevLogIndex"] + 1] + data["entries"]
- response = {
- "term": current_term,
- "success": True
- }
- else:
- response = {
- "term": current_term,
- "success": False
- }
- else:
- response = {
- "term": current_term,
- "success": False
- }
- return jsonify(response), 200
- except:
- return jsonify({"message": "Error processing request"}), 400
- if __name__ == '__main__':
- app.run(debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement