
Django vs. Flask - tony
https://www.git-pull.com/code_explorer/django-vs-flask.html
======
ris
So having used both, this is what I tend to say about them: some of Flask's
commonly-used components _are_ better than django's (SQLAlchemy notably), but
altogether, django is a better framework.

I _strongly_ disagree with the notion expressed by some that beginners should
start with flask "to learn how things work". Making a sane and maintainable
project layout is not a particularly easy thing to do, >90% of people (not
just beginners) will generally fuck it up somehow and end up living with a
really weird app initialization routine as a result. Django's project/app
layout and initialization is really quite well considered and I would say
appropriate for 99% of projects. That 1% would probably be better off with
flask.

More broadly, this is the whole opinionated vs. non-opinionated debate, and
I've come to the belief that the vast majority of programmers need the
guidance that an opinionated framework gives. It is said that flask doesn't
try to suggest any particular structure for your project, but I would say that
the effect of that the majority of the time is to produce a project with _no_
structure. Don't get me started on the pattern of `helpers.py` files
everywhere: I mean - what _isn 't_ a helper? What _doesn 't_ fall into that
category? So yeah, just heap everything and god knows what in that file.

It shouldn't be a shock to you by this point if I say that I don't think flask
is particularly well designed either, but I won't go into my interface-by-
interface rant now...

~~~
njharman
I agree about Flash/Django. But SQLAlchemy is definitely not "better". It is
more powerful, more correct, more proper, more flexible. But boy is it a
fucking obtuse, verbose, difficult piece of bahoo to use. Django ORM follows
Django's philosophy of pragmatism. Assume sane defaults/be opinionated. Make
the easy, everyday shit easy! The hard stuff can be figured out later (or just
drop to raw SQL). SQLAlchemy's philosophy is to be correct, like RDBMA
academic correct and proper. Make the insanely rare and/or difficult stuff
possible even if it means making the common stuff a PITA.

It's like the difference between an esoteric and powerful language like
Haskell which is objectively more correct. And Python, which is "who cares
purity, it lets me get shit done fast and easy."

There's also, I think, a huge divide in the way developers think/reason about
problems. Cause I've never seen anyone like both ORMs. Everyone
likes/tolerates one and hates the other. I'm guessing some devs "think" the
way SQLAlchemy works and others "think" the way DjangoORM works.

So, I do think both ORMs have their place. Just wish SQLAlchemy's place was
not in code I have to write/maintain.

~~~
bitexploder
Maybe I have programmer Stockholm syndrome, but SQLA is one of the best ORM in
existence. Period. I have spent a lot of time with it.

I think in terms of Python style and SQL and I think SQLA fits it better than
Django ORM. Django ORM fits Django better. SQLA makes it easy to do OO style
SQL modeling in a very Pythonic way.

I don't hate Django ORM. If I used Django I would use the ORM it comes with.
It is ok. I think data is so important I avoid Django because I think its ORM
becomes the limiting factor for medium or large projects. For small projects,
it hardly matters. Use what you know or has a path of least resistance for
you.

An aside, Pyramid is actually in between Flask and Django, but people often
think it has to be Flask or Django. Pyramid is beautiful and much less
opinionated than Django, but still has some batteries, or rather it supports
several different types of batteries.

Practical programmers don't hate tools IMO. Makes you too vulnerable to
overvaluing your opinion.

~~~
flavio81
To be honest, SQLAlchemy was the single reason I chose to dive more into
Python. I learnt it first because of being curious about it. Then, when I
found SqlAlchemy, I, having had long years of using Hibernate and NHibernate,
thought "if the other Python packages are as good as this one, i should use
Python for serious stuff". Which I did.

SQLAlchemy is damn easy to use.

------
Steeeve
I always saw it as Django is the lady with the 30 pound purse that has
everything you could possibly need on a trip to disneyland and Flask was the
guy who showed up to the camping trip wondering why everybody else brought a
tent when it's so nice out.

~~~
matt_wulfeck
Django is the camper with the U-Haul. Flask is the camper with the backpack.
Bottle is the camper with the fanny pack.

~~~
tedmiston
I wonder how Falcon fits in here.

[http://klen.github.io/py-frameworks-bench/](http://klen.github.io/py-
frameworks-bench/)

~~~
matt_wulfeck
The focus seems to be on performance, so my guess is they're the camper with a
fanny pack but it's already unzipped.

~~~
dguaraglia
Haha, that cracked me up!

------
yen223
I'm working with a large, 5 year old Django codebase. My humble opinion:
Django itself is actively hindering our ability to deliver new features.

Some pain points:

\- Django's fat models approach is bad. By coupling model behaviour to
database schema, it all but guarantees that you're gonna have a tough time
modifying either.

\- Django's class-based views and its admin framework strongly encourages a
sort of "one-view, one-model" approach. Just about nobody has requirements
that neatly fit that worldview. If you need to interact with two models in a
single view, working around it is painful.

\- Not Django specific, but Python is a bad choice to use at scale. The lack
of a good default immutable data structure means we're stuck using mutable
data structures everywhere. In a large codebase, the lack of guarantees around
something as basic as the shape of a data structure is a huge problem. A
notorious example is Django's HttpRequest, whose attributes may or may not be
set by the middlewares.

There are more, but one thing's for sure, I probably won't be using Django for
my next project.

~~~
neospice
What framework or language would you use to write the same codebase with from
scratch?

~~~
__float
Not OP, but as a Python developer with interests elsewhere, I'm very
productive in modern C# with ASP.NET Core MVC. (And I can write it on a Mac
and deploy on Linux, too!)

~~~
hitsurume
What are you using to host the app on linux? I've only worked with ASP.net in
IIS windows hosts and havn't seen an alternative so far.

~~~
dagw
I've only done a few small sites, but just putting my app behind nginx has
worked out fine for me so far.

[https://docs.microsoft.com/en-
us/aspnet/core/publishing/linu...](https://docs.microsoft.com/en-
us/aspnet/core/publishing/linuxproduction)

------
mixmastamyk
Used both and off the bat found Flask breezy and Django bureaucratic. But then
the next day with Flask you look up how to do something elementary like login
(for fsck sakes) and find there's alternatives of various qualities and
scopes, and the flask-security guy has disappeared. Found myself spending a
full week up front wrangling tokens and other crap instead of the project at
hand, sigh. Django starts to shine at that point.

Lately I've been yearning for a "Flango" distribution with flask and the top
twenty extensions supported by a single dev team.

~~~
nZac
Checkout Keg
([https://github.com/level12/keg](https://github.com/level12/keg))

It could use some documentation and some community TLC, but Level 12 is a
solid Python shop with a pragmatic approach to app development. There are
libraries for auth, login, webgrids, SQLAlchemy, forms, etc etc.

Disclaimer: I used to work for Level 12 and wrote a large production app atop
keg.

------
jedberg
I feel like Django has too much magic. I agree that it is easier to get quick
wins with Django, and if you're building a small hobby site or something, then
it's great.

But if you're building something that you hope you'll have to rapidly scale,
Django is going to hurt you. It's way harder to scale due to both its heavy
reliance on hidden magic its tight integration with its data store.

When you want to rapidly scale, the easiest way to do that is if your data
store and application aren't so tightly intertwined that you have to scale
both to solve a bottleneck in either.

~~~
coldtea
> _But if you 're building something that you hope you'll have to rapidly
> scale, Django is going to hurt you. It's way harder to scale due to both its
> heavy reliance on hidden magic its tight integration with its data store._

Considering that Django has 1/5th as much "magic" as Rails, and that Rails
powers some of the biggest websites on the world, I'd say "citation needed".

~~~
Steeeve
What besides reddit?

~~~
brynedwards
There is a list at the bottom of this page:
[https://www.djangoproject.com/start/overview/](https://www.djangoproject.com/start/overview/)

    
    
        Disqus
        Instagram
        Knight Foundation
        MacArthur Foundation
        Mozilla
        National Geographic
        Open Knowledge Foundation
        Pinterest
        Open Stack

~~~
yen223
If the answer here is to be believed, Pinterest has consciously moved _away_
from Django.

[https://www.quora.com/Would-Pinterest-consider-Flask-in-
plac...](https://www.quora.com/Would-Pinterest-consider-Flask-in-place-of-
Django-if-it-were-starting-today)

~~~
coldtea
Yes, but that doesn't matter much, since they got to billion valuations just
fine WITH Django.

------
drawkbox
Flask is still one of my favorites in web frameworks, mainly because it was
from the Sinatra/microframework moment and still is a pleasure to work with.
Just plugin other micro frameworks for the data, middleware, routing,
templating as desired.

Express is similar in Node still because of the simplicity and micro size of
it.

Micro frameworks don't dictate and grow with a product as needed rather than
growing into a monolith and it dictating too much.

As far as Django, it is still one of the most desirable monoliths out there
but you don't have to use it that way. However, it is meant to take over like
Angular, Rails, MVC etc.

------
martin_hnuid
Hmmm. OK. Read through most of this thread. Not sure I agree with some of what
is being said about Django. In particular about this "magic" thing.

It took me a while to get comfortable with Django. I tried to learn it on and
off for about four years. I finally decided the only way to do it was to
focus, commit to it and not jump off into something else until I got it.

That probably took about six months. Much of it felt confusing and, yes,
magical. Until I made one more decision: Read The Source Luke.

Seriously. I started to look things up in Django source code. Every single
time I came across something I did not understand or that seemed magical I
went to source. It was painful at first but it became easier as it turned into
a habit.

And then it happened, one day it just clicked. What seemed like a confusing
mess months earlier made complete sense. It almost felt like this happened
overnight, which wasn't the case.

I now believe the best way to learn Django is to do it exactly this way. Have
the source open on another monitor and look-up everything as you go through a
tutorial or book. In the process you'll discover much more than what you were
looking for originally.

~~~
sirtaj
I find myself doing this more and more often with python libraries, even with
the well-documented ones like Django REST Framework - always keep a source
browser open on the virtualenv dir so I can read library source. There's
something about the style of python documentation that makes it difficult to
really understand how the classes in a library fit together, so this is
necessary for larger python frameworks.

(My personal gold standard for programmer reference documentation has been the
Qt API docs for very, very long. They've varied in quality over the years but
they're always an example of how to do it.)

~~~
ProblemFactory
Reading the source of libraries I'm using has been a real eye-opener for me.
Even from very good documentation you can only learn how to _use_ it, not
learn how to write something similar yourself.

PyCharm is amazing help for it as well. Control-click on a function or class,
and you will jump into its definition in the library source.

~~~
martin_hnuid
I use PyCharm too. Love it.

------
sparkling
I love and use both frameworks on a daily basis.

For tiny applications: go with Flask.

For medium and big applications: it depends.

Flask is great since you can mix and match different parts from the toolbox
and build/use exactly what you want. But it is easy to end up at a point where
you are just rewriting your own mini-Django on top of Flask.

Django on the other hand brings a full meal to the table. Using other toys
from the toolbox is certainly possible, but it feels "wrong". And yes, Django
certainly has some rough/not-so-shiny edges here and there, partly due to
legacy code that cant be easily refactored due to compatibility. But overall
it gets the job done and it gets polished more with every release.

At the end of the day, it comes down to personal preference.

------
ishi
To paraphrase: "Whoever does not know Django, is doomed to reinvent it".

You can use Django with its "batteries included" philosophy. Or you can use
Flask and start adding in lots of extra libraries (which may or may not play
together nicely) to get an ORM, user models, admin site, etc. etc. So you end
up reinventing a full web framework based on Flask.

------
passive
I've done trivial and non-trivial projects in both, and the general summary
presented here feels correct. If you've got something with content, that
matches most common situations (users, content related to users, content
related to other content), Django will get you there quickly and efficiently.

But I still use Flask a lot more, because most of what I create are limited
use web services that do interesting things behind the scenes. Caching proxies
to improve performance of legacy services, script runners, report generation
tools.

Most of the time, Flask feels like the de facto web server, like Requests is
the de facto web client.

------
jaza
For nearly a decade now, Python has been my web project language of choice. I
started out working exclusively with Django, and I still applaud the rock-
solidness and the convenience of Django. However, over the past few years I've
shifted entirely to Flask, and I now code most new projects (no matter what
size) in Flask, whenever I have a choice.

Flask's main strength over Django, in my opinion, is that it does things in a
more modern and a more Pythonic way. The nice "app" object and nice import of
settings in Flask, that lets you instantiate multiple app objects in a single
process, vs the global app / settings in Django. The use of contexts for
exposing requests, sessions, and the like in Flask, vs using arguments and
globals in Django. The breakdown into separate, lightweight, independently-
usable projects for WSGI toolkit, template engine, CLI toolkit, etc in Flask,
vs the monolithic project that is Django.

I have always thought of Flask as the natural and the worthy successor to
Django, in terms of being the gold standard among Python web frameworks.

Yes, Flask's ecosystem is sometimes hit-and-miss in terms of code being well-
maintained and integrating together reliably. But, considering the number of
disparate projects and authors involved, it is actually (in general) quite
stable and it does all work nicely.

In terms of helping to enforce a good code structure, and in terms of bundling
together popular third-party libraries for Flask, there are a number of
utilities that can help. My personal favourite is
[https://github.com/sloria/cookiecutter-
flask](https://github.com/sloria/cookiecutter-flask) , but there are others.

------
jordic
On my next side project will use pyramid next aiohttp or tornado. Python has a
good ecosystem of libs. Pick one when you need it. Django is perhaps the less
pythonic option. After some time doing go and js.. I prefer the lib approach..
on the end you don't need so many things to quickly respond to http requests
;)

~~~
cshenton
Be careful with aiohttp, async io is great, but the actual http parser in
aiohttp is super slow.

See [https://magic.io/blog/uvloop-blazing-fast-python-
networking/](https://magic.io/blog/uvloop-blazing-fast-python-networking/) for
a full write up.

I've been building stuff in sanic, which is built on uvloop and is super fast.
I can recommend it if you're willing to sacrifice a bit of project maturity
for a solid async webserver.

~~~
e12e
I think the most interesting bit about that is that with a re-working of the
http header handling, python could be within spitting distance of "best of
breed" more or less out of the box (using async, not wrapping uvloop).

And also, of course: benchmark first, optimize later.

------
Buetol
Django re-usable apps and admin is the killer feature, making it a breeze to
do 99% of the work on most agencies websites and then the 1% is just tying it
together.

But I'm missing a good abstraction over Django, with most websites features
included (user registration, job runner, webpack integration). Also I've come
to hate django templates DSL so much I'm now only using a non-DSL method[0]
(but it's kinda painful when you want to use apps, making you appreciate
standardization)

[0]: [https://github.com/mdamien/lys](https://github.com/mdamien/lys)

------
mychael
Rule of thumb for Python web development:

Do you already know Django really well? Then use Django for small and big web
projects.

Do you not know either? Then learn Flask for small, trivial applications and
learn Django when you find yourself creating your own web framework on top of
Flask.

------
flavio81
The difference is easy to explain;

You adapt yourself, and your requirements, to Django. Django is "convention
over configuration" which means thar first you need to learn all conventions.
This takes time.

You adapt Flask to your requirements and your preferences. You build Flask to
your liking and needs. Flask is extremely easy to learn.

------
gshulegaard
I think both Django and Flask are good frameworks that solve different
problems. Django has a batteries included philosophy that gets you up and
running quickly without ever leaving Python (as the developer). Flask is
drastically less opinionated and focuses on providing you web hooks to bring
your project/logic to the web letting you do whatever you need behind the
scenes.

Personally, I feel like Django is great for a "traditional" and
straightforward web applications and Flask is better for projects that may
require a bit more flexibility both in modeling and backing services.

I think this line from the article follows this perspective:

> Before long, projects will be dealing with forms, REST endpoints and other
> things that are all best represented via a declarative model with types. The
> exact stance Django’s applications take from the beginning.

------
luord
The first application I worked in from the ground-up is a flask app; quite a
learning experience, to put it lightly. Despite the amount of technical debt
accumulated, however, I don't regret it. I grew a lot as a developer and
became more knowledgeable about web development in general.

I picked flask then because I, rather dogmatically, distrusted Django and its
batteries included approach. Nowadays, I think it's great and almost the
perfect choice to prototype something quickly. That said, if I felt the
application would grow in functionality too much, I'd use Flask. Django gets
in one's way rather quickly.

------
nthcolumn
One of these things is not like the other. You don't have to choose and there
will be cases for both where one is the vastly superior choice. For example:
I'd go with Flask for microservices but django for a CMS. I'm sure some people
will argue the more apposite. The nodejs thing is so fragmented and difficult
by comparison. Flask's routes are better. django's admin absolutely rocks
(still). I guess these face-offs are fun but I don't find them very
informative, relevant or meaningful. A weird hybrid though - now that would be
cool. Or a SAP killer in django.

~~~
cshenton
My apprehension about using flask for microservices is that calls to another
microservices are going to block. With NodeJS, the webserver and http
libraries are async and mature. Python's really missing a solid async requests
library (but async webservers like sanic are getting better).

~~~
nthcolumn
[https://eng.paxos.com/write-fast-apps-using-async-
python-3.6...](https://eng.paxos.com/write-fast-apps-using-async-
python-3.6-and-redis)

What do you think?

------
timwaagh
I worked with flask once. It was code made by an obviously gifted russian
coder i worked with. Cleanest webcode i have seen. I never played with django,
all i can say is flask can produce really clean code.

~~~
zanny
Python in general does this. Its designed to be readable first in most
regards, something really valuable for other languages to learn - for every
line written, it will probably be read dozens of times. Optimizing for the
writing part with arcane or convoluted syntax at the expense of legibility
only makes projects age poorly.

------
welder
Once upon a time I made this short worksheet you can use when deciding to use
Flask or Django:

[https://wakatime.com/django-vs-flask-worksheet](https://wakatime.com/django-
vs-flask-worksheet)

With a comparison between the two:

[https://wakatime.com/blog/14-pirates-use-flask-the-navy-
uses...](https://wakatime.com/blog/14-pirates-use-flask-the-navy-uses-django)

Your guide is way more comprehensive, so mind if I link to it?

------
osullivj
No mention of web sockets or asynchrony? Fifteen years ago I was coding
against Zope. I've used Django a fair bit too. Both were heavyweight, blot-
out-the-sun one-way-to-do-it. Now I use Tornado because it's lightweight, has
good web socket support and embraces the async style. It's a joy to code
Tornado coroutines with RethinkDB. If you thought Twisted was cool, but
couldn't hack the learning curve, Tornado is the answer.

------
smoe
I like both of them a lot for different reasons:

If I build a more generic web application that will include most of their
typical features I'd go with Django. If it is more of an one purpose API type
of project or solving a very domain specific problem it would be Flask.

Django gets your out of the door quickly and there are extensions for anything
I've ever needed, but it can get in your way later on. If you have to go
against its opinions or if you need to actually understand what it does under
the hood. E.g. file upload goes trough several hundreds of lines of code if I
remember correctly. Most of it probably doesn't apply to your project, but you
need to understand it anyway.

Flask projects are also super quick for simple projects, but if it is
something more elaborate you really have to spent the extra time setup the
architecture accordingly from the get go, otherwise it very easily becomes a
big unmaintainable mess.

My experience is mostly b2b products and projects, so scalability is less of
an issue for me.

~~~
cshenton
I've found falcon a real pleasure to work with building pure json APIs, super
sane approach to hooks and middleware which makes handling auth and db pooling
both explicit and simple. Plus it's pretty fast which is always nice for
building a REST API.

------
acconrad
Seems to me that an accurate analogy is Rails:Django::Sinatra:Flask

------
suvelx
I'm a big fan of flask, purely because there's no wrangling `request` objects
down your stack, and you can just fish it out later when you need it.

My main complaint would be Flask's 'extensions'. I'm really not a fan of the

> app = Flask(__name__) > db = Database(app)

pattern. it makes getting your db back later a little trickier. It would be
nice if the `Flask` instance held it for you, so you could get it back with
`flask.current_app` later.

It further doesn't work when the plugin provides a sets of views (i.e. CRUD)
e.g.

> app = Flask(__name__) > crud = CrudPlugin(app)

I've yet to see a case of why this isn't implemented as a blueprint.

~~~
keosak
Extensions can register themselves with the Flask application object, so you
can look there: current_app.extensions['whatever']. However, it is not
specified what exactly this dictionary contains, so eg. SQLAlchemy puts a
custom State class there. You can still get the extension object out of it,
it's just that there is no common convention.

[http://flask.pocoo.org/docs/0.12/api/#flask.Flask.extensions](http://flask.pocoo.org/docs/0.12/api/#flask.Flask.extensions)

[https://github.com/mitsuhiko/flask-
sqlalchemy/blob/master/fl...](https://github.com/mitsuhiko/flask-
sqlalchemy/blob/master/flask_sqlalchemy/__init__.py#L608)

------
smaili
For the python web folks, what web server do you tend to put in front of your
Django/Flask apps and how do you typically deploy new updates with zero
downtime?

~~~
mundanevoice
Nginx + Gunicorn is what we use. It has worked great for us. We have also
tried uWSGI, a waitress for our production and Nginx + Gunicorn have been sure
shot winners in terms of scalability and performance.

This is our gunicorn.conf that ensures gunicorn does not cause memory leaks

    
    
        import multiprocessing
        import os
        import random
        from getenv import env
    
        def pre_fork(server, worker):
           f = '/tmp/app-initialized'
           open(f, 'w').close()
    
        bind = 'unix:///tmp/nginx.socket'
        workers = os.environ.get('WEB_CONCURRENCY', 
        (multiprocessing.cpu_count() * 1 - 1))
    
        MAX_GUNICORN_REQUESTS = env('MAX_GUNICORN_REQUESTS', 100)
    
        if MAX_GUNICORN_REQUESTS:
           max_requests = MAX_GUNICORN_REQUESTS
    
        MAX_REQUESTS_JITTER = env('MAX_REQUESTS_JITTER', 25)
    
        if MAX_REQUESTS_JITTER:
            max_requests_jitter = env('MAX_REQUESTS_JITTER', 25)

------
gejjaxxita
One thing I'm surprised hasn't been mentioned much is the Django Rest
Framework (DRF). If you're building a CRUD-heavy website with very separate
back and frontend (no django templates) then the fact that DRF can give you a
big hyperlinked REST API for free is something I've found extremely useful.

I tend to use Django for big websites and Flask for small
websites/microservice APIs.

------
stanislavb
And here they are some specific numbers on the topic of "Django" VS "Flask"
[https://python.libhunt.com/project/django/vs/flask](https://python.libhunt.com/project/django/vs/flask)
. Flask is supposed to have a better code base?

------
guftagu
Offtopic but does anyone know of a Django alternative in JavaScript with
similar level of maturity?

~~~
luord
If you mean in the frontend, AngularJS was going in that direction. Then react
came along and the angular developers decided to copy it, in a different
language and with even more boilerplate.

I believe nowadays it's ember the one that comes with batteries included, but
I haven't used it nor read a lot about it so don't quote me on that.

If you meant the backend, the only one I always hear about is express, but I'm
not sure about that one either.

------
chintanjoshi
If a newbie looks into this I would say this : Flask :- Magic Django :- More
Magic

P.S. : Great work making a comparison of both, must have been >48 Hours of
work. Take a bow sir.

------
Dowwie
Use Pyramid.

------
BuckRogers
I'm surprised to see a Django vs Flask blog on the frontpage of HN in 2017. So
many of us ditched Python for greener pastures as the dev team lost focus on
the Zen of Python in recent iterations. I definitely wouldn't start a new
webdev project in Python today, even though I used to love it. There are just
faster, more convenient alternatives. I've moved all my projects to TypeScript
and a lot of people moved to Go.

~~~
Dowwie
I am interested in your story. Concrete examples would be helpful. Did the
team follow a performance improvement mandate, analyzing the Python system and
then deciding how best to proceed, or was performance not the primary
motivator?

~~~
BuckRogers
Both. It was loss of faith in the Python BDFL and core dev team, and also an
examination of performance and reliability. Running on V8 and having type
safety is a sweet spot that I haven't found elsewhere. Primary motivator was
that Python has been creaking along for a while now, with a precarious future
and there was finally a clear spot of greener grass to move to.

------
int_19h
For the "keep it simple" camp, I wonder why Bottle isn't more popular.

------
brango
If you need user authentication use django. If it's for APIs use flask or
gRPC.

~~~
CuriouslyC
I found Flask-user to be pain free. This is important because almost all
applications need some form of persistent user data.

At this point I wouldn't use suggest Django for anything other than a
straightforward server-rendered crud app, particularly if the developers are
less skilled.

