flask sqlalchemy使Postgres交易空闲

时间:2014-02-21 13:17:30

标签: python api postgresql sqlalchemy flask

我正在用烧瓶,sqlalchemy,Postgres,nginx,uwsgi写一个烧瓶api。我是python的新手。这是我的配置

database.py

from cuewords import app
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.pool import NullPool
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String , Text , Boolean , DateTime, MetaData, Table ,Sequence
from sqlalchemy.dialects.postgresql import JSON


 Base = declarative_base()
 db_name="postgresql+psycopg2://admin:password@localhost:5434/database_name"
 from sqlalchemy.orm import sessionmaker
 engine = create_engine(db_name,poolclass=NullPool ,echo=True)
 Session = sessionmaker(autocommit=False ,bind=engine)
 connection = engine.connect()
 metadata = MetaData()

api.py

   class Webcontent(Resource):

    def post(self):
    session=Session()
    ...assign some params...
    try:
      insert_data=Websitecontent(site_url,publisher_id)
      session.add(insert_data)
      session.commit()
      Websitecontent.update_url(insert_data.id,session)
    except:
      session.rollback()
      raise
    finally:
      return "Data created "
      session.close()                
  else:  
    return "some value"

这里我首先保存了刚才的url,然后使用samppipe保存网站的所有内容.Idea将稍后移到队列

model.py

 class Websitecontent(Base):

  @classmethod
  def update_url(self,id,session):
  existing_record=session.query(Websitecontent).filter_by(id=int(id)).first()
  data=Processing.processingContent(str(existing_record.url))

  #boilerpipe processing the content here
  #assigning some data to existing record in session 

  session.add(existing_record)
  session.commit()
  Websitecontent.processingWords(existing_record,session)

  @classmethod
  def processingWords(self,record,session)
    ...processing
    Websitecontent.saveKeywordMapping(session,keyword_url,record)

  @classmethod
  def saveKeywordMapping(session,keyword_url,record)
   session.commit()
   session.close()

所以这段代码在本地完美运行,但它在生产中不起作用。因此,当我检查pag_stat_activity时,它显示状态“在事务中空闲”。应用程序挂起然后我必须重新启动服务器。我不明白为什么session.close()不关闭池连接为什么它保持psql事务状态忙。任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:1)

您在关闭会话前返回:

  return "Data created "
  session.close()

我认为最终返回内部可能会吞下异常。