How to pass data to javascript in flask\jinja environment? - python

I am using VS code in a Windows 10 environment to debug a python flask\jinja application.
Python code pass data to html page without issue and {{ formDict }} displays data correctly. Debugging shows there are data passed to javascript. However, running to this line
var dict = json.stringfy('{{ formDict|tojson|safe }}');
generates this error
toJson is not defined
Is this VS code issue that not load jinja or some other problem? Any recommendation how to resolve it?
Python code:
formDict = {"firstname": "Eric", "lastname": "Smith"}
return render_template("appointment.html",formDict=formDict)
html file - appintment.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script>
function createPointOption () {
var dict = json.stringfy('{{ formDict|tojson|safe }}');
......
}
</script>
</head>
<body onload="creatPointOption()">
....
<p id="test">{{formDict}}</p>
</body>
</html>

Are you sure your error is tojson is not defined. When I ran your code, I got json is not defined.
Try:
var dict = JSON.stringify('{{ formDict|tojson|safe }}');
Note capatilisation of JSON

Related

I need to upload data from REST API on front-end using vue.js framework but not using vue.js cli

I'm trying to get the data from rest api using vue.js. But it's not working , I've started learning vue.js just now I've tried to implement many logic but still it doesn't gives the appropriate output.
Here's my views.py file
# Create your views here.
class TaskViewSet(ModelViewSet):
renderer_classes = [TemplateHTMLRenderer]
template_name = 'templates/list.html'
def list(self,request):
queryset = Task.objects.all()
serializer = TaskSerializer(queryset,many=True)
context = {
'serializer' : serializer.data
}
return Response(context)
Here's my list.html file
<!DOCTYPE html>
<html lang="en">
{%load static%}
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"
integrity="sha256-Gs0UYwrz/B58FsQggzU+vvCSyG/pewemP4Lssjzv8Ho="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.3.4/vue-
resource.min.js" integrity="sha256-OZ+Xidb5+lV/saUzcfonHJQ3koQncPy0hLjT8dROdOU="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.3.4/vue-
resource.min.js" integrity="sha256-OZ+Xidb5+lV/saUzcfonHJQ3koQncPy0hLjT8dROdOU="
crossorigin="anonymous"></script>
<title>Document</title>
</head>
<body>
<h3>Tasks Display Here</h3>
<div id="app" v-for="task in tasks">
{{task.data}}
</div>
<script>
var app = new Vue({
el : '#app',
data:{
tasks : []
}
},
methods : {
async getData(){
try {
// fetch tasks
const response = await
this.$http.get('http://localhost:8000/api/tasks/');
// set the data returned as tasks
this.tasks = response.data;
} catch (error) {
// log the error
console.log(error);
}
},
},
created(){
this.getData();
}
}
</script>
</body>
</html>
I have mentioned my API url from where the data is getting retrieved but still the vue.js script is unable to collect the data from the api. I'm really confused what's actually happening in my code. If I try to print the data in console using console.log() it still returns me a plain console.

python file not providing output in atom using angular

learning how to use angular and python on atom text editor
this is my angular code in index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
{{myData}}
<!-- <ul>
<li ng-repeat="x in myData">
{{x.name}},{{x.age}}
</li>
</ul> -->
</div>
</body>
</html>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get('test.py').then(function(response) {
$scope.myData = response.data;
});
});
</script>
and the python code is as below in test.py:
import json
message = "Hello World"
#test = [{'name':'sample1','age':'24'},{'name':'sample2','age':'25'}]
print json.dumps(message)
the commented code is what i really want to do, but i am not able to get the simple code work either.
when i run the code on live server, this is the output i see on the page http://127.0.0.1:3000/index.html:
import json message = "Hello World" #test = [{'name':'sample1','age':'24'},{'name':'sample2','age':'25'}] print json.dumps(message)

Vue app doesn't load when served through Python Flask server

I have a simple "hello world" VueJS app I'm trying to get working:
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">
Message: {{ message }}
</div>
<script>
var vm = new Vue({
el: "#app",
data: {
message: "Hello, world"
}
});
</script>
</body>
</html>
When I load this file in the browser, off my local disk (ie: file:///home/user/vue-project/index.html), it loads and "Hello, world" is displayed.
However, if I try to take the same file and serve it through the python flask development server, or through gunicorn, {{message}} renders blank.
Does anyone know what might be causing that to happen?
flask renders its variables with jinja2 which uses {{ variable }} as its parsing delimiter
render("mytemplate.html",message="Hello") would replace all {{ message }} blocks with "Hello" before any javascript is handled ... since you dont define message it is simply an empty string... you will need to configure vue to use alternative delimiters (I use [[ message ]])
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">
Message: [[ message ]]
</div>
<script>
var vm = new Vue({
el: "#app",
delimiters : ['[[', ']]'],
data: {
message: "Hello, world"
}
});
</script>
</body>
</html>

python web.py write in template html file error

use web.py to write a python program:
class user_name_friend_sub:
def POST(self):
u_n = web.input()
u_name = u_n.user_name
u_id = u_n.user_id
user_friends_list = self.user_info_page(u_name,u_id)
return render.user_friends(user_friends_list)
user_friends_list is a list containing many dic,like:
[{'user_id': '1146214671', 'user_name': 'Xiaohong Xu', 'user_unit': 'Toronto, Ontario'},
...
...
{'user_id': '668347108', 'user_name': 'Lynn Zou', 'user_unit': 'Lead Software Engineer I at American Institutes for Research (AIR)'}]
and the template html file - user_friends.html is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
<style>
h1 {
text-align: center;
font-size:30px;
}
</style>
</head>
<body>
<h1>User friends data</h1>
$def with (user_friends_list)
<ul>
$for user_friend in user_friends_list:
<li>$user_friend["user_name"]</li>
</ul>
</body>
</html>
when running,it errors:
File "templates\user_friends.html", line 21
def with (user_friends_list)
^
SyntaxError: invalid syntax
Template traceback:
File 'templates\\user_friends.html', line 21
</html>
however, when I delete almost all the html element, the user_friends.html become:
$def with (user_friends_list)
<ul>
$for user_friend in user_friends_list:
<li>$user_friend["user_name"]</li>
</ul>
it runs ok,
could you please tell me the reason
Python is a server-side language. This means it cannot be executed via a webpage directly, as it runs on a server (hidden from user visibility.) You must declare python code in .py files. Your HTML code could submit elements to a cgi end point, for example, which then allows the python to digest and return values: www.tutorialspoint.com/python/python_cgi_programming.htm

Jinja2 browser load

I am able to execute the python file through shell like so:
$ python jinja.py
[code]
from jinja2 import Environment, FileSystemLoader
DIR = '/Users/username/Sites'
env = Environment(loader=FileSystemLoader(DIR))
templateVars = {
"title" : "Test Example",
"description" : "Description"
}
template = env.get_template('index.html')
print template.render(templateVars)
[/code]
Here is the ouput via the shell:
[code]
<html>
<head>
<title>Test Example</title>
<meta name="description" content="Description">
</head>
<body>
test dictionary
</body>
</html>
[/code]
However, when I pull up index.html on the browser it doesn't render the variable, I am not sure the file jinja.py is even being executed.
Here is the sourcecode directly from my the browser window:
[code]
<html>
<head>
<title>{{ title }}</title>
<meta name="description" content="{{ description }}">
</head>
<body>
test dictionary
</body>
</html>
[/code]
Fyi, I am not using jinja2 in conjunction with any frameworks or other package dependencies.
Anyone able to help out.
Thanks
Mark
Your http://www.example.com/index.html should GET a script, which uses jinja to render the HTML.
You need a framework like webapp2 in Google App Engine to handle the GET.
I found this tutorial: https://www.youtube.com/watch?v=XyGW0ExGHDQ
Or use: https://developers.google.com/appengine/docs/python/gettingstartedpython27/introduction

Categories