Connect external Javascript with Flask - javascript

I am trying to get on-click coordinates of the screen. I have written a very basic code for the same. I am not able to connect my external js file with Flask.
When I run the .html file the code works perfectly fine. When I connect it through Flask, I tried including the Javascript in the HTML code itself and even that works. But when the Javascript part is connected via a .js file, the part in the .js file doesn't work.
I don't see any errors so it is getting difficult to debug.
Python script:
from flask import Flask, render_template, url_for
app = Flask(__name__)
#app.route('/')
#app.route('/button_click')
def button_click():
return render_template('button_click.html')
if __name__ == '__main__':
app.run(debug=True)
HTML code:
<html>
<head><title> Button Click </title></head>
<body>
<div id="example">
</div>
<script type="text/javascript" src="{{ url_for('static', filename='button_click.js') }}"> </script>
</body>
</html>
Javascript code:
function printMousePos(event) {
document.body.textContent =
"clientX: " + event.clientX +
" - clientY: " + event.clientY;
}
document.addEventListener("click", printMousePos);
Expected Result:
clientX: 93 - clientY: 113
Actual Result:
No change on screen

Related

Without reloading , dynamically update data in flask using ajax

I'm trying to update data in flask without reloading. Using ajax and javascript , I got the updated value in python , but it didn't make changes to html template which is rendered. Note that I also used Modular Apllications with Blue Print but I feel that is not the reason. Not to confuse with too much codes , I briefly changed and uploaded simple version. Please explain and point out my mistake or error why I'm not getting my expectation.
In app.py
from flask import render_template, request, Flask
app = Flask(__name__)
#app.route("/")
def home():
if request.args.get("field_changes"):
inps = request.args.get("field_changes")
else:
inps = 2
print(inps)
return render_template("home.html",num = inps)
if __name__ == "__main__":
app.run()
In home.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<input type="number" name="dynamic_inps" max="10" min="2" id="add_inps">
<h3>Your update value is : {{ num }}</h3>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.3.min.js">
inps = document.getElementById("add_inps")
$(document).on("input",'#add_inps',function(){
fields = $("#add_inps").val()
$.ajax({
type:"get",
url:"/calculations",
data : {field_changes:fields},
})
})
</script>
</body>
</html>
Although the value is changed in python script , it is not changed in html " Your update value is : ".

Flask returning 404 on static files regardless of pathing to the static folder

I am attempting to use flask to access a csv file and two json files which are being held in a folder named static. Even though i have mentioned the static folder in my code i am still having the following 404 issues with my map.js file running.
"GET / HTTP/1.1" 200
"GET /%7B%7B%20url_for('static',%20filename%20=%20'topo_E08000025.json')%20%7D%7D HTTP/1.1" 404
"GET /%7B%7B%20url_for('static',%20filename%20=%20'/static/sampleproperty3.csv')%20%7D%7D HTTP/1.1" 404
"GET /%7B%7B%20url_for('static',%20filename%20=%20'/static/sampleproperty3.csv')%20%7D%7D HTTP/1.1" 404
I have looked everywhere but can't seem to figure out what is going wrong.
I would like the code to pick up on the data in my static folder rather than returning a 404 error.
python code:
from flask import Flask,render_template, url_for
app = Flask(__name__)
#app.route('/')
def index():
return render_template('map.html')
if __name__== '__main__':
app.run(debug=True)
map html code:
<!doctype html>
<html>
<head>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://rawgit.com/nstrayer/slid3r/master/dist/slid3r.js"></script>
<script src = "https://unpkg.com/topojson#3.0.2/dist/topojson.js"></script>
<script src = "https://d3js.org/colorbrewer.v1.min.js"></script>
<script src = "{{ url_for('static', filename = 'mapFunctions.js') }}"></script>
<link rel="stylesheet" href= "{{ url_for('static', filename = 'map.css') }}">
</head>
<body style = "background-color:gray">
<script src = 'static/map.js' ></script>
</body>
map javascript code:
const svgHeight = 550;
const svgWidth = $(window).width(); // Uses Jquery to find the width of the window and set the svg width to that so it fills up the entire window
const svgPadding = 500;
let active = d3.select(null);
let filteredData ;
let radicusScale ;
let selected;
let originalTranslation ;
let locationLsoas = d3.json("topo_E08000025.json");
let locationWards = d3.json("topo_ward.json");
let properties = d3.csv("sampleproperty3.csv");
HTML files rendered using render_template shall be under templates folder and not static.
The files (CSS/JS) used by these HTML files, shall be under static folder.
I strongly recommend using an IDE like PyCharm and start with a blank flask project. That will give you a template to begin with.
For your reference, a sample hierarchy should be like this:
|static/
|---css/
|------style.css
|templates/
|---index.html
|app.py
My code for app.py:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def hello_world():
return render_template("index.html")
if __name__ == '__main__':
app.run()
My code for index.html (notice the way I access the css files):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}" type="text/css">
</head>
<body>
<h1>Header</h1>
</body>
</html>
Hope this helps. Good luck.

Flask + Jinja2 Script imports

I'm having an issue when using Flask and it's templates when importing Scripts and Stylesheets. I searched everywhere how to do it, and none of them solved my problem.
This is my project's structure:
https://i.gyazo.com/f746c58499cbbafa11b023eecb316b15.png
This is how I defined Flask's configuration:
app = Flask(__name__,
template_folder="../web/templates",
static_folder="../web/static",
static_url_path=''
)
And this is how i'm importing the scripts :
<script src={{ url_for('static', filename='/js/home.js') }}></script>
And this is the msg I get :
Falló la carga de con fuente “http://localhost:5000/js/home.js”.
(Basically says that it failed loading that script)
I already read the Quickstart guide from Flask.
I tried creating a "static" folder in the project's root and not setting anything on the config. Tried to change the static folder everywhere on my project.
Can anyone help me solve this? I'm new to Flask and Jinja, but have been searching the whole day and can't make it work.
NOTE : The path for the templates work, my templates work fine, except for .js and .css imports.
you need to remove starting '/' from <script src={{ url_for('static',filename='/js/home.js') }}.
so change it to <script src={{ url_for('static',filename='js/home.js') }}.
your project structure should look like this:
MyFlaskApp/templates/home.html
MyFlaskApp/static/js/home.js
MyFlaskApp/app.py
app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def home():
return render_template("home.html")
if __name__ == "__main__":
app.run()
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src={{ url_for('static',filename='js/home.js') }}> </script>
</body>
</html>
home.js
alert("hello");

d3 pie chart with flask server

I'm using the built-in flask server and I want to show an animated pie chart, like here:
http://codepen.io/tpalmer/pen/jqlFG
or
http://jsfiddle.net/thmain/xL48ru9k/1/
For simplicity, I use the latter one.
The python flask server code is:
from flask import Flask, render_template, request, flash
from forms import ContactForm
app = Flask(__name__)
app.secret_key = 'blah'
#app.route('/', methods = ['GET', 'POST'])
def test():
return render_template('test.html')
if __name__ == '__main__':
app.run(debug = True)
I did copy the javascript code provided on the webpage to the file static/script2.js
and the css code to static/css/style_d3.css
My HTML code is
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="//style_d3.css" type="text/css">
</head>
<body>
<p>test</p>
<div class="animated-ring">
<svg></svg>
</div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="//script2.js"></script>
</body>
</html>
I run the webpage through the flask server. But I get a webpage that just says "test", there's no chart.
What do I do wrong?
I'd really appreciate if someone could help me.
You only render the test.html at "/" path, the script2.js needs to be rendered too at "/script2.js".
Try this one liner at your project's root directory to host all files:
python -m SimpleHTTPServer
I think you need to set to a path your js file. In your app dir create a static folder then put your script2.js file and when you call this file at html use flask url_for() function
src="{{url_for('static', filename='script2.js'}}"

Separating html and JavaScript in Flask [duplicate]

This question already has answers here:
How to serve static files in Flask
(24 answers)
Closed 6 years ago.
Hey I've got the following problem:
I am building a little flask app, and usually i just stick with bootstrap and jinja templates to get what I want, but this time I needed a bit more customised version. In order to get a grip I started with a simple example of using custom js and flask to get the basic right. But lets go into detail:
Assume I have a simple flask web app called app.py located in my_app/ which looks like this
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(port=8080, debug=True)
and the corresponding index.html, which is located in my_app/templates, is simply
<!DOCTYPE html>
<html>
<body>
<p>Clicking here will make me dissapear</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<script>
$(document).ready(function() {
$("p").click(function(event){
$(this).hide();
});
});
</script>
</body>
</html>
then I see the expected result, that is, i can click on the paragraph to make it disappear.
BUT: I would like to put the javascript part into a main.js file under static/js/. like so:
$(document).ready(function() {
$("p").click(function(event){
$(this).hide();
});
});
and the index.html becomes:
<!DOCTYPE html>
<html>
<body>
<p>Clicking here will make me dissapear</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src='/js/main.js'></script>
</body>
</html>
Unfortunately nothing will happen. I have tried other ways of referencing the script file as well but until now nothing works. I have the impression im missing something really simple. Thanks in advance!
Simply invoke the url_for function within the template, referencing the special static endpoint so that the correct url to the desired target resource be created. As the desired target is the main.js file inside static/js, this would lead to the following:
<script type=text/javascript src="{{
url_for('static', filename='js/main.js')
}}"></script>
The rest of the quickstart guide contains additional useful information.

Categories