Flask is a lightweight Python micro framework. And by micro, they mean it’s super easy to use. Batteries are not included. (But you can inject batteries as you go!)
This tutorial will show you how to use Flask to create a Twitter clone. Most of my tutorials are based on Twitter since most people are familiar with it. So, let's get started.
You should have either
pip or
easy_install. For the sake of versioning we will use
virtualenv.
$ pip install virtualenv
// or
$ easy_install virtualenv
You may or may not need to use
sudo when running that. Let's follow up by creating a virtualenv for a project called TweetBot.
$ virtualenv tweetbot
$ cd tweetbot
$ source bin/activate
$ pip install flask sendgrid
Small recap of the commands. Source will actually activate the virtualenv in order for us to have a contained Python version. Everything we do now will be contained to this virtual python environment. Whenever you want to exit the virtualenv, just write
deactivate.
Like previously mentioned, we are going to be building a Twitter clone. Flask let's your start really simple, so in this case we're simply building a
RESTful API.
The starting boilerplate will look like the following:
from flask import Flask, request, jsonify
from random import randint
from sendgrid import Mail, SendGridClient
app = Flask(__name__)
app.debug = True
tweets = []
#put code here
if __name__ == '__main__':
app.run()
If you notice, Flask contains everything we need out of the box.
The POST endpoint will be used to save our tweets. Quick note, our database for this example is an array--so nothing fancy. On the other hand, the GET where no parameters are included, will return a list of all tweets.
@app.route('/tweet', methods=['POST', 'GET'])
def handle_create():
if request.method == 'POST':
new_tweet = {"id": randint(), "text": request.form['tweet']}
tweets.append(newtweet)
return jsonify(newtweet)
else:
return jsonify({"tweets": tweets})
Now, let's handle tweets individually. Either return a specific tweet (GET),
modify a tweet (PUT), or delete a tweet (DELETE).
@app.route('/tweet/', methods=['PUT', 'GET', 'DELETE'])
def handle_single_tweet(id):
for tweet in tweets:
if tweet['id'] == id:
if request.method == 'GET':
return jsonify(tweet)
elif request.method == 'PUT':
tweet['text'] = request.form('text')
return jsonify(tweet)
else:
removed = tweet
tweets.remove(tweet)
return jsonify(removed)
return jsonify({"error": "Not found"})
Notice this can be organized in a cleaner way, but for the sake of showing everything step by step, I made this a little verbose.
Now we have a way to create, view, edit, and delete tweets! Start playing around! This was initially built for a workshop I’ve been giving as practice for Puerto Rico’s upcoming hackathon,
hackPR. If you want me to drop by and give this workshop for your peeps, I’d be more than glad to do so! Send me a tweet
@elbuo8 and we can sort it out
You can use SendGrid's
Inbound
Parse API to accept incoming email. Why not point it to your Flash application?
Add the following route:
@app.route('/tweet/emailhook', methods=['POST'])
def email_tweet():
new_tweet = {'id': randint(), 'text': request.form['subject']}
tweets.append(new_tweet)
return jsonify(new_tweet)
This will receive a POST request and add the text within the subject to your Twitter clone.
The full source code for this Twitter clone tutorial is
available on GitHub.
For more details about receiving email in Flask applications, see Elmer's tutorial, Collect Inbound Email Using Python and Flask.