我正在学习如何使用sqlalchemy和金字塔,所以我一直在尝试从已经创建的数据库中获取我的对象,但我无法得到任何东西。我阅读了sqlalchemy的文档但我无法获得任何对象。
models.py
import os
import sys
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
class Poll(Base):
__tablename__ = 'poll'
# Here we define columns for the table person
# Notice that each column is also a normal Python instance attribute.
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
class Type(Base):
__tablename__ = 'type'
id = Column(Integer, primary_key=True)
name = Column(String(250))
class Question(Base):
__tablename__ = 'question'
# Here we define columns for the table address.
# Notice that each column is also a normal Python instance attribute.
id = Column(Integer, primary_key=True)
text = Column(String(250))
type_id = Column(Integer, ForeignKey('type.id'))
type = relationship(Type)
poll_id = Column(Integer, ForeignKey('poll.id'))
poll = relationship(Poll)
class Option(Base):
__tablename__ = 'option'
id = Column(Integer, primary_key=True)
text = Column(String(250))
question_id = Column(Integer, ForeignKey('question.id'))
question = relationship(Question)
class Answer(Base):
__tablename__ = 'answer'
id = Column(Integer, primary_key=True)
text = Column(String(250))
option_id = Column(Integer, ForeignKey('option.id'))
option = relationship(Option)
views.py
from pyramid.view import view_config
from .models import *
from sqlalchemy.orm import *
db = create_engine('mysql://polls:polls@localhost:3306/polls')
db.echo = True
Session = sessionmaker(bind=db)
session = Session()
@view_config(route_name='home', renderer='templates/mytemplate.jinja2')
def my_view(request):
q = session.query(Poll).first()
return {'project': 'polls', 'variable':q.name}
模板
{% extends "layout.jinja2" %}
{% block content %}
<div class="content">
<h1><span class="font-semi-bold">Pyramid</span> <span class="smaller">Starter project</span></h1>
<p class="lead">Welcome to <span class="font-normal">{{variable}}</span>, a Pyramid application generated by<br><span class="font-normal">Cookiecutter</span>.</p>
</div>
{% endblock content %}
我在视图中看到一个None对象。我究竟做错了什么?
答案 0 :(得分:0)
在SQLAlchemy文档中,它说连接MySQL DB的正确方法是这样的:
db = create_engine('mysql+pymysql://polls@localhost:3306/polls'
当你拨打+pymysql
create_engine()
)
注意:您可能必须使用pip install pymysql
答案 1 :(得分:0)
我对概念有点困惑,但显然问题是我在models.py中隐藏了Base.metadata.create_all(引擎),认为它会强制重新创建所有数据库。看起来如果这不可用,sqlalchemy不会正确映射数据。
感谢。