esinlayo esinlayo - 1 month ago 20
Python Question

Accessing object properties using Flask

I'm new to Flask and templating; I am trying to pass an object and display its data on my HTML pages.

I have a detachment class like

class Detachment:
def __init__(self, name, ...):
self.name = name
self.... = ... # lots of data, mostly lists that I'd like to index


I tried doing something like this:

import Detachment as dt
from flask import Flask, request, redirect, url_for

@app.route('/')
def go():
# stuff
testDetachment = dt.Detachment('name')
return redirect(url_for('cooliofunction', detachment=testDetachment)

@app.route('/templates')
def cooliofunction():
return render_template('data.html', obj=request.args.get('detachment'))


with my data.html attempting:

{{obj}} <br />
{{obj.name}} <br />


While {{obj}} will display the object address, I can't access the variables set in my detachment - it shows up blank. Am I approaching the whole problem wrong, or is there a simple way to access objects' properties?

EDIT: I was using redirect because the creation of testDetachment actually depends on a file upload, but I omitted it to focus on the object properties.

EDIT2: So I had been using the redirect because I was following a file upload tutorial that displayed what had been uploaded, but I don't need to do that. Rendering the template directly, I could access the object's attributes directly. Thanks, everyone!

Answer

If url_for gets arguments that are not part of the rule it's building, it will append them as the query string by converting the values to strings. The string representation of an object is its address, not the object itself. When you retrieve it in the other view, you're retrieving the string representation of the object, not the actual object.

As written, you should just omit the redirect and render the template directly in the go view.

If your actual code has a specific reason for that redirect, then you should send a unique identifier for the object, and re-load it in the other view. For example, if you're using a database, commit the object to the database, pass the id in the url, and load it by id in the other view.