简体   繁体   中英

Can't pass variables to html through flask

I'm trying to get data from postgressql through SQLAlchemy and loop items in to a html page.

I'm doing something wrong but I can't finger it out.

config.py

import connexion
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow


connex_app = connexion.App(__name__)

    # Get the underlying Flask app instance
    app = connex_app.app

# Configure the SqlAlchemy part of the app instance
app.config["SQLALCHEMY_ECHO"] = True
app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql://hey:hey2@localhost/heys"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

# Create the SqlAlchemy db instance
db = SQLAlchemy(app)

# Initialize Marshmallow
ma = Marshmallow(app)

models.py

from config import db, ma
from sqlalchemy import Column, Integer, String


class types(db.Model):
    __tablename__='types'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)

class TypesSchema(ma.ModelSchema):
    class Meta:
        model = types
        sqla_session = db.session

types.py

from flask import make_response, abort
from config import db
from models import types, TypesSchema

def all_types():

    # Create the list of wine type from our data
    types = types.query.order_by(types.id).all()
    # Serialize the data for the response
    types_schema = TypesSchema(many=True)
    data = types_schema.dump(types).data
    return data

app.py

from flask import render_template
import json
# local modules
import config

# Get the application instance
connex_app = config.connex_app

# create a URL route in our application for "/"
@connex_app.route("/")
def all_types():
    return render_template("index.html", types=all_types)

if __name__ == "__main__":
    connex_app.run(debug=True)

index.html

... 
<tbody>
           {% for type in types %}
              <h1>Name: {{type.name}}</h1>
              <h2>ID: {{type.id}}</h2>
          {% endfor %}
</tbody>
...

The return from types.py gives

[{'id': 1, 'name': 'Red wine'}, {'id': 2, 'name': 'White wine'}, {'id': 3, 'name': 'Sparkling'}, {'id': 4, 'name': 'Rosé'}, {'id': 7, 'name': 'Sweet Wine'}, {'id': 24, 'name': 'Tawny'}, {'id': 25, 'name': 'Not Classified'}]

But when I run it, I get "TypeError: 'function' object is not iterable".

What I'm doing wrong?

Traceback update

File "/Users/2/Library/Python/3.7/lib/python/site-packages/flask/app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/2/Library/Python/3.7/lib/python/site-packages/flask/app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "/Users/2/Library/Python/3.7/lib/python/site-packages/flask/app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/2/Library/Python/3.7/lib/python/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/Users/2/Library/Python/3.7/lib/python/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/Users/2/Library/Python/3.7/lib/python/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/2/Library/Python/3.7/lib/python/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/2/Library/Python/3.7/lib/python/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/Users/2/Library/Python/3.7/lib/python/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/2/Library/Python/3.7/lib/python/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/2/Desktop/Python/Vino_app/app.py", line 23, in all_types
return render_template("index.html", types=types.all_types())

AttributeError: module 'types' has no attribute 'all_types'

You have two things called all_types here - your handler and your utility function - which is confusing. But in fact you're not actually calling either of them. What you're doing is passing a reference to the current handler function into your template, which naturally doesn't know what to do with it.

You need to import your types module into your apps.py and then pass the result of calling the function:

import types
...
@connex_app.route("/")
def all_types():
    return render_template("index.html", types=types.all_types())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM