2013-01-04 62 views
1

我有一個金字塔web應用程序與zc.buildout管理。其中,我需要讀取磁盤上的文件,該文件位於構建目錄的子目錄中。

問題是確定文件的路徑 - 我不想硬編碼絕對路徑,只是提供相對路徑在生產中提供應用程序時不起作用(據推測是因爲工作目錄不同) 。

所以有前途「掛鉤」我的想法是:

  • 「根」擴建目錄,我可以在buildout.cfg地址0​​- 但是,我想不出如何我可以「出口」,以便它可以通過Python代碼

  • 的貼紙的.ini文件的其中啓動應用

回答

2

如果路徑相對於擴建根或paster.ini的位置的文件始終是相同的,這似乎是從你的問題,你可以將其設置在paster.ini:

[app:main] 
... 
config_file = %(here)s/path/to/file.txt 

然後從註冊表訪問它在Reinout的回答是:

def your_view(request): 
    config_file = request.registry.settings['config_file'] 
+0

啊,這是.ini本身,允許這個?很好,這意味着你不需要一個模板。 –

0

這裏位置訪問是一個相當ç lumsy解決方案我已經設計:

buildout.cfg我用的zc.recipe.eggextra-paths選項附加件目錄添加到sys.path

.... 
[webserver] 
recipe = zc.recipe.egg:scripts 
eggs = ${buildout:eggs} 
extra-paths = ${buildout:directory} 

然後我把一個叫app_config.py文件到附加件目錄:

# This remembers the root of the installation (similar to {buildout:directory} 
# so we can import it and use where we need access to the filesystem. 
# Note: we could use os.getcwd() for that but it feels kinda wonky 
# This is not directly related to Celery, we may want to move it somewhere 
import os.path 
INSTALLATION_ROOT = os.path.dirname(__file__) 

現在我們可以在我們的Python代碼中導入它:

from app_config import INSTALLATION_ROOT 
filename = os.path.join(INSTALLATION_ROOT, "somefile.ext") 
do_stuff_with_file(filename) 

如果有人知道一個更好的解決方案,您別客氣:)

+2

一般來說,我會生成一個文件,包括路徑; ['collective.recipe.template'](http://pypi.python.org/pypi/collective.recipe.template)可以很容易地將Buildout值插入到模板中。 –

+0

@MartijnPieters:你的意思是你使用'collective.recipe.template'從模板生成一個python文件?那麼你如何導入它?或者你的意思是生成一個貼紙.ini文件? – Sergey

+2

儘管你可以生成一個'.py',我建議不要這樣做。生成諸如'paster.ini'文件的東西,是的。 –

5

像@MartijnPieters建議在你自己的答案評論,我會使用collective.recipe.template產生的.ini的條目。我想知道自己如何才能在我的項目中訪問這些數據,所以我解決了這個問題:-)

讓我們按照自己的需要開展工作。首先在您的視圖代碼放到要附加件目錄:

def your_view(request): 
    buildout_dir = request.registry.settings['buildout_dir'] 
    .... 

request.registry.settingssee documentation)是「dictonary樣部署設置對象」。見deployment settings,就是這樣被傳遞到您的主要方法類似def main(global_config, **settings)

這些設置**settings是什麼在你的deployment.iniproduction.ini文件的[app:main]一部分。因此,在那裏添加構建目錄:

[app:main] 
use = egg:your_app 

buildout_dir = /home/you/wherever/it/is 

pyramid.reload_templates = true 
pyramid.debug_authorization = false 
... 

但是,這是最後一步,您不希望在那裏有硬編碼路徑。所以用模板生成.ini。模板development.ini.in使用${partname:variable}擴展語言。你的情況,你需要${buildout:directory}

[app:main] 
use = egg:your_app 

buildout_dir = ${buildout:dir} 
#    ^^^^^^^^^^^^^^^ 

pyramid.reload_templates = true 
pyramid.debug_authorization = false 
... 

buildout.cfg添加擴建部分產生development.inidevelopment.ini.in

[buildout] 
... 
parts = 
    ... 
    inifile 
    ... 

[inifile] 
recipe = collective.recipe.template 
input = ${buildout:directory}/development.ini.in 
output = ${buildout:directory}/development.ini 

注意,你可以做各種很酷的東西與collective.recipe.template。例如,${serverconfig:portnumber}可在您的production.iniyour_site_name.nginx.conf中生成匹配的端口號。玩的開心!