首页 > 解决方案 > 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'

标签: pythonpostgresqlflasksqlalchemy

解决方案


你在all_types这里调用了两件事——你的处理程序和你的实用程序函数——这令人困惑。但事实上,您实际上并没有调用它们中的任何一个。您正在做的是将对当前处理程序函数的引用传递到您的模板中,它自然不知道如何处理它。

您需要将您的 types 模块导入您的 apps.py 中,然后传递调用该​​函数的结果:

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

推荐阅读