Skip to main content
 

Publishing Markdown to Micropub Endpoints with Python

2 min read

You’re probably sick of my posts about Micropub by this point, so I’ll make this my last for a while. Maybe.

I’m up in Seattle this week on business, and the airplane ride from Los Angeles gave me a chance to play around a bit more with Micropub. I whipped up a quick script that allows for quickly publishing Markdown-formatted content to a Micropub endpoint.

This very post is published with the script! Micropub inception! Take a look:

#!/usr/bin/env python

'''
A script for quickly publishing blog posts to a Micropub endpoint. To use
this script, first ensure that you have installed:

    PyYAML
    requests
    markdown

You will also need to set the following environment variables:

    INDIEAUTH_TOKEN
    MICROPUB_ENDPOINT

Run the script, and pass it the path to a Markdown-formatted file. YAML
formatted front matter can be provided with Micropub arguments such as
`name`, `published`, and `slug`.
'''

import sys, os, yaml
import requests, markdown

# configuration
data = {}
token = os.environ.get('INDIEAUTH_TOKEN')
endpoint = os.environ.get('MICROPUB_ENDPOINT')

# make sure the user has provided adequate information
if not token or not endpoint:
    print 'INDIEAUTH_TOKEN & MICROPUB_ENDPOINT environment variables not set.'
    sys.exit(0)

if len(sys.argv) < 2:
    print 'Usage:'
    print '    blogit <path to markdown file>'
    sys.exit(0)

# read in the content
filename = sys.argv[1]
raw_content = open(filename, 'rb').read()

# check for front matter
if raw_content.startswith('---'):

    # parse out the front matter from the raw content
    _, front_matter, raw_content = raw_content.split('---', 2)

    # parse the frontmatter
    data = yaml.load(front_matter)

# render markdown
data['content'] = markdown.markdown(raw_content, extensions=[
    'markdown.extensions.codehilite',
    'markdown.extensions.extra',
    'markdown.extensions.smarty'
])

# populate remaining details
data['access_token'] = token
if 'h' not in data:
    data['h'] = 'entry'

# create the post
result = requests.post(endpoint, data=data)

# check the result
if result.status_code not in (200, 201):
    print 'Failed to publish post with status code: %d' % result.status_code
    sys.exit(1)

print 'Published successfully.'

You’ll note that it supports some Markdown extras, including code highlighting with Pygments, and several other extras.

Feedback is, of course, welcome. On my flight home, I plan on polishing the script up a bit, making it easy to install, and adding a few options.