如何在 Pyramid 中获取 add_static_view() 的文件路径 [英] How to get file path of a add_static_view() in Pyramid

查看:30
本文介绍了如何在 Pyramid 中获取 add_static_view() 的文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我像这样添加静态视图时:

cfg = config.Configurator(...)cfg.add_static_view(name='static', path='MyPgk:static')# 我想为favicon.ico"添加一个视图.cfg.add_route(name='favicon', pattern='/favicon.ico')cfg.add_view(route_name='favicon', view='MyPgk.views.mymodule.favicon_view')

我正在尝试添加浏览器调用的 /favicon.ico 的 favicon.ico 默认路径,如果它在网页中未定义.我想使用 http://docs.pylonsproject.org 中的示例/projects/pyramid_cookbook/en/latest/files.html 并将其修改为:

def favicon_view(request, cache=dict()):如果(不是缓存):_path_to_MyPkg_static = __WHAT_GOES_HERE___icon = open(os.path.join(_path_to_MyPkg_static, 'favicon.ico')).read()缓存['响应'] = 响应(content_type='image/x-icon', body=_icon)返回缓存['响应']

既然我无法真正定义示例中提出的 _here,我如何让它依赖于 request 以在运行时获取实际的完整路径?还是我真的要处理:

_here = os.path.dirname(__file__)_path_to_MyPkg_static = os.path.join(os.path.dirname(_here), 'static')

当我决定重构并将视图放入另一个 pkg 或子包或任何地方时必须小心?

等效于 request.static_path() 但不是获取 url path,而是实际获取目录路径:

request.static_file_path('static') -> /path/to/site-packages/MyPkg/static

谢谢,

解决方案

您可以使用 pkg_resources 模块创建相对于 Python 模块的路径(因此,独立于检索它们的模块)).例如:

import pkg_resources打印 pkg_resources.resource_filename('os.path', 'static/favicon.ico')# 'C:\\Python27\\lib\\static\\favicon.ico'

只需将 os.path 替换为静态文件的父模块即可.

EDIT:如果您需要记住映射到 'MyPkg:static''static' 路由,那么最简单的方法是首先将其保存在某个字典中:

STATIC_ROUTES = {'static': 'MyPkg:static'}对于名称,STATIC_ROUTES.iteritems() 中的路径:cfg.add_static_view(名称=名称,路径=路径)

然后简单地检索路径:

static_path = STATIC_ROUTES['static']包,relative_path = static_path.split(':')icon_path = pkg_resources.resource_filename(包,os.path.join(relative_path,'favicon.ico'))

如果这是不可能的(例如,您无权访问 cfg 对象),您可以 检索此路径,这非常痛苦.这是一个示例函数,它使用未记录的调用(因此可能会在未来的 Pyramid 版本中更改)并忽略一些其他设置(例如 route_prefix 配置变量):

def get_static_path(request, name):从 pyramid.config.views 导入 StaticURLInfo注册 = StaticURLInfo()._get_registrations(request.registry)如果不是 name.endswith('/'):姓名 = 姓名 + '/'route_name = '__%s' % 名称对于注册中的 _url、spec、reg_route_name:打印 ':', reg_route_name如果 reg_route_name == route_name:退货规格

在你的情况下,它应该像这样工作:

<预><代码>>>>get_static_path(请求,'静态')我的包:静态/

When I am adding a static view like this:

cfg = config.Configurator(...)
cfg.add_static_view(name='static', path='MyPgk:static')

# And I want to add a view for 'favicon.ico'.
cfg.add_route(name='favicon', pattern='/favicon.ico')
cfg.add_view(route_name='favicon', view='MyPgk.views.mymodule.favicon_view')

I am trying to add that favicon.ico annoying default path of /favicon.ico called by the browser if it's undefined in the webpage. I would like to use the example at http://docs.pylonsproject.org/projects/pyramid_cookbook/en/latest/files.html and modify it to have:

def favicon_view(request, cache=dict()):
    if (not cache):
        _path_to_MyPkg_static = __WHAT_GOES_HERE__
        _icon = open(os.path.join(_path_to_MyPkg_static, 'favicon.ico')).read()
        cache['response'] = Response(content_type='image/x-icon', body=_icon)
    return cache['response']

Since, I can't really define the _here proposed in the example, how can I make it dependent to request to get the actual full path at runtime? Or do I really have to deal with:

_here = os.path.dirname(__file__)
_path_to_MyPkg_static = os.path.join(os.path.dirname(_here), 'static')

and having to be careful when I decide to refactor and put the view in another pkg or subpackage, or where-ever?

Something equivalent to request.static_path() but instead of getting the url path, to actually get a directory path:

request.static_file_path('static') -> /path/to/site-packages/MyPkg/static

Thanks,

解决方案

You can use the pkg_resources module to make paths that are relative to Python modules (and thus, independent of the module that retrieves them). For example:

import pkg_resources
print pkg_resources.resource_filename('os.path', 'static/favicon.ico')
# 'C:\\Python27\\lib\\static\\favicon.ico'

Just substitute os.path with whatever module that is the parent of your static files.

EDIT: If you need to remember that 'static' route mapped to 'MyPkg:static', then the easiest way is to save it in some dictionary in the first place:

STATIC_ROUTES = {'static': 'MyPkg:static'}
for name, path in STATIC_ROUTES.iteritems():
    cfg.add_static_view(name=name, path=path)

and then simply retrieve the path:

static_path = STATIC_ROUTES['static']
package, relative_path = static_path.split(':')
icon_path = pkg_resources.resource_filename(
    package, os.path.join(relative_path, 'favicon.ico'))

If that's impossible, though (e.g. you don't have access to the cfg object), you can retrieve this path, it's just quite painful. Here's a sample function that uses undocumented calls (and so may change in future Pyramid versions) and ignores some additional settings (like route_prefix configuration variable):

def get_static_path(request, name):
    from pyramid.config.views import StaticURLInfo
    registrations = StaticURLInfo()._get_registrations(request.registry)
    if not name.endswith('/'):
        name = name + '/'
    route_name = '__%s' % name
    for _url, spec, reg_route_name in registrations:
        print ':', reg_route_name
        if reg_route_name == route_name:
            return spec

In your case, it should work like this:

>>> get_static_path(request, 'static')
MyPkg:static/

这篇关于如何在 Pyramid 中获取 add_static_view() 的文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆