Python Forum
[Flask]Trow away JS function and use a Python function - Printable Version

+- Python Forum (
+-- Forum: General (
+--- Forum: Tutorials (
+---- Forum: Web Tutorials (
+---- Thread: [Flask]Trow away JS function and use a Python function (/thread-444.html)

[Flask]Trow away JS function and use a Python function - snippsat - Oct-14-2016

So will trow away a JavaScript function and use a Python function to do the same.
JavaScript work on client side and Python dos not(not gone talk about Bryton ect they all have there problems),
so need a way to transfer from server to client so it works the same way.

First look at an run Change color
Now all is on client side(browser),and advantage that JavaScript has and why is so popular.

Python code that dos the same.
>>> from random import randint
>>> "#{:06x}".format(randint(0,0xFFFFFF)).upper()
>>> "#{:06x}".format(randint(0,0xFFFFFF)).upper()
The approach is to use Ajax,all transport from server(Python code) to client(Browser) is Json.

Folder and files:
from flask import Flask, render_template, jsonify
from random import randint

app = Flask(__name__)
def hex_color():
   return render_template("index.html")

def hex_text():
   '''Return hex text in in json format'''
   d = {}
   d['hex'] = "#{:06x}".format(randint(0,0xFFFFFF)).upper()
   return jsonify(d)

if __name__ == '__main__':
<!DOCTYPE html>
   <meta charset="UTF-8">
   <link rel=stylesheet type=text/css href="{{ url_for('static', filename='css/style.css') }}">
   <script src=''></script>
   <script type=text/javascript src="{{url_for('static', filename='js/hex_call.js') }}"></script>
   <title>Random hex color generator</title>
   <div class="hex">
     <h1>Hex Color Code</h1>
     <button>Change color</button>
$(document).ready(function() {
 $("button").click(function() {
   $.getJSON('/python_func', function(dat) {
     $("body").css({background: dat['hex']}); 
Copy from Pen.

Now to run code and it should look and work exactly like code from CodePen.
Cd into color change folder then python
Now in browser

If look at image under,
now we see that stuff get transferred from server to client.
XMLHttpRequest is the transfer between server and client that Ajax use.

RE: Trow away JS function and use a Python function(Flask) - metulburr - Oct-14-2016

I plan on, in the future, digging into keep these tutorials up  :)