This question already has an answer here:
Call python function using HTML
(1 answer)
Closed 8 years ago.
I have a python script (display_names.py) that displays the list of names in the json file
def search():
with open('business_ten.json') as f:
data=f.read()
jsondata=json.loads(data)
for row in jsondata['rows']:
a=str(row['name'])
yield a
print list(search())
I am trying to call this function in my html file(crawl.html) using flask.
{% extends "layout.html" %}
{% block content %}
<div class="jumbo">
<h2>Welcome to the Rating app<h2>
<h3>This is the home page for the Rating app<h3>
</div>
<body>
<p>{{ myfucntion}}</p>
</body>
{% endblock %}
My routes file is as follows:
from flask import Flask,render_template
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
#app.route('/crawl')
def crawl():
return render_template('crawl.html' , myfucntion=search)
if __name__ == '__main__':
app.run()
This doesnt work and it always gives an error on the html page
please help
I believe you need to execute the function when calling it. In python, to execute a function, you use parentheses, so try:
{{ myfucntion() }}
Edit: I see you typoed them both, so that was not an issue. My apologies.
Related
I have my server.py file, where i have:
from flask import Flask,render_template,url_for
app=Flask(__name__)
#app.route("/")
#app.route("/home")
def home():
return render_template("home.html",posts=posts,title="arroz")
if __name__=="__main__":
app.run(debug=False)
My home.html file has:
{%extends "layout.html"%}
{%block content%}
<!--here-->
{%endblock content%}
I want to execute some python code in a python file on the client side in the comment here on the home.html file. I can't just call regular python code from flask, because that would run on the server side. How can I run it on the client side?
My project's structure is the following:
|-server.py
|-pythonToExecuteOnClientSide.py
|-templates
|-home.html
This won't work since Python is not a web-app language supported by browsers. Everything that is client-side needs to be able to run on the client computer and for Python code you need to have Python installed on your computer.
The only option you have is to code your feature in JavaScript to let it run on the client side.
Why exactly do you want it to run on the client side? Maybe there is a different solution for your problem. Like a server-client program.
You are already executing python code on the client side.
{% pyton code %} <html> {% python %}.
to give you an example.
when you render your page you can pass a python variable named 'posts' to your page with the value "i did it"; along with a python variable named 'title' with the value "arroz".
return render_template("home.html", posts=posts, title=title)
you can display the value of those python variables like this:
{%extends "layout.html"%}
{%block content%}
{{ posts }} {{ title }}
{%endblock content%}
you can format the value displayed just like any other html content:
<p> {{ posts }} </p> <h1> {{ title }} </h1>
your final code should be
server.py
from flask import Flask,render_template,url_for
app=Flask(__name__)
#app.route("/")
#app.route("/home")
def home():
posts = None
title = "arroz"
return render_template("home.html",posts=posts,title=title)
if __name__=="__main__":
app.run(debug=False)
home.html
{%extends "layout.html"%}
{%block content%}
<p> {{ posts }} </p> <h1> {{ title }} </h1>
{%endblock content%}
I am using a Queensland government API. The format for it is JSON, and the keys have spaces in them. I am trying to access them with python and flask. I can pass through the data required to the HTML file yet cannot print it using flask.
{% block content %}
<div>
{% for suburb in data %}
<p>{{ suburb.Age }}</p>
<p>{{ suburb.Manslaughter Unlawful Striking Causing Death }}</p>
{% endfor %}
</div>
{% endblock content %}
Above is the code for the HTML file. "Manslaughter Unlawful Striking Causing Death" is the key I am trying to access but it comes up with this error when I load the page.
from flask import Flask, render_template
import requests
import json
app = Flask(__name__)
#app.route('/', methods=['GET'])
def index():
req = requests.get("https://www.data.qld.gov.au/api/3/action/datastore_search?resource_id=8b29e643-56a3-4e06-81da-c913f0ecff4b&limit=5")
data = json.loads(req.content)
print(data)
district=[]
for Districts in data['result']['records']:
district.append(Districts)
return render_template('index.html', data=district)
if __name__=="__main__":
app.run(debug=True)
Above now is all the python code I am running.
The error that is shown on the webpage when trying to load it.
Any suggestions, please?
Instead of using dot notation in your template, you can access values in a dictionary like this
{{ suburb['Manslaughter Unlawful Striking Causing Death'] }}
Hopefully that solves your issue!
In jinja2 (which is used by Flask for templating) you can access dict elements like in python, consider following example:
import jinja2
temp = jinja2.Template("Value of abc is {{data['a b c']}}")
data = {'a b c': '1 2 3'}
rend = temp.render(data=data)
print(rend)
output
Value of abc is 1 2 3
This question already has answers here:
Passing HTML to template using Flask/Jinja2
(7 answers)
Closed 4 years ago.
So I want to put an svg file into my page(not as an image, as an xml element) - need it like this so I could dynamically change elements within the page.
and I made a simple code that I thought it'll do:
#app.route('/map_test/')
def test():
svg = render_template('file.svg')
response = make_response(svg)
response.content_type = 'image/svg+xml'
return render_template('test.html', svg=response)
and test.html:
{% block content %}
<section>
{{ svg }}
</section>
{% endblock %}
....which just returned <Response 126181 bytes [200 OK]> instead of svg element...
so... what do I need to do in order to get this to work?
this did the trick:
from flask import Markup
#app.route('/map_test/')
def test():
svg = open('file.svg').read
return render_template('test.html', svg=Markup(svg))
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def hello_world():
img = './static/download.svg'
return render_template('index.html', img=img)
if __name__ == '__main__':
app.run()
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<img src="{{ img }}">
</body>
</html>
put your svg file in dir called static
Im having trouble getting anything from the shown HTML form
I always get "ValueError: View function did not return a response"
Can somebody help me out here please? I have tried every variation of request.get that I can find on the web. Also if I specify my form should use post it uses get anyway - anybody know why this is?
Im new to flask so forgive my ignorance!
Thanks in advance.
The python file (routes.py)
from flask import Flask, render_template, request
import os
app = Flask(__name__)
musicpath = os.listdir(r"C:\Users\Oscar\Music\iTunes\iTunes Media\Music")
lsize = str(len(musicpath))
looper = len(musicpath)
#app.route('/')
def home():
return render_template('home.html', lsize=20, looper=looper, musicpath=musicpath)
#app.route('/pop', methods=['POST', 'GET'])
def pop():
if request.method == "GET":
text = request.args.get('som')
return text
#Have tried every variation of request.get
#app.route('/about')
def about():
name = "Hello!"
return render_template('about.html', name=name)
if __name__ == '__main__':
app.run(debug=True)
The html file (home.html)
{% extends "layout.html" %}
{% block content %}
<div class="jumbo">
<h2>A Music app!<h2>
</div>
<div>
{% if lsize %}
<form action="/pop">
<select id="som" size="20">
{% for i in range(looper):%}
<option value="{{i}}">{{ musicpath[i] }}</option>
{% endfor %}
</select>
</form>
{% endif %}
</div>
Select,
{% endblock %}
You don't have a name attribute on your select element. That is the attribute that browsers use to send information in forms; without it no data will be sent.
Note also that your pop handler does not do anything if the method is POST, even though you explicitly say you accept that method.
Im having trouble getting anything from the shown HTML form
I always get "ValueError: View function did not return a response"
Can somebody help me out here please? I have tried every variation of request.get that I can find on the web. Also if I specify my form should use post it uses get anyway - anybody know why this is?
Im new to flask so forgive my ignorance!
Thanks in advance.
The python file (routes.py)
from flask import Flask, render_template, request
import os
app = Flask(__name__)
musicpath = os.listdir(r"C:\Users\Oscar\Music\iTunes\iTunes Media\Music")
lsize = str(len(musicpath))
looper = len(musicpath)
#app.route('/')
def home():
return render_template('home.html', lsize=20, looper=looper, musicpath=musicpath)
#app.route('/pop', methods=['POST', 'GET'])
def pop():
if request.method == "GET":
text = request.args.get('som')
return text
#Have tried every variation of request.get
#app.route('/about')
def about():
name = "Hello!"
return render_template('about.html', name=name)
if __name__ == '__main__':
app.run(debug=True)
The html file (home.html)
{% extends "layout.html" %}
{% block content %}
<div class="jumbo">
<h2>A Music app!<h2>
</div>
<div>
{% if lsize %}
<form action="/pop">
<select id="som" size="20">
{% for i in range(looper):%}
<option value="{{i}}">{{ musicpath[i] }}</option>
{% endfor %}
</select>
</form>
{% endif %}
</div>
Select,
{% endblock %}
The Problem is that your HTML form does not have a name.
request.args.get("som") needs an HTML form input with the name "som"
<select name="som" id="som" size="20">
Just change that line and add a name. The form is not interested in the id attribute.
You don't specified the method of the form, you have to do it! For example use this<form method="POST action"/pop">
Your form action is /pop. That means that if you submit the form it will do a POST request to the address /pop. Your code does only return a value for a GET request, therefore Flask complains you do not return anything. Write some code to process a POST request and return a text or rendered template.
BTW, in the code for GET you refer to request.args.get('som'); this gives you request arguments (i.e. in the URL), not from the form. som is in the form, so you cannot refer to it this way.