I want to render json file to html script part. In the tornado part, No1 is sendering json data to html. And, No2 part is received the json data from No1. However this code is not working. I found that html script doesn't allow the form of {{ }}. How I send the json data to part of html ?
[ python - tornado part ]
import tornado.web
import tornado.httpserver
import tornado.ioloop
import os.path
from tornado.options import define, options
define("port", default=3000, help="run on the given port", type=int)
class Application(tornado.web.Application):
def __init__(self):
base_dir = os.path.dirname(__file__)
settings = {
}
tornado.web.Application.__init__(self, [
tornado.web.url(r"/", MainHandler, name="main"),
], **settings)
class MainHandler(tornado.web.RequestHandler):
def get(self):
data = {"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}
self.render("index.html", data=data) #No1
def main():
tornado.options.parse_command_line()
Application().listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
[ html part ]
<!DOCTYPE html>
<html>
<body>
<h2>JSON Object Creation in JavaScript</h2>
<p id="demo"></p>
<script>
/* var text = '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}'; */
var text = '{{data}}'; /*No2*/
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.name + "<br>" +
obj.street + "<br>" +
obj.phone;
</script>
</body>
</html>
The {{ }} in your index.html template will be autoescaped for html. You want raw output because in this case you're outputting javascript rather than html. You also want to make sure you're actually letting python convert your data object to correctly formatted json.
Import the json library and add a call to json.dumps to get correctly formatted JSON:
import tornado.web
import tornado.httpserver
import tornado.ioloop
import os.path
import json
from tornado.options import define, options
define("port", default=3000, help="run on the given port", type=int)
class Application(tornado.web.Application):
def __init__(self):
base_dir = os.path.dirname(__file__)
settings = {
}
tornado.web.Application.__init__(self, [
tornado.web.url(r"/", MainHandler, name="main"),
], **settings)
class MainHandler(tornado.web.RequestHandler):
def get(self):
data = {"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}
self.render("index.html", data=json.dumps(data))
def main():
tornado.options.parse_command_line()
Application().listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
And use raw to prevent the html auto-escaping output in your template:
<!DOCTYPE html>
<html>
<body>
<h2>JSON Object Creation in JavaScript</h2>
<p id="demo"></p>
<script>
/* var text = '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}'; */
var text = '{% raw data %}';
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.name + "<br>" +
obj.street + "<br>" +
obj.phone;
</script>
<body>
</body>
</html>
The key point is that string will be autoescaped by template engine. So we need to decode it before parsing it as a json.
{% raw %} directive mentioned by #clockwatcher is one solution. But it may cause error if the variable text is double-quoted since json.dumps(data) will use double quotation marks in its output.
Therefore, a possible better solution is to unescape text.
import tornado.web
import tornado.httpserver
import tornado.ioloop
import os.path
import json
from tornado.options import define, options
define("port", default=3000, help="run on the given port", type=int)
class Application(tornado.web.Application):
def __init__(self):
base_dir = os.path.dirname(__file__)
settings = {
}
tornado.web.Application.__init__(self, [
tornado.web.url(r"/", MainHandler, name="main"),
], **settings)
class MainHandler(tornado.web.RequestHandler):
def get(self):
data = {"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}
self.render("index.html", data=json.dumps(data))
def main():
tornado.options.parse_command_line()
Application().listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
<!DOCTYPE html>
<html>
<body>
<h2>JSON Object Creation in JavaScript</h2>
<p id="demo"></p>
<script>
String.prototype.unescapeHtml = function () {
var temp = document.createElement("div");
temp.innerHTML = this;
var result = temp.childNodes[0].nodeValue;
temp.removeChild(temp.firstChild);
return result;
}
var text = '{{data}}';
var obj = JSON.parse(text.unescapeHtml());
document.getElementById("demo").innerHTML =
obj.name + "<br>" +
obj.street + "<br>" +
obj.phone;
</script>
</body>
</html>
The snippet of function unescapeHTML comes from JavaScript: how to unescape HTML entities.
Related
The code is designed to generate a dataframe using a background task. Once the background task is completed, the results from the dataframe is emitted to an html script using flask-socketio. A user can click a button to toggle the text.
Python script:
from flask import Flask, render_template, request
import pandas as pd
from flask_executor import Executor
from flask_socketio import SocketIO, emit
import json
app = Flask(__name__)
socketio = SocketIO(app)
#socketio.on("response")
def background_task_func():
data = {'Name': ['Tom', 'Joseph', 'Krish', 'John'], 'Age': [20, 21, 19, 18]}
desired_output={"objects":[
{"Name":"Tom","Age":20},
{"Name":"Joseph","Age":21},
{"Name":"krish","Age":19},
{"Name":"John","Age":18},
]}
data_2= pd.DataFrame(data)
df_json=data_2.to_json(orient='records')
results = {"objects":df_json}
socketio.emit('response_output',desired_output, broadcast=True)
#app.route('/', methods=['GET'])
def index():
executor.submit(background_task_func)
return render_template('views/index_img_soc4.html')
if __name__ == "__main__":
executor = Executor(app)
socketio.run(app)
Variable desired_output is a test dict, which successfully displays in the html script below.
The html script is following:
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
<style>
#bargraph ={display:none;}
</style>
<button id="button_demo" class="w3-button w3-white w3-small w3-border w3-border-green w3-round-large" onclick="myFunctionChart()">View Chart</button>
<div id="testmesg"><span id="myText"></span></div>
<div id="myData"></div>
<div class="chart" id="bargraph">
<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js" integrity="sha256-yr4fRk/GU1ehYJPAs8P4JlTgu0Hdsp4ZKrx8bDEDC3I=" crossorigin="anonymous"></script>
<script type="text/javascript" charset="utf-8">
var socket = io().connect('http://127.0.0.1:5000');
socket.emit('response')
var str_;
socket.on('response_output', function(obj) {
str_ ="Hello";
var html = "";
for (var i=0; i < obj.objects.length; i++) {
html += "<p>" + obj.objects[i].Name + obj.objects[i].Age + "</p>";
}
document.getElementById("myData").innerHTML = html;
});
</script>
</div>
<script>
function myFunctionChart() {
var x = document.getElementById("testmesg");
if (x.style.display === "none") {
x.style.display = "block";
document.getElementById("myText").innerHTML=str_;
} else {
x.style.display = "none";
}
}
</script>
I would like to convert the dataframe data_2 to same structure as variable desired_output.
Below is a snippet of the code which can be used to view the outputs of the dataframe and to view the expected outputs' structure (i.e. variable desired_output).
The input is called data which is a dict. This is converted to a dataframe called data_2. The output of df_json is a string and not a dictionary. Therefore my final output is called results which is a dict of string {"objects":'[ {"Name":"Tom","Age":20}, {"Name":"Joseph","Age":21}, {"Name":"krish","Age":19}, {"Name":"John","Age":18} ]'} .
How can I rectify this to output {"objects":[ {"Name":"Tom","Age":20}, {"Name":"Joseph","Age":21}, {"Name":"krish","Age":19}, {"Name":"John","Age":18} ]}?
import pandas as pd
import json
data = {'Name': ['Tom', 'Joseph', 'Krish', 'John'], 'Age': [20, 21, 19, 18]}
desired_output = {"objects":[
{"Name":"Tom","Age":20},
{"Name":"Joseph","Age":21},
{"Name":"krish","Age":19},
{"Name":"John","Age":18},
]}
data_2= pd.DataFrame(data)
df_json=data_2.to_json(orient='records')
result = {"objects":df_json}
You need to parse the json string to an object
result = {"objects": json.loads(df_json)}
I am working on Yolov3, OpenCV,python and Flask. Here, I explain the details of usage for each item.
Yolov3 - To detect and recognize object in video input
Opencv - To capture images of detected object in video input.
Flask - As a web server since it's support python language.
My objective
To develop application which able to captured the image of the object and update in the flask web directly or real-time
For your information, currently my system able to capture image and save in one folder which name as images by using OpenCv and python. you can refer the code below.
opencv and python code to capture image of object detected
for i in range(len(boxes)):
if i in indexes:
x,y,w,h = boxes[i]
label = str(LABELS[class_ids[i]])
confidence= confidences[i]
color = colors[class_ids[i]]
crop_img = image[y:y + h, x:x + w]
imagesPath = "images/file_%d.jpg"%self.d
cv2.imwrite(imagesPath, crop_img)
self.d+=1
cv2.rectangle(image,(x,y),(x+w,y+h),color,2)
cv2.putText(image,label+" "+str(round(confidence,2)),(x,y+30),font,1,(255,255,255),2)
When the images successfully save in images folder. I convert all the images in to base64 and return as json in flask. Here I attach the python code in flask.
Covert image to base64 and render in html templates
#app.route("/images")
def get_images():
directory = os.listdir('C:/Users/HP/Miniconda3/envs/count_vechicle/coding/images')
os.chdir('C:/Users/HP/Miniconda3/envs/count_vechicle/coding/images')
image_list= list()
for file in directory:
data = dict()
base = os.path.basename(file)
data["label"] = base
open_file = open(file,'rb')
image_read = open_file.read()
image_64_encode = base64.encodebytes(image_read)
data["data"] = image_64_encode.decode('ascii')
image_list.append(data)
final_data = {'files':image_list}
return render_template('images.html', final_data=final_data)
images.html
<!DOCTYPE html>
<html>
<head>
<!DOCTYPE html>
<html lang="en">
<head>
<title>yolo</title>
</head>
<body>
<h1 class="logo">Results</h1>
<ul>
{% for data in final_data.files %}
<li>{{data.label}}</li>
<img alt="embedded" src="data:image/jpg;base64,{{data.data}}"/>
{% endfor %}
</ul>
</body>
</html>
Problem and question
I have two major problem here.
1) When i run my application, my application captured the images welly. But it's automatically stop when image.html page is open to display the picture. Why it's happen and how to solve this?
2) If the application able to capture image even i open the image.html page. What should i do to update my web directly or real-time?
Here I attach the full code. Because I have been works for many weeks but still not found the solution. Hope someone can helps. Let's me know if u need more information
code
App.py
from flask import Flask, render_template, Response,jsonify
from camera import VideoCamera
import numpy as np
import os
import time
import detect as dt
from PIL import Image
import cv2
import base64
import json
from pprint import pprint
app = Flask(__name__)
def success_handle(output, status=200, mimetype='application/json'):
return Response(output, status=status, mimetype=mimetype)
#app.route("/images")
def get_images():
directory = os.listdir('C:/Users/HP/Miniconda3/envs/count_vechicle/coding/images')
os.chdir('C:/Users/HP/Miniconda3/envs/count_vechicle/coding/images')
flist = list()
for file in directory:
data = dict()
base = os.path.basename(file)
data["label"] = base
open_file = open(file,'rb')
image_read = open_file.read()
image_64_encode = base64.encodebytes(image_read)
data["data"] = image_64_encode.decode('ascii')
flist.append(data)
final_data = {'files':flist}
return render_template('images.html', final_data=final_data)
#app.route('/')
def index():
return render_template('index.html')
def gen(camera):
frame_id = 0
while True:
frame = camera.get_frame()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
#app.route('/video_feed')
def video_feed():
return Response(gen(VideoCamera()),
mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
camera.py
import cv2
import time
import os
import numpy as np
font = cv2.FONT_HERSHEY_PLAIN
starting_time= time.time()
frame_id = 0
count = 0
d = 0
labelsPath = os.path.sep.join(["yolo-coco", "coco.names"])
weightsPath = os.path.sep.join(["yolo-coco", "yolov3.weights"])
configPath = os.path.sep.join(["yolo-coco", "yolov3.cfg"])
#imagesPath = 'C:/Users/HP/Miniconda3/envs/count_vechicle/coding/images/file_%d.jpg"%d'
labelsPath = os.path.sep.join(["yolo-coco", "coco.names"])
VideoPath = os.path.sep.join(["videos", "highway.mp4"])
LABELS = open(labelsPath).read().strip().split("\n")
net = cv2.dnn.readNet(configPath, weightsPath)
layer_names = net.getLayerNames()
outputlayers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
colors= np.random.uniform(0,255,size=(len(LABELS),3))
class VideoCamera(object):
def __init__(self):
# Using OpenCV to capture from device 0. If you have trouble capturing
# from a webcam, comment the line below out and use a video file
# instead.
self.video = cv2.VideoCapture(VideoPath)
self.frame_id = 0
self.d = 0
# If you decide to use video.mp4, you must have this file in the folder
# as the main.py.
# self.video = cv2.VideoCapture('video.mp4')
def __del__(self):
self.video.release()
def get_frame(self):
success, image = self.video.read()
# We are using Motion JPEG, but OpenCV defaults to capture raw images,
# so we must encode it into JPEG in order to correctly display the
# video stream.
self.frame_id+=1
#print(frame_id)
height,width,channels = image.shape
#print (frame.shape)
#detecting objects
blob = cv2.dnn.blobFromImage(image,0.00392,(320,320),(0,0,0),True,crop=False) #reduce 416 to 320
net.setInput(blob)
outs = net.forward(outputlayers)
#print(outs)
print(outs[1])
#Showing info on screen/ get confidence score of algorithm in detecting an object in blob
class_ids=[]
confidences=[]
boxes=[]
for out in outs:
#print(out)
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
print(confidence)
if confidence > 0.8:
#object detected
center_x= int(detection[0]*width)
center_y= int(detection[1]*height)
w = int(detection[2]*width)
h = int(detection[3]*height)
#cv2.circle(img,(center_x,center_y),10,(0,255,0),2)
#rectangle co-ordinaters
x=int(center_x - w/2)
y=int(center_y - h/2)
#cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
boxes.append([x,y,w,h]) #put all rectangle areas
confidences.append(float(confidence)) #how confidence was that object detected and show that percentage
class_ids.append(class_id) #name of the object tha was detected
indexes = cv2.dnn.NMSBoxes(boxes,confidences,0.4,0.6)
# result = open('C:/Users/HP/Miniconda3/envs/count_vechicle/coding/images/frame%04d.txt'%(count), 'w')
for i in range(len(boxes)):
if i in indexes:
x,y,w,h = boxes[i]
label = str(LABELS[class_ids[i]])
# cv2.imwrite(label, crop_img)
confidence= confidences[i]
color = colors[class_ids[i]]
crop_img = image[y:y + h, x:x + w]
imagesPath = "images/file_%d.jpg"%self.d
cv2.imwrite(imagesPath, crop_img)
self.d+=1
cv2.rectangle(image,(x,y),(x+w,y+h),color,2)
cv2.putText(image,label+" "+str(round(confidence,2)),(x,y+30),font,1,(255,255,255),2)
elapsed_time = time.time() - starting_time
fps=frame_id/elapsed_time
cv2.putText(image,"FPS:"+str(round(fps,2)),(10,50),font,2,(0,0,0),1)
# cv2.imshow("Image",image)
# key = cv2.waitKey(1) #wait 1ms the loop will start again and we will process the next frame
# if key == 27: #esc key stops the process
# break;
ret, jpeg = cv2.imencode('.jpg', image)
return jpeg.tobytes()
index.html
<html>
<head>
<title>Object Detection</title>
</head>
<body>
<h1>Video Streaming Demonstration</h1>
<img src="{{ url_for('video_feed') }}">
</body>
</html>
images.html
<!DOCTYPE html>
<html>
<head>
<!DOCTYPE html>
<html lang="en">
<head>
<title>yolo</title>
</head>
<body>
<h1 class="logo">Results</h1>
<ul>
{% for data in final_data.files %}
<li>{{data.label}}</li>
<img alt="embedded" src="data:image/jpg;base64,{{data.data}}"/>
{% endfor %}
</ul>
</body>
</html>
I try to draw circular gauge using jQuery and circularchart and I'm able to make it.
I want the setInterval() function of javascript to auto-refresh the value so that the gauge value keep update by itself without manual refresh.
But the setinterval() function is not working at all.
I don't want to refresh the whole page or the body of html.
I just want to refresh the particular circleChart#0 function.
Your help is needed.
This is circle.html
<body>
<div class="circleChart" id="0"></div>
<div class="circleChart" id="1" data-value="77"></div>
<script src="{{ url_for('static', filename='jquery-1.12.4.min.js') }}"></script>
<script src="{{ url_for('static', filename='circleChart.js') }}"></script>
<script>
$(".circleChart#1").circleChart();
$(".circleChart#0").circleChart({
size: 200,
value: {{temperature}},
text: 0,
onDraw: function(el, circle) {
circle.text(Math.round(circle.value) + "'C");
}
});
setInterval(function() {
$("#0").circleChart({
value: {{temperature}},
onDraw: function(el, circle) {
circle.text(Math.round(circle.value) + "'C");
}
});
}, 2000);
</script>
</body>
</html>
This is my python code (main.py)
#!/usr/bin/python
from flask import Flask, render_template
app = Flask(__name__)
import os
import glob
import time
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
def read_temp_raw():
f = open(device_file, 'r')
lines = f.readlines()
f.close()
return lines
def read_temp():
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 / 5.0 + 32.0
return temp_c, temp_f
#app.route("/")
def main():
temperature , humidity = read_temp()
templateData = {
'temperature' : temperature,
'humidity': humidity
}
return render_template('circle.html', **templateData)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, debug=True)
Assuming {{temperature}} is some kind of template variable, those are (typically) only evaluated once when generating the page from your template.
You will need some kind of AJAX call to fetch the updated temperature value.
Just join to this community. I have python script that produce string in html :
from shelljob import proc
import flask
import os
import eventlet
eventlet.monkey_patch()
app = flask.Flask(__name__)
#app.route('/create')
def create():
g = proc.Group()
p = g.run("timeout 30s mycommand | grep -Eo 'https?://\S+'")
def read_process():
while g.is_pending():
lines = g.readlines()
for proc, line in lines:
yield "data:" + line + "\n\n"
return flask.Response( read_process(), mimetype= 'text/event-stream' )
#app.route('/')
def get_page():
return flask.send_file('page.html')
if __name__ == '__main__':
app.run(debug=True)
that code will produce something like :
This sample output with static result...
Please visit https://www.example.com/click?nonce=1a2b3c4d to bla bla bla.
This sample output with static result...
Please visit https://www.example.com/click?nonce=1a2b3c4d to bla bla bla.
How i can get url only like this one and only show first result :
https://www.example.com/click?nonce=1a2b3c4d
because if i type"timeout 30s mycommand | grep -Eo 'https?://\S+'" i can get exact url.
I can replace the text with javascript, but i'm still got list result instead 1 line. This my html "page.html"
<!DOCTYPE html>
<html>
<head>
<style type="text/css">.urldb{color: #ffffff;padding: 10px;background: red;text-decoration: none;}</style>
</head>
<body>
<div id="output"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jQuery-linkify/2.1.4/linkify.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jQuery-linkify/2.1.4/linkify-string.min.js"></script>
<script>
var source = new EventSource("/create");
var options = {className: 'urldb',target: {url: '_blank'}};
source.onmessage = function(event) {
document.getElementById("output").innerHTML += event.data.replace(/(\bhttps?:\/\/\S+)|[^]/g, '$1').linkify(options) + "<br/>";
if (event.data.indexOf('Welcome') > -1) {
$("#output").hide();
window.location.href = "https://example.com";
}
};
</script>
</body>
</html>
Using that script i got result like :
https://www.example.com/click?nonce=1a2b3c4d
https://www.example.com/click?nonce=1a2b3c4d
https://www.example.com/click?nonce=1a2b3c4d
Thanks and sorry if any wrong in my question.
Edit to add more alternative wrong in python or javascript and remove "e" to make clear.
You have maybe typo in the pattern. Change https?://e\S+ to https?://\S+ (remove e) and it works.
For output only fist match you can use -m1. For more informations see man page.
I am new to Flask and Javascript. I am trying to upload a file and use one of its columns as options in the drop down menu. Please correct me where I am wrong.
Here are the codes:
Flask:
from flask import Flask, render_template, redirect, url_for, request, flash, send_from_directory
from werkzeug import secure_filename
import os
import pandas as pd
import numpy as np
import json
UPLOAD_FOLDER = 'uploads/'
ALLOWED_EXTENSIONS = set(['csv'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
#app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['data_file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
data = pd.read_csv(os.path.join(app.config['UPLOAD_FOLDER'], filename))
names = data['some_column']
return redirect(url_for('drop_down', names=names))
#return render_template('drop_down.html', names=names)
return render_template('file_upload.html')
#app.route('/meta')
def drop_down():
return render_template('drop_down.html')
Javascript:
function my_script(){
console.log('script called.');
//var cars = ["Volvo","Ferrari","Audi","BMW","Mercedes","Porche","Saab","Avanti"];
var cars = {{ names|safe }};
console.log('cars assigned.');
function make_drop_down(list_of_names, element_id){
select_elem = document.getElementById(element_id)
if(select_elem){
for(var i = 0; i < list_of_names.length; i++) {
var option = document.createElement('option');
option.innerHTML = list_of_names[i];
option.value = list_of_names[i];
select_elem.appendChild(option);
}
}
};
console.log("Making Drop Downs!!");
make_drop_down(cars, 'drop_down_1');
make_drop_down(cars, 'drop_down_2');
console.log("Made Drop Downs!!");
};
html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="static/drop_down.js"></script>
<title>DROP DOWN</title>
</head>
<body onload="my_script()">
<select id="drop_down_1">
<option>Choose Option 1</option>
</select>
</br></br>
<select id="drop_down_2">
<option>Choose Option 2</option>
</select>
</body>
</html>
I get the following error on the console:
ReferenceError: my_script is not defined
There are two problems.
The first one is that you are not passing the list of cars in your view handeling /meta
#app.route('/meta')
def drop_down():
return render_template('drop_down.html')
This should probably look something like this:
#app.route('/meta')
def drop_down():
cars = ["Volvo","Ferrari","Audi","BMW","Mercedes","Porche","Saab","Avanti"]
return render_template('drop_down.html',
names=cars)
The second problem is that your javascript won't be able to access the list, unless you pass it in your call to the function.
html
<body onload="my_script({{ names }})">
javascript
function my_script(names){
console.log('script called.');
var cars = names;
...
Edit:
The function that handles the view is the function that needs to pass the data. You could also use the commented away part of your upload file, which calls render_template... with the necessary data, but this doesn't feel as a "nice" approach.
You need to make the data available to your drop_down() view, either by storing it in a database, reading the data from the file in this function or by storing it in the session. So that you can pass the data along with the template