python web.py write in template html file error - python

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

Related

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

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

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>

Render return html into text

This is urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.login_page, name='login_page'),
]
my views.py like this
def login_page(request):
return render(request, 'mileage/login_page.html', {})
this is my html code
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, width=device-width" >
<meta charset="UTF-8">
<title>Test</title>
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
</script>
</head>
<body bgcolor="#4599e8">
<div class="title"><span><h1>Test</h1></span></div>
<div class="home_password">
<div class="password"><input type="password" name="password" placeholder="Password"></div>
<div class="button"><button>OK</button></div>
</div>
</body>
</html>
And start server, but my localhost:8080/ shows only html text not page.
Using Chrome Developer Console, I checked element.
<html>
<head></head>
<body>
<pre style="word-wrap: break-word; white-space: pre-wrap;">
"
my html code here.
"
</pre>
</body>
</html>
I don't know how to solve it.
Who is inserting all your html code inside the pre tag is your browser because it probably receives a Content-type: text/plain header with the response and it thinks you want to see the html code instead of the rendered webpage.
Try making a test using:
render(request, 'mileage/login_page.html', {}, content_type='text/html')
If it works, set the DEFAULT_CONTENT_TYPE constant to 'text/html' in your settings.
DEFAULT_CONTENT_TYPE
Default: 'text/html'
Default content type to use for all HttpResponse objects, if a MIME
type isn’t manually specified. Used with DEFAULT_CHARSET to construct
the Content-Type header.
Probably an environment variable is messing you up with this, It's weird that it has a default 'text/plain' content type set.

Jinja2 weird encoding error

I have been fighting this for a whole night...
I'm trying to use Python markdown to generate HTML files from .md files and embed them into some other HTML files.
Here is the problematic snippet:
md = markdown.Markdown(encoding="utf-8")
input_file = codecs.open(f, mode="r", encoding="utf-8") # f is the name of the markdown file
text = input_file.read()
html = md.convert(text) # html generated from the markdown file
context = {
'css_url': url_for('static', filename = 'markdown.css'),
'contents': html
}
rendered_file = render_template('blog.html', **context)
output = open(splitext(f)[0] + '.html', 'w') # write the html to disk
output.write(rendered_file)
output.close()
Here is my "blog.html" template , which is really simple:
<!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" lang="en">
<head>
<title>blog</title>
<link rel="stylesheet" href="{{ css_url }}" type="text/css" />
</head>
<body>
{{ contents }}
</body>
</html>
And yet this is what I get:
<!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" lang="en">
<head>
<title>blog</title>
<link rel="stylesheet" href="/static/markdown.css" type="text/css" />
</head>
<body>
<li>People who love what they are doing</li>
<li></li>
</ol>
</body>
</html>
So I'm getting those weird "&gt", "&lt" stuff, even though I've already specified the encoding to be 'utf-8'. What could possibly go wrong?
Thank you!
<> has nothing to do with encoding. These are HTML entities that represent your input. You should mark it as safe so that jinja will not automatically escape it.
{{ contents|safe }}

webpy: how to override content of basic template?

I'm using webpy with a basic template
render = web.template.render(basedir + 'templates/', base='layout', globals=globals_vars_custom)
in layout.html I have something like:
$def with (content)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>PAGE TITLE</title>
<!-- Some CSS and some javascript -->
</head>
<body>
$:content
</body>
</html>
This basic template works fine for the 90% of my site, but I have a page in which I need to insert some other data inside the <head> (some meta tags).
How can I do this? How can I put the <head> inside a structure that I can easily override inside a template?
Thanks!
It was easier than I tought:
You can create a variable in a template:
in page.html you can define a variable
$var title = 'specific title'
in the base template layout.html you can call the varable:
$def with (content)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>$content.get("title","DEFAULT TITLE")</title>
<!-- Some CSS and some javascript -->
</head>
<body>
$:content
</body>
</html>
I hope this answer can be useful also for other people.

Categories