Flask无法从sqlalchemy获取数据

时间:2017-12-11 21:48:59

标签: python sqlalchemy

我无法理解为什么我无法在Flask函数和模板中从SQLAlchemy获取数据。这是代码: 1. main.py

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-

    from flask import Flask, jsonify, request, g, render_template as render
    from models import *
    from settings import *
    from flask_httpauth import HTTPBasicAuth


    ALLOWED_EXTENSIONS = set(EXTENSIONS)
    auth = HTTPBasicAuth()

    app = Flask(__name__)
    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


    @app.route('/')
    def home_page():
        brands = [item.serialize for item in session.query(Category).all()]
        items = []
        title = ''
        print brands
        return render('catalog/index.html', brands=brands, cars=items, titlr=title)


    if __name__ == '__main__':
        app.debug = True
        app.run(host='0.0.0.0')
  1. models.py:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    from sqlalchemy import Column, Integer, String, ForeignKey, DateTime
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import relationship, sessionmaker
    from sqlalchemy import create_engine
    from passlib.apps import custom_app_context as pwd_context
    from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
    from itsdangerous import BadSignature, SignatureExpired
    from data_control import get_unique_str
    
    
    Base = declarative_base()  # initialisation the database
    secret_key = get_unique_str(32)  # create secret_key
    
    # create session
    engine = create_engine('sqlite:///catalog.db')
    Base.metadata.bind = engine
    DBSession = sessionmaker(bind=engine)
    session = DBSession()
    
    
    # TODO: User model
    class User(Base):
        __tablename__ = 'user'
        id = Column(Integer, primary_key=True)
        username = Column(String(32), index=True)
        picture = Column(String(250), default='/img/no-img.png')
        first_name = Column(String(25), default=None)
        last_name = Column(String(25), default=None)
        email = Column(String(40))
        password_hash = Column(String(64))
        status = Column(String(10), default='user')
    
        def hash_password(self, password):
            """
            hash password
    
            :param password:
            :return void:
            """
            self.password_hash = pwd_context.encrypt(password)
    
        def verify_password(self, password):
            """
            Password verification
    
            :param password:
            :return bool:
            """
            return pwd_context.verify(password, self.password_hash)
    
        @property
        def get_full_name(self):
            """
            Return full name (first and last name)
    
            :return string:
            """
            return "%s %s" % (self.first_name, self.last_name)
    
        def generate_auth_token(self, expiration=3600):
            """
            Generate authentication token
    
            :param expiration:
            :return string: (token)
            """
            s = Serializer(secret_key, expires_in=expiration)
            return s.dumps({'uid': self.id})
    
        @staticmethod
        def verify_auth_token(token):
            """
            Try to load token, success return user id false return None
    
            :param token:
            :return mix:
            """
            s = Serializer(secret_key)
            try:
                data = s.loads(token)
            except SignatureExpired:
                # Valid Token, but expired
                return None
            except BadSignature:
                # Invalid Token
                return None
            uid = data['uid']
            return uid
    
        @property
        def serialize(self):
            """
            Return user data
    
            :return dict:
            """
            return {
                'id': self.id,
                'username': self.username,
                'picture': self.picture,
                'first_name': self.first_name,
                'last_name': self.last_name,
                'email': self.email,
                'status': self.status
            }
    
    
    # TODO: Image model
    class Image(Base):
        __tablename__ = 'image'
        id = Column(Integer, primary_key=True)
        product = Column(Integer, nullable=False)
        url = Column(String(250))
    
        @property
        def serialize(self):
            """
            Return user data
    
            :return dict:
            """
            return {
                'id': self.id,
                'url': self.url
            }
    
    
    # TODO: Category model
    class Category(Base):
        __tablename__ = 'category'
        id = Column(Integer, primary_key=True)
        name = Column(String(30))
    
        @property
        def serialize(self):
            """
            Return user data
    
            :return dict:
            """
            return {
                'id': self.id,
                'name': self.name
            }
    
    
    # TODO: Catalog model
    class Catalog(Base):
        __tablename__ = 'catalog'
        id = Column(Integer, primary_key=True)
        model = Column(String(30))
        title = Column(String(250))
        description = Column(String(250))
        category = Column(Integer, ForeignKey("category.id"), nullable=False)
        price = Column(Integer, nullable=False)
        author = Column(Integer, ForeignKey("user.id"), nullable=False)
    
        def get_author(self):
            """
            Return product`s author
    
            :return object:
            """
            return session.query(User).filter_by(id=self.author).one().serialize
    
        def get_images(self):
            """
            Prepare list of images for JSON
    
            :return list:
            """
            images = session.query(Image).filter_by(product=self.id).all()
            return [img.serialize for img in images]
    
        def get_category(self):
            """
            Return category
    
            :return object:
            """
            category = session.query(Category).filter_by(id=self.category).first()
            return category.serialize
    
        @property
        def serialize(self):
            """
            Return user data
    
            :return dict:
            """
            return {
                'id': self.id,
                'model': self.model,
                'title': self.title,
                'description': self.description,
                'brand': self.get_category(),
                'price': self.price,
                'images': self.get_images(),
                'author': self.get_author(),
            }
    
    
    Base.metadata.create_all(engine)
    
    模板中的

    {% extends 'base.html' %}
    
    {% block title %}{{ title }}{% endblock %}
    
    {% block content %}
    
    <div class="row">
    {{ brands }}
    {% for item in brands %}
      <div>{{ item.name }}</div>
    {% endfor %}
    {% for car in cars %}
     <div class="col-sm-4 col-lg-4">
      <div class="col-sm-6 col-lg-4 mb-5">
        <span class="tumbl-image" data-ng-click="main.showDescription()"
              image-bg="{{ car.images[0].url }}">
          <div class="hide description">{{ car.description }}</div>
        </span>
        <div class="pt-2 text-center" id="title-link">
          <a href="/car/{{ car.id }}">{{ car.title }}</a>
        </div>
        <div class="pt-2">
          <span data-ng-click="main.sendEmail(item.author.email)" class="mail-to">
            <i class="fa fa-envelope-o" aria-hidden="true"></i>
          </span>
          <a href="/profile/{{ car.author.id }}">{{ car.author.first_name }} {{ item.author.last_name }}</a>
        </div>
      </div>
     </div>
    {% endfor %}
    </div>
    {% endblock %}
    
  2. 如果我运行app并转到localhost:5000,我会看到[]

    在终端:

    * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
    * Restarting with stat
    * Debugger is active!
    * Debugger PIN: 342-567-684
    

    []    127.0.0.1 - - [11 / Dec / 2017 15:34:00]&#34; GET / HTTP / 1.1&#34; 200 -

    但如果我运行python console:

        PyDev console: starting.
        import sys; print('Python %s on %s' % (sys.version, sys.platform))
        sys.path.extend(['/path/to/catalog'])
        Python 2.7.10 (default, Jul 15 2017, 17:16:57) 
        [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
        >>> from main import *
        >>> brands = [item.serialize for item in session.query(Category).all()]
        >>> print brands
        [{'id': 1, 'name': u'BMW'}, {'id': 2, 'name': u'Ford'}, {'id': 3, 'name': u'Nissan'}, {'id': 4, 'name': u'Toyota'}, {'id': 5, 'name': u'Dodge'}, {'id': 6, 'name': u'Audi'}, {'id': 7, 'name': u'Jeep'}, {'id': 8, 'name': u'Mazda'}, {'id': 9, 'name': u'Chevrolet'}]
    

    有人请告诉我为什么烧瓶没有输出数据?提前谢谢。

1 个答案:

答案 0 :(得分:0)

我花了两天时间找到解决方案,但问题出在PyCharm上。我不知道为什么,但出于某种原因,如果我尝试在PyCharm中运行应用程序SQLAlchemy停止工作。如果我在终端中运行应用程序,它运行良好。

P.S。我希望这有助于某人。