Pyramid:如何自动生成站点地图?
有没有办法在Pyramid框架中动态生成网站地图,并定期提交给Google呢?
我看到有两个代码片段(在这里和在这里)是用Flask实现的,但好像不适用于Pyramid。
具体来说,当我在__init__.py
中加入config.add_route('sitemap', '/sitemap.xml')
,然后再添加以下视图时:
@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_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>
2 个回答
你可以看看这里
from pyramid.threadlocal import get_current_registry
def mview(request):
reg = get_current_registy
当我查看源代码时,发现了在pyramid.config.Configurator
里面有一个方法叫get_routes_mapper
。
也许这能帮助你动态生成网站地图哦 :)
假设你想把 http://example.com/sitemap.xml 设定为你的网站地图网址,那就这么做。
在 init.py 文件里添加这一行代码,这样就能把网址 http://example.com/sitemap.xml 注册为一个叫 sitemap
的路由。
config.add_route('sitemap', '/sitemap.xml')
接下来,你需要为 sitemap
这个路由注册一个视图代码,并用你自定义的 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)
这样做可以解决你在命名模板时出现的错误,因为你试图把模板命名得像网址一样。不过,这样会导致渲染器的使用规则混淆,具体如下:
- *.pt 会触发 Chameleon 渲染器
- *.jinja2 会触发 Jinja2 渲染器
- *.mako 会触发 Mako 渲染器
- *.xml 会触发 XML 渲染器(这也是你最初错误的原因)
现在,创建符合 网站地图协议 的 XML 文件还是得靠你自己。不过,你的代码看起来很不错。你把资源树传给了 XML 模板。每个资源通常都能访问到它们的属性,比如网址或最后修改时间等信息。