2012-10-12 24 views
1

我想從連接到我的金字塔應用程序的數據庫中的條目創建一個Whoosh索引。但是,我並不確定如何在應用程序之外訪問數據庫。訪問WSGI實例外的金字塔數據庫

所以我models.py被初始化如下:

from sqlalchemy import (
    Column, 
    Integer, 
    Text, 
    String, 
    ForeignKey, 
    Table 
    ) 

from sqlalchemy.ext.declarative import declarative_base 

from sqlalchemy.orm import (
    scoped_session, 
    sessionmaker, 
    relationship, 
    backref 
    ) 

from sqlalchemy.dialects.mysql import DATETIME, FLOAT, TEXT 

from zope.sqlalchemy import ZopeTransactionExtension 

db_session = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) 
dbBase = declarative_base() 
dbBase.query = db_session.query_property() 

然後在__init__.py,有裝載在模型的例子:

from pyramid.config import Configurator 
from sqlalchemy import engine_from_config 
from .models import db_session, Recipe 
def main(global_config, **settings): 
    """ This function returns a Pyramid WSGI application. 
    """ 
    engine = engine_from_config(settings, 'sqlalchemy.') 

    db_session.configure(bind=engine) 

production.ini由引擎分配:

sqlalchemy.url = mysql+pymysql://username:[email protected]:3306/database?charset=utf8 

所以main被稱爲當WSGI進程啓動時,它從.ini文件傳遞引擎。但是我想通過一個不依賴WSGI進程的腳本來訪問數據庫。我可以只分配引擎並將其綁定到腳本中的會話? extension=ZopeTransactionExtension()如何影響會話?

回答

0

金字塔文檔中有一章討論編寫腳本,但它埋在Command-Line section中。相關部分是initializedb.py已被轉換爲控制檯腳本,該腳本在bin目錄中創建腳本。這就是爲什麼使用相對導入導入models的原因。

對於我目前的需求,這看起來有點誇張,所以我仍然需要更簡單的東西。該解決方案將包括:

if __name__ == '__main__': 
    main() 
在我的劇本

,然後從目錄中包含與我production.ini文件調用腳本:

../bin/python -m myproject.scripts.whooshindex production.ini 

-m運行模塊作爲腳本。這可以修復相對導入,從而利用預定義的initializedb.py腳本的所有優點。

+0

如今金字塔文檔告訴你一切你需要知道的正確使用console_scripts的建議@madjar - http://pyramid.readthedocs.org/en/latest/narr/commandline.html#making-your-script-into- a-console-script –

+0

我們可以使用pshell和正確的.ini文件(development.ini或production.ini)然後導入模型的DBSession等嗎?這對我行得通。我已經完成了。 –

1

alchemy腳手架包含一個initialize script您可以使用爲例。該設置看起來像下面的例子,我爲你評論。

config_uri = argv[1] # Get config file name from arguments 
setup_logging(config_uri) # In case you want ti use the logging config from the file 
settings = get_appsettings(config_uri) # Get a settings dir from the file 
engine = engine_from_config(settings, 'sqlalchemy.') # Setup the engine from the settings 
DBSession.configure(bind=engine) # Configure the session to use the engine 
with transaction.manager: # Do stuff in a transaction 
    # Do DB stuff 

ZopeTransactionExtension只是意味着DB工作需要提交,因此你要麼transaction.commit()結束你的代碼,或者你把它包裝成一個with transaction.manager:

+0

我仍然不確定如何運行它,因爲我得到了「ValueError:試圖在非包的相對導入」關於導入..models。我試過在父目錄中運行,似乎在所有目錄中都有__init__.py文件。 – abroekhof