Hacker News new | past | comments | ask | show | jobs | submit login
Building websites in Python with Flask (maximebf.com)
276 points by dabent on Oct 11, 2012 | hide | past | favorite | 56 comments



Great tutorial, a good level of detail too.

The only other thing i'd mention for Flask newbies would be the excellent debugger facility in Werkzeug (effectively a part of Flask).

I lied, one more reference - the guy that wrote flask (bit of a genius, also has a bunch of other excellent libraries) has shared slides from some talks he's given, they're really worth a read too: http://lucumr.pocoo.org/talks/

Bucket list 2013, attend a talk by Armin Ronacher.


Yes, the interactive debugger in Werkzeug[1] is fantastic! I couldn't tell you how many times I've deliberately put "asdf.asdf" in a method to deliberately throw an exception so that I can play around inside the debugger.

One more Flask thing: Flask-Login[2] is a popular way of managing sessions.

1. Werkzeug is the WSGI utility library upon which Flask is built. If you do enough stuff in Flask, you'll probably end up learning something about it, which is okay, because the documentation — like Flask's — is excellent.

2. http://packages.python.org/Flask-Login/


Stick this in your app and you can call the debugger however you wish by customizing the function name, and it will only throw in debugger mode (in case you forget it):

  from flask import current_app

  def asdf():
      assert current_app.debug == False, "You just called debug!"


I wish more people would contribute information on using Flask at a larger scale. Everyone and their brother has written a basic tutorial outlining how to get up and running with Flask. This is a GREAT post and I do not want to demean it ... however I think that a lot of this can be gleaned from following along with the docs and experimenting with Flask in general.

I'd really love to see/hear some stories of others using Flask at a slightly larger scale. For example ... did your startup build their REST API in Flask? Sure, people say it's possible and outline a basic hello-world style REST app ... but in my experience it became a pain in the ass very quick. Primarily because no structure is enforced.

After being a Python dev for a long time, building quite a few big Django apps and a handful of tiny Flask apps I have finally jumped ship to Rails. I spent a week experimenting with various Pythonic combinations. Ultimately I had to ask myself ... "Why am I doing this? What the hell am I wasting my time with this lightweight framework?" I've built my current REST API in Rails and would not have it any other way. It's been tremendously efficient and performs great on my little Linode in London + PostgreSQL.


Having no structure enforced is also a good thing. It allows you to get into and work on the project faster without having to set up all your boilerplates that Django comes with.

Flask apps are supposed to be tiny. I personally use three different stacks for different things: web.py for larger projects, flask for midsized projects and bottlepy for really quick and dirty stateless projects


The author, emixam, is going to go deeper in the next part of the series. If I'm not mistaken, he'll show us the 'blueprints' concept - which I've understood is basically what "everone" who've contiuned developing their Flask code - starts using and keeps using.

So it's coming, hold on! :-)

On another note, I'd recommend that you check out my good pal Kenneth's link (also a comment to your comment).

And on a seperate note, I'd recommend watching "Diving into Flask - Head on" from EuroPython 2012: http://www.youtube.com/watch?v=5twaatBqmjE

It's basically a talk about a company that rewrote their current PHP site and took on Python and Flask - kept at it and banged out something pretty advanced. I liked watching it. I hope you do too.


I know Python well but don't know Ruby. I'd like to start building serious Web apps and would love to hear why you like RoR more than any of the Python frameworks. I am under the impression that though there are more people who know Python than Ruby, yet more Web dev is done with RoR than all of Python combined, and I'm curious why. What is it that is so attractive about Rails? And with Rails having been the #1 reason for people to learn Ruby for years now, why is there no parallel Python on Rails?


The trouble is, larger apps are logical extensions of smaller apps in Flask. I find it rather pleasant to use Flask to build large RESTful APIs, but I don't find there to be any interesting challenges or insights that would make it worthwhile to produce an article relating the experience. I'm afraid it's the same way for many people I know who are using Flask to build large APIs at their companies - the process is so predictably boring that I doubt any of them have even considered writing about it.



A good tutorial, but it was missing any mention of blueprints, which are essential to building a Flask site larger than a few endpoints. Blueprints also allow you to reuse components across multiple apps, or as releasing a set of endpoints as open source libraries that can be easily plugged into other apps.

Edit: adding a link to Blueprints in the Flask docs: http://flask.pocoo.org/docs/blueprints/


I'm the author of the article. I plan to write another full tutorial on blueprints. I use them a lot but I already found this post long enough :)


Great, looking forward to it. I love Flask, and am working on a backend site built on top of it (http://woventheapp.com) -- the more people we can get knowledgeable about it, the better!


Good read. I wrote a similar Flask introductory article[0] on how I moved my Wordpress site/blog over to Flask. The source code of my site can be viewed on github[1].

[0]: http://vertstudios.com/blog/new-flask-site/ [1]: https://github.com/joequery/Vert-Flask


Great little tutorial but I'd also like to mention that if you're creating websites using flask make sure to check out blueprints (http://flask.pocoo.org/docs/blueprints/) it lets you modualize your website and make it a lot more manageable once your code gets a little bit larger.


Second that and would go as far as to say that if you're doing anything other than a tiny tiny micro site, you should default to using them. They're easy to use, come with no downside (that I'm aware of) and the modularity benefit is huge.


Great tutorial.

Since you're already using backbone.js why not plug in CSRF protection with Flask-SeaSurf? (http://flask.pocoo.org/extensions/)

If you use this backbone.js change then CSRF is practically invisible: https://github.com/alanhamlett/backbone/commit/91941afe693ae...

Also, if building an api with Flask make sure you use blueprints with a url prefix so your api routes become relative, which means less typing: http://flask.pocoo.org/docs/blueprints/


Flask is so damn awesome! For all those other projects Django seems too big, I use Flask. The hardest thing for me was finding a project structure that worked for me. I still haven't landed one that was "perfect". What project structure/skeletons for Flask apps work for you?


Going big? Blueprints.

http://flask.pocoo.org/docs/blueprints/

Going small? Put everything in one folder.

app = Flask(__name__, static_folder='.', static_url_path='', template_folder='')


I'm using blueprints too which are great to organize your app as modules. I plan to write another tutorial on that


Flask is awesome and I'd strongly recommend it to anyone curious about doing webdev in python.

When I was starting out, I found the source code to the Flask website itself really helpful for getting to grips with the basics: https://github.com/mitsuhiko/flask/tree/website/flask_websit...


Agreed. If you want to read some well-written Python, take a look at the Flask source code. It is the embodiment of Pythonic.


I just cannot thank you enough - you are a life saver. Coming from Java world I was looking for exactly like this. Maybe I'm new to Python, I was just about to give up. Setting Nginx/Apache for Flask was giving me nightmares -just could not get it right to play with gunicorn, uwsgi and so on.

I know Java is verbose but the tooling is good. Just put you war(a pre-defined structure) in Tomcat webapps dir and your good to go with a fairly scalable web site. I was so surprised it wasn’t that easy for Python. I think it stems out that Python is more of systemish kinda ecosystem.


If you're experienced in Java, have you taken a look at the Play Framework?

http://playframework.org


Thanks. I tried Scala but got a bit scared :-) I chose Clojure as the next step from Java. But that doesn't exclude Scala by any means - it's just about time that I play with it as I've heard it isn't that complex as people think of it.


Good stuff! Just a question, in the first session example, should the url_for('say_hello') be url_for('message')? And in the message template, 'index' maybe should be 'home'.


Yeah I'm going to fix that. I published the article too early by mistake with a few errors still left


No problem! Thanks for writing this.


I've always wondered why people who like using these python micro frameworks don't use App Engine. Have any of you guys tried out GAE and decided it wasn't worth it?


I mostly use Flask to create handy status dashboards and debugging tools for servers that do other things. It's a nice use pattern: you want to expose some of the internals of a server over a firewalled-off port, so you whip up a few HTTP endpoints in Flask, start an HTTP server in a background thread, and declare victory. It's quick and easy, and can save huge amounts of time later when you're trying to figure out why something isn't quite working.

There are other reasons to avoid GAE -- price, datastore latency, lack of flexibility -- but my main one is that GAE just doesn't apply to most of the things I use Flask for.


Same here. I've used Flask for an internal "database cloner". It's ridiculously easy to get it up and running.


One thing I personally realised is that App Engine is absolutely fantastic for my needs, but as soon as my sites are outside of the free quota the costs rise extremely fast almost putting them out of price range before they even got started.

The other thing for me is that I have now spent time and invested hours into learning the App Engine platform but I get almost nothing in return since moving requires me to re-write or re-learn other tools anyway.

Unless I was a 100% committed to App Engine I don't want to launch a new project on top of it.


I'm definitely toward the novice end of the spectrum, but GAE scares me with how tightly coupled you can get to it, especially if you use libraries they provide.

It took a while, but I really like Heroku's workflow so far and I feel like I have to jump through a lot less hoops. For me, it's the perfect middle ground between buying and admining some ubuntu VM somewhere and GAE's deploy and hope it works style.


I was a big user of appengine in the last couple of years but have slowly moved off for cost reasons. It is a great service getting started, and scaled amazingly, but as the userbase grew, the cost became too much. There are certainly ways to mitigate it but for me it was not worth the extra time investment when it was mostly my side projects causing the problems.


GAE's working very well for me, i use flask on GAE.

I'm still bemused at how much of a free quota you get on GAE. I've had days with a few thousand hits, that doesn't even take any of my daily quotas above 35%.


No need to have to choose there -- you've been able to run Flask on AppEngine for some time now.


Apples and cucumbers. GAE is a platform as a service; Flask is a framework that can be deployed anywhere.

Unless I'm wrong about GAE...


You're not. Also of note is that you could simply choose to run Flask on GAE.


For those working on GAE, try this handy template: https://github.com/kamalgill/flask-appengine-template


good read. I am working on something built in scratch using Flask and so far, it has been a breeze in understanding the document, source code and samples provided on the pocoo site.


See also bottle http://bottlepy.org/docs/dev/

Both are great but I find them very slow.


You can't just use Flask straight out of the box. You need to put it on something. I've used Gunicorn with Gevent and it runs as fast as I need it to run. Gevent with Nginx as a reverse proxy play very well together and the responsiveness is more about how you're managing your DB queries rather than rendering the site. (I shy away from ORMs for this reason but still use sqlalchemy.)


Could you explain?


Slow relative to what? Based on what?


what an amazing tutorial!


Nicely done. I'm a Ruby/Sintra bod myself, but now I'm keen to play with Flask a bit - thanks!


Thanks for the tutorial. Can't wait for the next part about blueprints!


what's the difference between Flask and Django?


Django follows Python's philosphy of "batteries included". In particular, it uses its own ORM. It also has a large ecosystem of pluggable apps, whether contrib modules or outside the Django tree.

Flask is a microframework. It lets you build your website in a single file if that's what you need, or scale up to multiple files/sub-websites if your website is more complex. It doesn't have its own ORM, but it's very easy to use SQLAlchemy (the best ORM/SQL abstraction framework out there, IMHO). Its templating engine (Jinja2) is superior to Django's. On the other hand, the list of plugins available is smaller than Django's.

Both have very good documentation.


Django's a huge, monolithic framework that you need to run a script for that generates some files and a folder strucutre.

Flask is a microframework. You can create a flask app contained entirely in one file, or on spanning several. It requires a minimum of configuration to work.


> Django's a huge, monolithic framework

I'd like that misconception to finally be dispelled. In spite of being installed as an apparently single entity, Django is modular. You can use SQLAlchemy and Jinja2 with Django, and you can use Django's ORM all by itself, or its templating system standalone. You can use Django without manage.py, and while the only actual requirement is settings.py, that is in the process of being done with.


Good tutorial. You should check out Django. It comes with most of the script you have written plus a lot more and a really active community.


I learned on Django but have turned to Flask for my smaller projects after wrestling too many times with Django's poor handling of static files during development.


Any opinions about Flask vs Bottle?



So you took flask documentation, some other sources and made it into a blog post about it?


Why is that a problem?




Consider applying for YC's Spring batch! Applications are open till Feb 11.

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

Search: