Flask Printing Post Data in Browser [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 days ago.
Improve this question
Hope you are all well!
I am very new to Flask and can't seem to wrap my head around some key elements.
The project I am working on is based on this youtube documentation : Subscribe to Push Notifications
Is there any way to print the received POSTed data into the browser?
Here is the app, so far :
from flask import Flask, render_template, request
import xmltodict
app = Flask(__name__)
#app.route("/result", methods=['POST', 'GET'])
def result():
if request.method == 'POST':
result = xmltodict.parse(request.data)
return render_template("table.html", result = result)
if __name__ == "__main__":
app.run(debug=True)
Here is the Table.html in case
<!doctype html>
<html>
<body>
<table border = 1>
{% for key, value in result.items() %}
<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>
{% endfor %}
</table>
</body></html>
So far, I have tried a lot of different searches everywhere online but I can't seem to find a way to make this work.

Related

Creating Dynamic Url in HTML for Flask Application [duplicate]

This question already has answers here:
Create dynamic URLs in Flask with url_for()
(6 answers)
Closed 8 months ago.
I am trying to creating dynamic url in html and routing all "orders/<key_id[0]>" to flaks app.
On the browser hyperlink should be link to name but it should route as "orders/<key_id[0]>"
Tried a lot of thing couln't manage to generate href with key_id variable with it.
Trying to create something like
{{key_id[0]}<p>{{name[0]}}</p></td>
My Base Html Code:
{% for name, sample, date, coord_x, coord_y, key_id in zipped_ %}
<tr>
<td><p>{{name[0]}}</p></td>
<td>{{sample[0]}}</td>
<td><span class="badge badge-danger">{{date[0]}}</span></td>
<td>
<div class="sparkbar" data-color="#00a65a" data-height="20">{{coord_x[0]}},{{coord_y[0]}}</div>
</td>
</tr>
{% endfor %}
Flask App Routing:
#views.route('/orders')
#views.route('/orders/<key_id>', methods=['GET', 'POST']) # ordersda birşey yazdın ama indexten bir post ya da get gelmiyor sanki
def orders():
print(key_id)
#mycursor.execute("SELECT * FROM processed_data WHERE primary_key IN (%s)",(key_id))
#zip_q = mycursor.fetchall()
return render_template("orders.html", zip_q=zip_q)
There are many ways to do it depending on your Jinja version. The "most compatible" one is to use string formatting with urlencode filter
{{key_id[0]}<p>{{name[0]}}</p>
I have found the answer at last.
<a href= {{ url_for('views.orders' , key_id=key_id[0]) }} <p>{{name[0]}}</p></a></td>
with url_for i can dynamically edit the link and for passing variable to flask:
#views.route('/orders')
#views.route('/orders/<key_id>', methods=['GET', 'POST'])
def orders(key_id):
print(key_id)
i can get the key_id variable in the flask app.

Iterating multiple lists in parallel with Python inside HTML (Flask)

I am building a python web app hosted on pythonanywhere following this tutorial loosely. I am modifying the resulting application to fit my own goal.
Here is my python code that I am using to pass variables to a HTML document in order for them to be added to a table using a for loop:
from flask import Flask, redirect, render_template, request, url_for
app = Flask(__name__)
app.config["DEBUG"] = True
productnames = []
reviews = []
#app.route("/", methods=["GET", "POST"])
def index():
if request.method == "GET":
return render_template("main.html", reviews=reviews, productnames=productnames)
reviews.append(request.form["review"])
productnames.append(request.form["products"])
return redirect(url_for('index'))
Using the following code within my HTML, I am looping through that list and adding each item to the table:
{% for review in reviews %}
<tr>
<td></td>
<td>{{ review }}</td>
<td></td>
</tr>
{% endfor %}
And this works, however, I am trying to iterate through multiple lists and found various statements saying that the zip function was what I was looking for so I changed my HTML code to the following segment and it no longer works.
{% for review, product in zip(reviews, productname) %}
<tr>
<td>{{ product }}</td>
<td>{{ review }}</td>
<td></td>
</tr>
{% endfor %}
From python anywhere, the error page says "Error code: Unhandled Exception", and the error log through the pythonanywhere dashboard says:
2018-04-24 12:57:23,957: File "/home/FdScGroup/cloudapp/templates/main.html", line 43, in top-level template code
2018-04-24 12:57:23,957: {% for review, product in zip(reviews, productnames) %}
How do I get this to work?
Any help appreciated, thank you.
zip() is a python function, not a function to be executed in the template language of Flask (Jinja2).
So apply zip() in the view and pass the result to the template:
return render_template("main.html", reviews_products=zip(reviews, productnames))
Then apply this trick:
how to iterate over a list of list in jinja
in the template.

AngularJS with Python flask [duplicate]

This question already has answers here:
Is it possible to use AngularJS with the Jinja2 template engine?
(2 answers)
Closed 4 years ago.
I'm using flask to render index page
app = Flask(__name__)
#app.route("/")
def main():
return render_template('index.html')
I'm sending the results in an ajax call made to an flask REST API. I'm able to build table using Jquery but If I'm using angularjs ng-repeat for a table like below
<table>
<tr data-ng-repeat="r in regResults">
<td>{{r.TCID}}>
</tr>
</table>
I'm getting the below error
[2018-01-30 16:50:32,833] ERROR in app: Exception on / [GET]
UndefinedError: 'r' is undefined
That's because Angular and Jinja2 use {{}} as template tags to print out variables. Jinja2 processes the template before it's rendered by the browser (and eventually picked up by Angular). The simplest solution is to enclose the block in {% raw %} like this:
{% raw %}
<table>
<tr data-ng-repeat="r in regResults">
<td>{{r.TCID}}>
</tr>
</table>
{% endraw %}
This tells jinja2 not to interfere with that section of the template.
If you find yourself with too many {% raw %} tags it might be time to separate your frontend from the backend and communicate over an API.

How to Reload Flask-based Webpage after form submission [duplicate]

This question already has answers here:
Clear valid form after it is submitted
(4 answers)
Closed 5 years ago.
Here is my code currently (omitting libraries and other unnecessary parts):
app = Flask(__name__)
class SearchForm(Form):
inputString = TextAreaField('', [validators.DataRequired()])
#app.route('/')
def index():
return render_template('Website.html')
#app.route('/results', methods=['POST'])
def results():
...
form = SearchForm(request.form)
if request.method == 'POST' and form.validate():
inputString = request.form['inputString']
...
return render_template('Website.html', cLinkName=cLinkName, \
lLinkName=lLinkName)
if __name__ == '__main__':
app.run(debug=True, use_reloader=True)
And here is the webpage (showing only the form and the variables that are changed when the SearchForm is submitted):
<form method=post action="{{url_for('results')}}" style="text-align: center;">
<input type="text" id="inputString" name="inputString"/>
<input type=submit value='Search' name='search_btn'>
</form>
<table align="center" border="1">
<tr>
<td style='text-align: center;'>{{ cLinkName }}</td>
<td style='text-align: center;'>{{ lLinkName }}</td>
</tr>
</table>
Firstly, I have looked at Flask: redirect to same page after form submission and I believe I tried to implement what was accepted as the correct answer, but it did not work for me since I am also trying to submit variables to the updated webpage rather than just refresh the webpage.
I want to be able to submit the webpage's SearchForm and then update my webpage with the cLinkName and lLinkName produced from submitting my SearchForm more than once. Unfortunately my code is only allowing me to submit the SearchForm and then update my webpage with the cLinkName and lLinkName produced from submitting my SearchForm exactly once. And, when I try to reload the webpage I receive a "Continue Form Resubmission" pop-up. So my question is how can I get my webpage to allow me to submit the SearchForm and update itself more than once?
After further research,
Clear valid form after it is submitted, I can now ask for GET requests and ensure that I can reload the localhost/results page and submit another form, but it does not run the form through the algorithm again.
Added return redirect(url_for('results')) as last line in if request.method == 'POST' and form.validate(): body and everything worked fine.

How do I get the key for the current record in GAE ndb in a Python for loop?

I currently have a web page that presents a list of records from a datastore with an edit link. I want to convert this from db. to ndb. I am a Python and GAE newbie.
The current code =
<tbody>
{% for listtype in listtypes %}
<tr>
<td> {{ listtype.ListTypeName }} </td>
<td>edit </td>
</tr>
{% endfor %}
</tbody>
Then on the .py side, I have:
def post(self, listtype_id):
iden = int(listtype_id)
listtypes = db.get(db.Key.from_path('ListTypes', iden))
listtypes.ListTypeName = self.request.get('ListTypeName')
listtypes.put()
I got to these by copying someone else's code bbut it works. I need to know what the code would look like to make it work with ndb. (I am ok with the model and the include statements, I just need to know how to retrieve the key in the jinja2 template and how to use it in the post function.
Please provide what the actuall code should look to make this work with ndb.
Thanks in advance.
With NDB key is an attribute not a method. So you listtype.key().id() should be listtype.key.id()

Categories