Skip to main content
 首页 » 编程设计

python之Pyramid :如何自动生成站点地图

2025年05月04日13虾米哥

有没有一种方法可以动态生成站点地图并使用 Pyramid 定期将它们提交给 Google?

我在 Flask 中看到了 2 个代码片段(here 和 here),但它们似乎不适用于 Pyramid。

具体来说,当我在 __init__.py 中包含 config.add_route('sitemap', '/sitemap.xml') 然后是以下 View 时:

@view_config(route_name='sitemap', renderer='static/sitemap.xml') 
def sitemap(request): 
    ingredients = [ ingredient.name for ingredient in Cosmeceutical.get_all() ] 
    products = [ product.name for product in Product.get_all() ] 
    return dict(ingredients=ingredients, products=products) 

我得到一个错误:

File "/home/home/SkinResearch/env/local/lib/python2.7/site-packages/pyramid-1.4.5-    py2.7.egg/pyramid/registry.py", line 148, in _get_intrs_by_pairs 
raise KeyError((category_name, discriminator)) 
KeyError: ('renderer factories', '.xml') 

将 View 更改为:

@view_config(route_name='sitemap', renderer='static/sitemap.xml.jinja2') 
def sitemap(request): 
    ingredients = [ ingredient.name for ingredient in Cosmeceutical.get_all() ] 
    products = [ product.name for product in Product.get_all() ] 
    request.response.content_type = 'text/xml' 
    return dict(ingredients=ingredients, products=products) 

通过了之前的 KeyError,但是当我尝试导航到 mysite.com/static/sitemap.xml. 时却给了我一个 404。发生了什么事?

编辑:这是我的 sitemap.jinja2 文件。

<?xml version="1.0" encoding="UTF-8"?> 
<urlset 
      xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 
            http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"> 
 
{% for page in other_pages %} 
<url> 
  <loc>http://www.wisderm.com/{{page}}</loc> 
  <changefreq>weekly</changefreq> 
</url> 
{% endfor %} 
 
{% for ingredient in ingredients %} 
<url> 
  <loc>http://www.wisderm.com/ingredients/{{ingredient.replace(' ', '+')}}</loc> 
  <changefreq>monthly</changefreq> 
</url> 
{% endfor %} 
 
{% for product in products %} 
<url> 
  <loc>http://www.wisderm.com/products/{{product.replace(' ', '+')}}</loc> 
  <changefreq>monthly</changefreq> 
</url> 
{% endfor %} 
 
</urlset> 

请您参考如下方法:

假设你想建立http://example.com/sitemap.xml作为您的站点地图网址。

将此行添加到 init.py 以注册 URL 模式 http://example.com/sitemap.xml作为路线 sitemap

config.add_route('sitemap', '/sitemap.xml') 

为路由 sitemap 注册 View 代码并使用自定义 jinja2 模板 sitemap.jinja2 呈现响应。文件扩展名“jinja2”将触发 jinja2 渲染器的使用。

@view_config(route_name='sitemap', renderer='static/sitemap.jinja2') 
def sitemap(request): 
    ingredients = [ ingredient.name for ingredient in Cosmeceutical.get_all() ] 
    products = [ product.name for product in Product.get_all() ] 
    return dict(ingredients=ingredients, products=products) 

这将修复由于尝试将模板命名为 URL 而导致的错误。但这混淆了如下所示的渲染器约定。

  • *.pt 触发 Chameleon 渲染器
  • *.jinja2 触发 Jinja2 渲染器
  • *.mako 触发 Mako 渲染器
  • *.xml 触发 XML 渲染器(引发您的第一个错误)

现在仍由您根据 sitemaps protocol 创建 XML。 .但是您的代码看起来很有希望。您将资源树传递给 XML 模板。每个资源通常都可以访问其属性,例如 URL 或 last_changed 内容。