Skip to content

Instantly share code, notes, and snippets.

Last active March 6, 2018 00:54
What would you like to do?
Import MF2 JSON selectively
#!/usr/bin/env python
A script for quickly publishing MF2 content to a Micropub endpoint. To use this
script, first ensure that you have installed:
You will also need to set the following environment variables:
Run the script, and pass in a path to a directory containing MF2 JSON files.
import sys, os, os.path, codecs, json
import requests
# configuration
token = os.environ.get('INDIEAUTH_TOKEN')
endpoint = os.environ.get('MICROPUB_ENDPOINT')
def publish(mf2_path, path, mf2_filename):
# build out the data to send
content =, mode='r', encoding='utf-8').read()
data = json.loads(content)
h = {'Authorization': 'Bearer ' + token}
# create the post
result =, json=data, headers=h)
# check the result
if result.status_code not in (200, 201):
print 'Failed to publish post with status code: %d' % result.status_code
print 'Moving file to "failed" directory.'
os.system('mkdir -p %s/failed' % path)
os.system('mv %s %s/failed' % (mf2_path, path))
print 'Published successfully.'
target = result.headers.get('Location')
print ' ->', target
os.system('mkdir -p %s/published' % path)
os.system('mv %s %s/published' % (mf2_path, path))
open('%s/published/' % (path, mf2_filename), 'w').write(target)
def skip(mf2_path, path):
print 'Skipping file and moving to "skipped" subdirectory.'
os.system('mkdir -p %s/skipped' % path)
os.system('mv %s %s/skipped' % (mf2_path, path))
def save(mf2_path, path):
print 'Skipping file and moving to "saved" subdirectory.'
os.system('mkdir -p %s/saved' % path)
os.system('mv %s %s/saved' % (mf2_path, path))
if __name__ == '__main__':
# make sure the user has provided adequate information
if not token or not endpoint:
print 'INDIEAUTH_TOKEN & MICROPUB_ENDPOINT environment variables not set.'
path = sys.argv[1]
for mf2_file in sorted(os.listdir(path)):
mf2_path = os.path.join(path, mf2_file)
if not os.path.isfile(mf2_path): continue
data = json.loads(open(mf2_path).read())
if data.get('properties', {}).get('photo') != None:
print '=' * 80
print 'Skipping PHOTO post:', mf2_path
skip(mf2_path, path)
print '=' * 80
print os.path.join(path, mf2_file)
print '-' * 80
print open(mf2_path).read()
print '-' * 80
action = raw_input('Publish file [(Y)es, (n)o, (s)ave]?: ')
if action in ('Y', 'y', ''):
publish(mf2_path, path, mf2_file)
elif action == 'n':
skip(mf2_path, path)
elif action == 's':
save(mf2_path, path)
print 'Unknown action', action
now_what = raw_input('Continue [(Y)es, (n)o]?: ')
if now_what not in ('Y', 'y', ''):
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment