beacon.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # encoding=utf-8
  2. '''Formatting URL data into the BEACON format.'''
  3. from datetime import datetime
  4. from terroroftinytown.format.base import *
  5. __all__ = ['BEACONWriter']
  6. class BEACONWriter(BaseWriter):
  7. homepage = 'http://urlte.am/'
  8. def __init__(self, *args, **kwargs):
  9. super(BEACONWriter, self).__init__(*args, **kwargs)
  10. self._site = None
  11. def write_header(self, site, *args, **kwargs):
  12. self.fp.write('#FORMAT: BEACON\n'.encode('ascii'))
  13. if '{shortcode}' in site:
  14. self._site = site
  15. else:
  16. self.fp.write(('#PREFIX: %s\n' % (site)).encode('utf8'))
  17. if self.homepage:
  18. self.fp.write(('#HOMEPAGE: %s\n' % (self.homepage)).encode('utf8'))
  19. timestamp = datetime.utcnow()
  20. if 'timestamp' in kwargs:
  21. assert isinstance('timestamp', datetime), \
  22. 'timestamp argument must be datetime instance'
  23. timestamp = kwargs['timestamp']
  24. self.fp.write(('#TIMESTAMP: %s\n' % (timestamp.isoformat())).encode('ascii'))
  25. self.fp.write(b'\n')
  26. def write_shortcode(self, shortcode, url, encoding):
  27. if self._site and '{shortcode}' in self._site:
  28. self.fp.write(
  29. self._site.format(shortcode=shortcode).encode('ascii')
  30. )
  31. else:
  32. self.fp.write(shortcode.encode('ascii'))
  33. self.fp.write(b'|')
  34. self.fp.write(url.encode(encoding))
  35. self.fp.write(b'\n')
  36. registry['beacon'] = BEACONWriter