constance

Scripts for generating (an earlier obsolete version of) my personal web site
git clone https://code.djc.id.au/git/constance/

tools/export_readinglog_wp.py (2270B) - raw

      1 import os, time, re, urllib, uuid, sys
      2 import MySQLdb
      3 import yaml
      4 
      5 def export(options):
      6     log_entries = []
      7 
      8     cn = MySQLdb.connect(host=options.host, user=options.username, 
      9             passwd=options.password, db=options.db, use_unicode=True)
     10 
     11     cur = cn.cursor()
     12     cur.execute('SELECT id, post_title, post_date, guid FROM wp_posts '
     13             'INNER JOIN wp_term_relationships ON '
     14             'wp_term_relationships.object_id = wp_posts.id '
     15             'WHERE post_status = %s AND term_taxonomy_id = %s '
     16             'ORDER BY post_date ASC', ('publish', 14))
     17     for row in cur.fetchall():
     18         id, title, date, guid = row
     19         entry = {'Title': title, 'Date': date, 'GUID': guid}
     20         subcur = cn.cursor()
     21         subcur.execute('SELECT meta_key, meta_value FROM wp_postmeta '
     22                 'WHERE post_id = %s', (id,))
     23         for key, value in subcur.fetchall():
     24             if key == '_readinglog_url': entry['URL'] = value
     25             elif key == '_readinglog_author': entry['Author'] = value
     26             elif key == '_readinglog_rating': entry['Rating'] = float(value)
     27         log_entries.append(entry)
     28 
     29     if options.output is not None:
     30         f = open(options.output, 'w')
     31     else:
     32         f = sys.stdout
     33     
     34     yaml.add_representer(unicode, lambda dumper, value: 
     35             dumper.represent_scalar(u'tag:yaml.org,2002:str', value))
     36     yaml.dump_all(log_entries, f, default_flow_style=False, allow_unicode=True)
     37 
     38 if __name__ == '__main__':
     39     from optparse import OptionParser
     40     parser = OptionParser()
     41     parser.add_option('-H', '--host', 
     42             help='connect to MySQL server HOST [default: %default]')
     43     parser.add_option('-u', '--username', 
     44             help='use USERNAME when connecting [default: %default]')
     45     parser.add_option('-p', '--password', 
     46             help='use PASSWORD when connecting [default: no password]')
     47     parser.add_option('-d', '--db', 
     48             help='name of the Wordpress database [default: %default]')
     49     parser.set_defaults(host='localhost', username='root', 
     50             password=None, db='wordpress')
     51     parser.add_option('-o', '--output', metavar='FILE', 
     52             help='write output to FILE instead of stdout')
     53     options, args = parser.parse_args()
     54     export(options)