Skip to content

Instantly share code, notes, and snippets.

@inthuriel inthuriel/notes_import.py
Last active Jul 10, 2018

Embed
What would you like to do?
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
# encoding=utf8
import re
import pprint
import json
import requests
import base64
import sys
reload(sys)
sys.setdefaultencoding('utf8')
notes = list()
tittle_pattern = re.compile(r'((\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) - (.+))')
tags = [
1
]
categories = [
1
]
wp_url = 'http://localhost:8000/wp-json/wp/v2/posts'
wp_usr = 'admin'
wp_passwd = 'admin'
with open('./eksport-notek.txt', 'r') as notes_file:
text = notes_file.readlines()
for position, line in enumerate(text):
beg_match = tittle_pattern.search(line)
if beg_match:
note = dict()
note.setdefault('begin', position)
note.setdefault('date', beg_match.group(2))
note.setdefault('tittle', beg_match.group(3).rstrip('\r').rstrip())
note.setdefault('tags', tags)
notes.append(note)
for note_id, note_data in enumerate(notes):
start_line = note_data.get('begin') + 1
try:
stop_line = notes[note_id+1].get('begin') - 1
except (KeyError, IndexError) as error:
stop_line = len(text)
note_text = ''.join(text[start_line:stop_line])
note_data.setdefault('content', note_text)
for note in notes:
payload = {
'title': note.get('tittle'),
'status': 'draft',
'content': note.get('content'),
'categories': categories,
'tags': tags,
'date': note.get('date').replace(' ', 'T'),
'slug': re.sub(r'-+', '-', re.sub(r'\W', '-',
note.get('tittle').strip())).strip('-').lower()
if len(note.get('tittle')) else 'not-set'
}
headers = {
'Content-type': 'application/json',
'Authorization': 'Basic {}'.format(base64.b64encode('{}:{}'.format(wp_usr, wp_passwd)))
}
response = requests.post(wp_url, data=json.dumps(payload), headers=headers)
data = response.json()
print('Post {} added on link {}'.format(data.get('title', {}).get('raw', 'not-set'),
data.get('link')))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.