I'm going to answer this question exactly, although be aware that setting page colour can be done entirely on the frontend, and probably shouldn't require a request to the server to get the actual colour.
This answer perfectly explains now to do this in Javascript alone, and avoid that request to the server every time someone changes the color.
If you did want to make this request to the server (for learning purposes, say) you could do. Let's modify your flask route slightly to account for a few things:
@app.route('/changeColor', methods=['GET'])
def change_color():
colors = ['red', 'black', 'purple', 'yellow', 'white', 'pink', 'grey', 'green']
i = random.randint(0, len(colors)-1)
rand_col = colors[i]
return {'color': rand_col}, 200
We have:
- Changed the request method to GET.
- Changed the randomization line, to account for the length of the
colors
list. Adding more items to the list will automatically include them all in the random selection now.
- Returned a dictionary with the key
'color'
and value of rand_col
. This dictionary will automatically be turned into JSON by flask. Also we have added the 200
response code.
@app.route('/')
def index():
return render_template('index.html')
- Here we've added a separate route to render the frontend template, users hit this page, and the
change_color
route specifically deals with returning a colour.
Now for the template. I'm actually using jquery for this which is included from cloudflare's CDN along with an SNI tag for security reasons.
We create a button in the HTML, with the class changecolor
then use a Jquery selector to call the AJAX functon when the button is clicked.
This is the contents of templates/index.html
:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
</head>
<body>
<p>I am the page text.</p>
<button class="changecolor" type="button">Change my Colour</button>
<script type='text/javascript'>
$(function() {
// This catches the button click
$('.changecolor').click(function() {
// This does the ajax call to the server (GET Request)
$.ajax({
type: 'GET',
// Dynamically set the URL for the python `change_color`
// function.
url: '{{ url_for("change_color") }}',
success: function(data) {
// Actually set the page color, if the request is suecessful
document.body.style.backgroundColor = data['color'];
}
});
});
});
</script>
</body>
</html>
- Notice that instead of providing the URL as
/changeColor
we use Jinja2's template functionality, this time the url_for
function to dynamically set the corresponding URL for the change_color
function in the Python code. (more info)
Now on your front-end you should be able to click the button and change the page color:
