Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

flask

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.

like image 628
losingle Avatar asked Dec 25 '11 10:12

losingle


People also ask

How do I fix NoneType has no attribute?

The Python "AttributeError: 'NoneType' object has no attribute 'get'" occurs when we try to call the get() method on a None value, e.g. assignment from function that doesn't return anything. To solve the error, make sure to only call get() on dict objects.

What does NoneType object has no attribute mean?

The Python error "AttributeError: 'NoneType' object has no attribute..." probably means that the Gramps program attempted to retrieve an object (such as a person, or family) by using its internal handle, but the database can't find it.

What is NoneType error in Python?

NoneType in Python is a data type that simply shows that an object has no value/has a value of None . You can assign the value of None to a variable but there are also methods that return None .

How do you create a NoneType in Python?

If you want NoneType back, just define NoneType = type(None) .


2 Answers

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'
like image 143
Don Question Avatar answered Oct 10 '22 18:10

Don Question


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?

like image 23
twooster Avatar answered Oct 10 '22 19:10

twooster