losingle
losingle

Reputation: 143

Flask AttributeError: 'NoneType' object has no attribute 'request'

My code:

#!/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)

my models.py,this is a simple models ,just a 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 '<Node %r>' % (self.title)

my database.py,I'm not using 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:[email protected]: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)

when I first request "http://127.0.0.1:5000/add" this code throws: AttributeError: 'NoneType' object has no attribute 'request'

request again,every things is ok.

Upvotes: 6

Views: 11359

Answers (2)

twooster
twooster

Reputation: 931

In contrast to Don Question, you shouldn't be setting up a context yourself. Flask should do that when you connect to it. Assuming you're using a browser to access /add, you should not have the problem you're having.

Are you connecting programmatically or using a browser?

Upvotes: 2

Don Question
Don Question

Reputation: 11614

Obviously you lack an object which should have a request attribute. It's possible, that somewhere in your add-method you need a reference to the request-object/context. (Is this really the whole Error-Report? Partial Error-Reporst are seldom useful!) I guess your using the django libraries here, and maybe Flask with SQLite3-Example might be useful to you. Through the teardown_request a request-context is automatically established and that maybe the reason it just fails at the first call.

According to Context-Locals there is sometimes a need for an explicit request-context (whatever that means in detail i can't explain) maybe the following will help:

from flask import request

... 
def add():
   with app.request_context(environ):
      node = Node('test','test','this is a test',1)
      db_session.add(node)
      db_session.commit()
      return 'is ok'

Upvotes: 2

Related Questions