%%python--bgfromflaskimportFlask,request,jsonifyfromflask_corsimportCORS# initialize a flask application (app)
app=Flask(__name__)CORS(app,supports_credentials=True,origins="*")# Allow all origins (*)
users=["advik","aashray","akhil","srijan"]@app.route("/",methods=["GET","POST"])defindex():ifrequest.method=="POST":# Get the user data from the form
user_data=request.form.get("user")ifuser_data:# Add the user to the list
users.append(user_data)return"""
<p>User added successfully!</p>
<br>
<a href="/users"><button>View Users</button></a>"""# Display the form to add a user
return"""
<form method="POST" action="/">
<label for="user">Add a user:</label>
<input type="text" id="user" name="user" required>
<input type="submit" value="Submit">
</form>
<br>
<a href="/users"><button>View Users</button></a>
"""@app.route("/users",methods=["GET"])defshow_users():# Return the list of users in JSON format
returnjsonify(users)if__name__=="__main__":# starts flask server on default port, http://127.0.0.1:5001
fromwerkzeug.servingimportrun_simplerun_simple("localhost",5001,app)
Tester Function
importrequests# Tester program to check any function that returns something
deftester(result,expected_result):try:# Validate the functionality
ifresult==expected_result:print("Users match! Everything is secure!")else:print("Users did not match!! Check immediately!")exceptExceptionase:# Handle exceptions gracefully
print(f"Test failed: An error occurred - {str(e)}")defget_users():req=requests.get("http://localhost:5001/users")userlst=req.textcharlist=["'",'"',"[","]","\n"]foriincharlist:userlst=userlst.replace(i,"")userlst=userlst.strip().split(",")req.close()returnuserlsttester(get_users(),["advik","aashray","akhil","srijan"])