Sitemap generator
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
1.9 KiB

  1. import asyncio
  2. from aiofile import AIOFile, Reader, Writer
  3. import logging
  4. from datetime import datetime, timezone, timedelta
  5. class XMLWriter():
  6. def __init__(self, filename: str):
  7. self.filename = filename
  8. async def write(self, urls, timezone_offset):
  9. async with AIOFile(self.filename, 'w') as aiodf:
  10. writer = Writer(aiodf)
  11. await writer('<?xml version="1.0" encoding="utf-8"?>\n')
  12. await writer(
  13. '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"'
  14. ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
  15. ' xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">\n')
  16. await aiodf.fsync()
  17. for data in urls:
  18. timestamp = data[1][1]
  19. changefreq = data[1][2]
  20. priority = data[1][3]
  21. images = data[1][4]
  22. url = "<loc>{}</loc>".format(data[0])
  23. if timestamp is not None:
  24. timestamp = datetime.strptime(timestamp, "%a, %d %b %Y %H:%M:%S %Z").astimezone(tz=timezone(timedelta(hours=timezone_offset))).isoformat()
  25. url += "<lastmod>{}</lastmod>".format(str(timestamp))
  26. if changefreq is not None:
  27. url += "<changefreq>{}</changefreq>".format(str(changefreq))
  28. if priority is not None:
  29. url += "<priority>{}</priority>".format(str(priority))
  30. if len(images) > 0:
  31. for image in images:
  32. url += "<image:image><image:loc>{}</image:loc></image:image>".format(str(image))
  33. await writer('<url>{}</url>\n'.format(url))
  34. await aiodf.fsync()
  35. await writer('</urlset>')
  36. await aiodf.fsync()