赞
踩
我的代码:
#!/bin/python
import os,sys
from datetime import datetime
from flask import Flask
from database import db_session,init_db
from models import Node
version = '0.1'
app = Flask(__name__)
@app.route("/")
def index():
return "hello"
@app.route("/add")
def add():
node = Node('test','test','this is a test',1)
db_session.add(node)
db_session.commit()
return 'is ok'
@app.teardown_request
def shutdown_session(exception=None):
print "Teardown 1 {0!r}".format(exception)
db_session.remove()
if __name__ == "__main__":
app.run(debug=True)
我的models.py,这是一个简单的模型,只是一个Node
from sqlalchemy import Column,Integer,String,Text
from database import Base
class Node(Base):
__tablename__ = 'nodes'
id = Column(Integer, primary_key=True)
title = Column(String(300))
tagnames = Column(String(125))
body = Column(Text())
nodetype=Column('node_type',Integer(11))
def __init__(self,title=None,tagnames=None,body=None,nodetype=0):
self.title = title
self.tagnames = tagnames
self.body = body
self.nodetype = nodetype
def __repr__(self):
return '' % (self.title)
我的database.py,我没有使用flask-sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('mysql://root:123456@127.0.0.1:3306/test', echo=True,convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,autoflush=False,bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
def init_db():
import flaskq.models
Base.metadata.create_all(bind=engine,checkfirst=True)
当我第一次请求“http://127.0.0.1:5000/add”时
这段代码抛出:
AttributeError:’NoneType’对象没有属性’request’
请求再次,一切都好.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。