background preloader

The Flask Mega-Tutorial, Part I: Hello, World!

The Flask Mega-Tutorial, Part I: Hello, World!
This is the first article in a series where I will be documenting my experience writing web applications in Python using the Flask microframework. NOTE: This article was revised in September 2014 to be in sync with current versions of Python and Flask. Here is an index of all the articles in the series that have been published to date: My background I'm a software engineer with double digit years of experience developing complex applications in several languages. In addition to Python, I've written web apps in PHP, Ruby, Smalltalk and believe it or not, also in C++. UPDATE: I have written a book titled "Flask Web Development", published in 2014 by O'Reilly Media. The application The application I'm going to develop as part of this tutorial is a decently featured microblogging server that I decided to call microblog. These are some of the topics I will cover as we make progress with this project: So as you see, I'm going pretty much for the whole thing. Requirements Installing Flask #! . Miguel Related:  trenchmortar1

Building websites in Python with Flask | Tech & statup blog by maximebf For some times now, I have been doing some projects in Python and some were web applications. Flask is a small framework to do exactly that and I have found it perfect for the job. It’s really easy to use, fast, has good documentation and a good community. This is the first post in a series dedicated to building websites with Python and more notably Flask. First steps with Flask I use pip to install Python modules and I would strongly recommend it (as well as using virtualenv).Installing Flask is as easy as: pip install Flask Flask has an excellent quickstart tutorial so I will only do a quick overview of the basics. As a framework, Flask is similar to Sinatra in Ruby or Slim in PHP. from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' In this example taken from Flask’s quickstart tutorial, app is our application object and is used to map the hello_world() function to the path /. app.run() starts the built-in web server on port 5000. <! #! $ .

Python Flask and jQuery Ajax POST I have already covered an introductory article on getting started with python web application development using Python Flask and MySQL. In this tutorial, we'll focus on the client side of the web application. We'll see how to use jQuery AJAX along with Python Flask. Prior to getting started with this tutorial, make sure you have Python installed. You can check if it's installed from the command prompt: python --version If python is installed, it'll show the version of python installed. pip install Flask Now create an app directory called FlaskApp, navigate to it and create app.py with the following code: from flask import Flask app = Flask(__name__) @app.route("/")def hello(): return "Welcome to Python Flask!" The python code shown above is quite self explanatory. First we imported the Flask module and then created a flask app instance. Save the app.py and from terminal run: python app.py Your app must be now running. Let's create a Sign Up page called signUp,html. <!

Getting bigger with Flask | Tech & statup blog by maximebf My last post about creating websites with Flask covered the steps to create a simple application. What happens when it grows bigger? In this post I will take as example a common use case for a web app: a public section (homepage, tour, signup, login) a member only section (the app, user settings) an api Each member will have its own subdomain (ie: if my username is maximebf, I get the maximebf.example.com subdomain). I’ll assume the same file organization as I described in my previous post. Getting modular with Blueprints Flask provides a feature called Blueprints which let your organize your app as modules. I like to create a modules folder in my application directory where all my module files will be stored. example/ modules/ __init__.py public.py member.py api.py To create a module, you initializes a Blueprint object which acts in the same way as the Flask object. Each blueprint can have its own templates folder. I use the same logic for static files. Wildcard subdomains

How to automatically create a form from a model in Flask | Isak Utegard I’ve been playing around a bit with a Python microframework called Flask lately. I like it very much and it’s really simple to get started. You should absolutely check it out if you like Python. I’ve been able to combine Flask with MySQL through Flask-SQLAlchemy and by using Flask-WTF I’ve managed to successfully post data to my database. I’ve tried various approaches where one was this approach where you automatically creates a form from your model like this: from flask import render_template from flask.ext.wtf import Form from wtforms.ext.sqlalchemy.orm import model_form MyForm = model_form(MyModel, base_class=Form) form = MyForm() return render_template('form.html', form=form) I thought that was pretty cool but every column from my database was rendered as an input-field from the HTML template which wasn’t that cool in the end. When this was done there was no problem to iterate over the fields in my HTML template by using this code:

Large app how to · mitsuhiko/flask Wiki This document is an attempt to describe the first step of a large project structure with flask and some basic modules: SQLAlchemyWTForms Please feel free to fix and add your own tips. Installation Flask Flask Installation I recommend using virtualenv: it is easy and allows multiple environments on the same machine and doesn't even require you to have super user rights on the machine (as the libs are locally installed). Flask-SQLAlchemy SQLAlchemy provides an easy and advanced way to serialize your object to different types of relational databases. pip install flask-sqlalchemy More here about the Flask-SQLAlchemy package Flask-WTF WTForms provides an easy way to handle user's data submission. pip install Flask-WTF More here about the Flask-WTF package Overview Ok, so from now, we should have all the libs ready. /config.py /run.py /shell.py /app.db /app/__init__.py /app/constants.py /app/static/ For every module (or sub app... ) we'll have this file structure (here for the users module) Config #! Testing

Facebook Authentication for Flask Apps Ok, it looks like you want to add Facebook login to your Flask app. If you followed my first tutorial on Flask apps, you might have something like this in your app.py: import os from flask import Flask, render_template, send_from_directory #---------------------------------------- # initialization #---------------------------------------- app = Flask(__name__) app.config.update( DEBUG = True, ) #---------------------------------------- # controllers #---------------------------------------- @app.route('/favicon.ico') def favicon(): return send_from_directory(os.path.join(app.root_path, 'static'), 'ico/favicon.ico') @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.route("/") def index(): return render_template('index.html') #---------------------------------------- # launch #---------------------------------------- if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) app.run(host='0.0.0.0', port=port) register your app on Facebook

Structuring flask apps, a how-to for those coming from Django The other day a friend of mine was trying out flask-peewee and he had some questions about the best way to structure his app to avoid triggering circular imports. For someone new to flask, this can be a bit of a puzzler, especially if you're coming from django which automatically imports your modules. In this post I'll walk through how I like to structure my flask apps to avoid circular imports. In my examples I'll be showing how to use "flask-peewee", but the same technique should be applicable for other flask plugins. I'll walk through the modules I commonly use in my apps, then show how to tie them all together and provide a single entrypoint into your app. Project layout I use a structure that may look familiar to users of the django framework: In a little bit I'll get to the reason "main.py" is the secret sauce, for now though I'll focus on the other bits. app.pymodels.pyauth.pyadmin.py / api.pyviews.pymain.py app.py """I keep app.py very thin.""" That's it! models.py auth.py views.py

Lightweight Python Apps with Flask, Bootstrap, and Heroku Welcome! This is a quick start guide for easily and quickly deploying python apps. The goal of this guide is to provide you with a simple, step-by-step flow that you can follow when building small, simple apps from the ground up (which can later turn into large, complex apps). Each technology, including Heroku, Flask, and Twitter Bootstrap, has been carefully chosen to make the process as simple, quick, and painless as possible. Please note that this guide does not explain every step in detail, and assumes you have at some point interacted with either a few of these technologies or related ones. Now for a little introduction about the design decisions made in this quick start guide: Flask is a popular lightweight python framework (or micro-framework), allowing you to develop simple apps extremely quickly. Heroku is above and beyond the best choice for a lone developer or small team, especially considering it is: Alright, now that we've gotten all of that out of the way, let's get started!

Saturday morning hack: a little note-taking app with Flask A couple Saturdays ago I spent the morning hacking together a note-taking app. I'm really pleased with the result, so I thought I'd share the code in case anyone else might find it useful. The note-taking project idea came about out of necessity -- I wanted something that worked well from my phone. While I have a personal wiki site I've used for things like software installation notes or salsa recipes, I've also noticed that because it's so cumbersome to use from my phone, I often end up emailing things to myself. Plus a wiki implies a kind of permanence to the content, making it not a great fit for these impromptu notes. I also like to use markdown to format notes, but markdown isn't too easy on a phone because of the special characters or the need to indent blocks of text. Here is how the app appears on a narrow screen like my phone: And here it is on my laptop: If you'd just like to see the code, here is the multi-file gist. Feature review The tools Setting it up Python code Templates

Python : Bien configurer son environnement de développement C'est quand même plus sympa de développer quand notre environnement de développement est bien configuré ! Ce didacticiel est une introduction à quelques bonnes pratiques qui vous permettront d'avoir un environnement de développement Python aux petits oignons : Travailler avec des environnements virtuels et les associer aux projets,Personnaliser le script de démarrage du shell Python,Valider son code Python,Standardiser l'exécution des tests. Pré-requis Je considère dans ce tutorial que vous avez déjà installé Python > 2.7.9 et > 3.4. Ces versions de Python fournissent par défaut pip qui est un outil permettant de télécharger et d'installer des modules Python depuis le Python Package Index (PyPI). 1. Les environnements virtuels Python permettent d'avoir des installations de Python isolées du système et séparées les unes des autres. Installation de Virtualenv pip install virtualenv Exemple d'utilisation mkdir -p ~/virtualenvs virtualenv ~/virtualenvs/project1 (project1) pip install --upgrade pip

How To Structure Large Flask Applications Introduction There are many methods and conventions for structuring Python web applications. Although certain frameworks are shipped with tools (for scaffolding) to automate -- and ease -- the task (and the headaches), almost all solutions rely on packaging / modularizing applications as the codebase gets distributed [logically] across related files and folders. The minimalist web application development framework Flask, has its own - blueprints. In this DigitalOcean article, we are going to see how to create an application directory, and structure it to work with re-usable components created with Flask's blueprints. Glossary 1. 2. 3. Prepare The Operating SystemSetting up Python, pip and virtualenv 4. Creating Application FolderCreating A Virtual EnvironmentCreating Application FilesInstalling Flask 5. Module BasicsModule Templates 6. Edit run.py using nanoEdit config.py using nano 7. Flask: The Minimalist Application Development Framework Our Choices In This Article Flask-SQLAlchemy Flask-WTF

Related: