Written by Sean Behan on Thu Mar 02nd 2017

I wrote my first Python package over the weekend. It is a simple package that adds a basic blog API to an existing Flask application.

It's called command_line_blog and is available on Github and on PyPi

It can be installed with pip

pip install command_line_blog

It assumes a few things.

Your blog will use a database
You will write the view templates for the display yourself
You're comfortable from the command line and know how to use CURL

The idea is that each blog post has a unique slug and can read and write to that URL from the command line with POST and GET requests. If a post with the slug in question doesn't exist, create it. If it does exist, update it.

Because blog posts tend to have a lot of copy, it makes sense to keep your work in a file. And so we use file to set the body of the post. For example...

curl -X POST http://example.com/blog/hello-world -F file=@myfile.md

This will create a new blog post at /blog/hello-world with whatever the contents of myfile.md are. It doesn't have to be markdown. It can be anything as you're responsible for rendering the HTML in the view.

You can also use headers to set other attributes. For instance...

-H 'Author: Sean' -H 'Tags: Programming, Python, Flask'

You can also delete a post by sending a delete request to the resource

curl -X DELETE http://example.com/blog/hello-world

To edit an existing post you will want to download the contents of the file first. This is also done with Curl...

curl http://example.com/blog/hello-world > myfile.md

Since we now have a copy of the body from the post on file we can issue our post request from above to replace the contents with our updated version.

The app is packaged as a Flask Blueprint and in this example is mounted at /blog. It could be anything, for instance, /posts-api works just as well.

And finally, it is protected with Basic Auth. The credentials for managing posts are set as environment variables.

The environment variables are DATABASE_URL COMMAND_LINE_BLOG_TABLE COMMAND_LINE_BLOG_USER and COMMAND_LINE_BLOG_PWD

If you are on linux you can set these in your .bash_profile, e.g.,

export DATABASE_URL = sqlite:///database.db
export COMMAND_LINE_BLOG_TABLE  = 'name_of_database_table'
export COMMAND_LINE_BLOG_USER   = 'username used for basic auth'
export COMMAND_LINE_BLOG_PWD    = 'password used for basic auth'

And here is an example app that uses this package

from flask import Flask as App
from command_line_blog import command_line_blog as blog_app, command_line_blog_posts as posts

app = App(__name__)
app.register_blueprint(blog_app, url_prefix='/blog')

@app.route("/")
def index():
        return render_template('posts.html', posts=posts.all())

if __name__=='__main__':
        app.run(debug=True)

Tagged with..
#Python #Flask #Web Development #Blogging #API #Curl

Just finishing up brewing up some fresh ground comments...