Flask Restful: Project Structure

There are many different ways to organize your Flask-RESTful app, but here we’ll describe one that scales pretty well with larger apps and maintains a nice level organization.

The basic idea is to split your app into three main parts: the routes, the resources, and any common infrastructure.

Here’s an example directory structure:

myapi/
    __init__.py
    app.py          # this file contains your app and routes
    resources/
        __init__.py
        foo.py      # contains logic for /Foo
        bar.py      # contains logic for /Bar
    common/
        __init__.py
        util.py     # just some common infrastructure

The common directory would probably just contain a set of helper functions to fulfill common needs across your application. It could also contain, for example, any custom input/output types your resources need to get the job done.

In the resource files, you just have your resource objects. So here’s what <span class="pre">foo.py</span> might look like:

from flask_restful import Resource

class Foo(Resource):
    def get(self):
        pass
    def post(self):
        pass

The key to this setup lies in <span class="pre">app.py</span>:

from flask import Flask
from flask_restful import Api
from myapi.resources.foo import Foo
from myapi.resources.bar import Bar
from myapi.resources.baz import Baz

app = Flask(__name__)
api = Api(app)

api.add_resource(Foo, '/Foo', '/Foo/<string:id>')
api.add_resource(Bar, '/Bar', '/Bar/<string:id>')
api.add_resource(Baz, '/Baz', '/Baz/<string:id>')

Python Envelope: Mailing for human beings.

Envelopes is a wrapper for Python’s email and smtplib modules. It aims to make working with outgoing e-mail in Python simple and fun.

 

from envelopes import Envelope, GMailSMTP

envelope = Envelope(
    from_addr=(u'from@example.com', u'From Example'),
    to_addr=(u'to@example.com', u'To Example'),
    subject=u'Envelopes demo',
    text_body=u"I'm a helicopter!"
)
envelope.add_attachment('/Users/bilbo/Pictures/helicopter.jpg')

# Send the envelope using an ad-hoc connection...
envelope.send('smtp.googlemail.com', login='from@example.com',
              password='password', tls=True)

# Or send the envelope using a shared GMail connection...
gmail = GMailSMTP('from@example.com', 'password')
gmail.send(envelope)