Hacker News new | past | comments | ask | show | jobs | submit login
How I Structure My Flask Applications (mattupstate.com)
266 points by llambda on June 26, 2013 | hide | past | web | favorite | 46 comments

A couple other things I'd add to this good article:

- I took a couple of good things from Django's manage.py by using Flask-Script. It looks like [1]

- I'm not sure if there's a better way of doing this, but I really want to be able to swap out configurations based on which environment I'm using. I think I've forced some Django structure onto Flask, but that said, I dynamically load in a `settings` object and use that to configure my `app` object. I use something like [2]. Just looking over it again I think I have some extraneous code in there but I'm tired. It works pretty well, so far.

- Flask-SQLAlchemy has some good stuff too but I'm not entirely sold on using it. I'm using it on one project, but not the other. I don't miss it when I don't have it.

1. https://gist.github.com/mattdeboard/5872584

2. https://gist.github.com/mattdeboard/3cbe5395052128e60328

Good call on the Flask-Script mention. I will add a note about that.

As far as configuration based on environment goes, I really dislike environment based configuration in my project repository. So I use Flask's instance folder functionality:


This file can be used to configure the app based on its environment wether it be local development or my production environment. The shared factory method attempts to load this file and fails silently if it does not exist.

Regarding your SQLAlchemy comment, well...thats just not really something to add to the article now, is it? ;)

Yeah but how would this solve having identical app installations in dev, prod and staging?

The settings.cfg file that I place in the instance folder is generally placed on the server during deployment. Any values in this file will override defaults. I generally do this with Chef or Fabric. Perhaps that answers your question

Not sold on using it? What are the reasons?

Well, I just haven't had a TON of use for it yet. I'm a little wary that I'll need to work around leaky abstractions. I'm not poo-pooing it, just ... cynical.

Flask-SQLAlchemy is a thin layer over SQLAlchemy, so the risk of leakage is low. That said, what I don't like is that it's too coupled with Flask, so I prefer to use my own version: https://github.com/lucuma/orm

Nice, thanks for the link. I'll look into this next week.

Thanks for the mention! If anyone has further questions I'd be happy to answer them here, or in the comments of the article itself.

Enjoyed reading through the approach you take and I'll spend some time reading through the code tomorrow to see how it all fits together. It's surprisingly infrequent that an article pops up describing the thought process behind using a specific structure for your code - thanks for taking the time to write it up.

One thing I've done differently on my last couple of projects is to put the core parts of the app into their own packages at the top level and to make a 'web' package that just contains the web interface and the config. That way I make sure that the core application code isn't bound to the web framework at all. Then within my web blueprints they import the bits of the core library they need to do their work. I can then use the main bit of the library myself without having anything to do with the flask app.

The web app itself is responsible for creating a db connection and then injecting that into the core when needed. I've made a simple gateway class that wraps the db connection and deals with persistence.

The data layer is the bit I'm least happy with. Mostly that's because I went with a nosql solution for the db which ultimately has made the data model more complex than it needs to be. Tomorrow I'm going to experiment with switching to SQLAlchemy again to see how that effects things.

Definitely not saying it's the right way to do things but it's another take on how you can structure things and it's been working really well for me. Feels like you're writing an application first and a website second - which changes how you think about the code.

I hear you on the "core" library idea. I have strived for this separation before with varying success. I just did not feel as if I wanted to go that far with this article.

Thanks for sharing this, it's always nice to hear how other people are set up. Out of curiosity, how do you serve your static files?

With Nginx as a reverse proxy whenever possible.

Have there been any recent rumblings on #pocoo on extension approval?

It'd be great to see Flask-Security gain more prominence (after you change the default away from plaintext of course :)

It's only plaintext by default to get up and running as fast as possible, which is why I wrote the extension in the first place. Armin has, on occasion, expressed interest in improving the extension ecosystem but nothing specific yet.

I didn't even manage to change it. Tried all three values for SECURITY_PASSWORD_HASH mentioned in the docs and nothing worked (i.e. still plain text).

This was just a test project of mine so I used the settings like this (in my app.py file):

    SECURITY_PASSWORD_HASH = 'pbkdf2_sha512'
    app = Flask(__name__)

If you set the password hash type to something other than plaintext you also need to set the `SECURITY_PASSWORD_SALT` configuration option.

This is great. As a recently new Python and Flask user it's good to see how things are done in a nicer way than I have hacked together!

Question: I have a web app built in flask, but I also require a worker process in the background that is actively scraping websites and inserting/ updating data into the DB via the ORM. How would you go about that in the cleanest way?

You could use Celery: http://www.celeryproject.org/

I like and use Flask, but as to how to structure it, I always end up mirroring a classic Django structure: views, models, forms, utils, static, templates etc. About the only thing missing is urls and admin.

It works, and it's easier for me to organize projects according to a common standard.

Flask-Admin (http://flask-admin.readthedocs.org) will cover you on the admin area to a certain degree.

As a newbie to web frameworks, I found Flask was much easier to deploy and I understood what was happening compared to Django. I also found the documentation and support better than that of Tornado and cherryPy.

Great article, but the best take away for me.. Alembic, awesome! I'd just started to write something myself (poorly)

Just use django bro

> Just use django bro

I would be fascinated to read your rationale for just using Django. Specifically I'm curious what use-cases you see as Django having an advantage in? (Specific examples make for a much more interesting dialogue.) In relation to this, do you think there are contrasting use-cases where Flask might excel as a more suitable option? Personally, I do not favor Flask or Django or <insert web application suite here> exclusively; instead I evaluate a use-case and then determine which tool best fits my needs. However, it would be amazing if you could somehow show that "just use django" is axiomatic to web development in Python...

Indeed, I'd be curious as well to hear about why someone should use Django. I initially started using Flask because it is the lightest framework I could find in terms of dependencies, boilerplate, and mental-modeling. Additionally, it had EXCELLENT documentation for everything, from the super newbie (me) to the more seasoned expert.

Since then I've yet to run into a case where I want a lot more than what Flask offers. However, If there's something better that I just don't know about, I'd love to hear about it!

I've used both Flask and Django more or less extensively: generally I like to start out in Flask and move to Django if necessary, as opposed to the other way around.

The three big things I think Django has over Flask:


- Django-admin

- A stronger ecosystem

(But of course, none of these are entirely absent from Flask -- its not as if its particularly difficult to plug in SQLAlchemy, and I believe there's a Flask-admin package nowadays.)

My general advice is that if you feel like the thing you're developing is going to turn into a CRUD app, use Django.

I don't think the ORM concern is valid - SQLAlchemy is probably the best ORM available for python and you can drop it straight in to your flask app.

As you say, it really depends on your use-case. I wrote a number of crud apps in Django in a previous life (when Django was still fairly young). I found that out of the box you could get something set up quickly but trying to bend it to your (or the clients) will sometimes required a lot of work. I remember at one point having to duplicate a huge chunk of code into one of my models. That's the tradeoff you'll always run into. You'll get a really complete system for free but it won't be as flexible as you may one day need it to be.

Agreed on both counts. (I don't use SQLAlchemy nearly as much as I should, and I'm often reminded of that fact.)

I believe Flask actually has the advantage in the ORM since you aren't tied to Django's strictly RDBMS structure and Flask will allow you to easily use NoSQL solutions if that's your thing. Flask with SQLAlchemy is just as powerful as Django's ORM.

Flask does have an admin plugin but it's nowhere near as good, polished, or documented as Django's.

Django does have the advantage of a bigger mind share, users and ecosystems.

> Flask with SQLAlchemy is just as powerful as Django's ORM.

sqlalchemy is more powerful than django orm.

> I believe Flask actually has the advantage in the ORM since you aren't tied to Django's strictly RDBMS structure and Flask will allow you to easily use NoSQL solutions if that's your thing

easy there. you can as well use nosql with django (orm is useless then, by definition) and you are in the same exact situation as using nosql engines with flask. if you get rid of the orm in django (which is doable), you are just bringing your own batteries here, just as you are bringing them to flask.

"Flask will allow you to easily use NoSQL solutions if that's your thing"

Agreed - we normally use flask alongside psycopg2 and postgres but recently we've been using it with NEO4J for fun


Use Django when you're an agency making a finite delivery to a client. :)

Edit: on a serious note, use it when all the dependencies it comes with matches what you exactly need. Once you're down the path of swapping something out, all the third-party apps/packages (one of the key features) become useless. This becomes problematic when you start to use something like MongoDB and end up having to write a lot of code on your own.

> Use Django when you're an agency making a finite delivery to a client. :)

or when the client is dictating the tech stack. :)

What about Flask vs. CherryPy?

> I'm curious what use-cases you see as Django having an advantage in?

My primary use case involves having a webapp that actually works

Let's just ignore him. He's trolling.

Whereas, in your vast experience, you found that Flask webapps don't work?

In production

Whereas -- not where.

And I was being sarcastic.

Django is a great framework, but it has always struck me as Python's answer to Ruby-on-Rails. Very structured.

Flask is literally a 5-minute ad hoc content management system with all the power to take on massive tasks. The "micro-framework" label is an understatement.

I also think Armin's style is quite elegant and I've learned a lot more about the language just from reading Flask source.

How is Flask a "content management system"? I thought it was a fairly small set of utilities for writing web applications, aka a microframework. A CMS is a program/app for publishing and editing web pages or blogs, is it not?

Flask is a framework for writing applications. You can build whatever. I've used it for blog engines, geospatial models, and much more. A CMS is exactly as you say: a system for managing content.

Switching to Flask from Django was like switching to Slackware from Mandrake (back in the day...). For the first time I was actually learning the system I was using.

I hear you there. Flask's code base is really easy to get into if you're curious how things work under the hood.

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact