Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 [Flask]Trow away JS function and use a Python function
#1
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()
'#750EDA'
>>> "#{:06x}".format(randint(0,0xFFFFFF)).upper()
'#92B1D9'
The approach is to use Ajax,all transport from server(Python code) to client(Browser) is Json.


Folder and files:
color_change\ 
app.py
   tempaltes\
   index.html
   static\
       css\
       style.css
       js\
       hex_call.js
app.py
from flask import Flask, render_template, jsonify
from random import randint

app = Flask(__name__)
@app.route('/')
def hex_color():
   return render_template("index.html")

@app.route('/python_func')
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__':
   app.run(debug=True)
index.html
<!DOCTYPE html>
<html>
 <head>
   <meta charset="UTF-8">
   <link rel=stylesheet type=text/css href="{{ url_for('static', filename='css/style.css') }}">
   <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
   <script type=text/javascript src="{{url_for('static', filename='js/hex_call.js') }}"></script>
   <title>Random hex color generator</title>
 </head>
 <body>
   <div class="hex">
     <h1>Hex Color Code</h1>
   </div>
   <div>
     <button>Change color</button>
   </div>
 </body>
</html>
hex_call.js
$(document).ready(function() {
 $("button").click(function() {
   $.getJSON('/python_func', function(dat) {
     $("body").css({background: dat['hex']}); 
     $("h1").text(dat['hex']);       
   });
 });
});
style.css
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 app.py
Now in browser http://127.0.0.1:5000/

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.
metulburr likes this post
Quote
#2
I plan on, in the future, digging into flask...so keep these tutorials up  :)
Quote

Top Page

Forum Jump:


Users browsing this thread: 1 Guest(s)