Flask Documentation Release 0.13.Dev Jul 31, 2017
Total Page:16
File Type:pdf, Size:1020Kb
Flask Documentation Release 0.13.dev Jul 31, 2017 Contents I User’s Guide1 1 Foreword3 2 Foreword for Experienced Programmers5 3 Installation7 4 Quickstart 11 5 Tutorial 29 6 Templates 45 7 Testing Flask Applications 51 8 Application Errors 59 9 Debugging Application Errors 67 10 Configuration Handling 69 11 Signals 81 12 Pluggable Views 85 13 The Application Context 91 14 The Request Context 95 15 Modular Applications with Blueprints 101 16 Flask Extensions 107 i 17 Command Line Interface 109 18 Development Server 117 19 Working with the Shell 119 20 Patterns for Flask 123 21 Deployment Options 181 22 Becoming Big 195 II API Reference 199 23 API 201 III Additional Notes 277 24 Design Decisions in Flask 279 25 HTML/XHTML FAQ 283 26 Security Considerations 289 27 Unicode in Flask 295 28 Flask Extension Development 299 29 Pocoo Styleguide 307 30 Python 3 Support 313 31 Upgrading to Newer Releases 315 32 Flask Changelog 325 33 License 343 34 How to contribute to Flask 347 ii Part I USER’S GUIDE This part of the documentation, which is mostly prose, begins with some background information about Flask, then focuses on step-by-step instructions for web develop- ment with Flask. 1 2 CHAPTER 1 Foreword Read this before you get started with Flask. This hopefully answers some questions about the purpose and goals of the project, and when you should or should not be using it. What does “micro” mean? “Micro” does not mean that your whole web application has to fit into a single Python file (although it certainly can), nor does it mean that Flask is lacking in functionality. The “micro” in microframework means Flask aims to keep the core simple but exten- sible. Flask won’t make many decisions for you, such as what database to use. Those decisions that it does make, such as what templating engine to use, are easy to change. Everything else is up to you, so that Flask can be everything you need and nothing you don’t. By default, Flask does not include a database abstraction layer, form validation or any- thing else where different libraries already exist that can handle that. Instead, Flask supports extensions to add such functionality to your application as if it was imple- mented in Flask itself. Numerous extensions provide database integration, form val- idation, upload handling, various open authentication technologies, and more. Flask may be “micro”, but it’s ready for production use on a variety of needs. Configuration and Conventions Flask has many configuration values, with sensible defaults, and a few conventions when getting started. By convention, templates and static files are stored in subdi- 3 rectories within the application’s Python source tree, with the names templates and static respectively. While this can be changed, you usually don’t have to, especially when getting started. Growing with Flask Once you have Flask up and running, you’ll find a variety of extensions available in the community to integrate your project for production. The Flask core team reviews extensions and ensures approved extensions do not break with future releases. As your codebase grows, you are free to make the design decisions appropriate for your project. Flask will continue to provide a very simple glue layer to the best that Python has to offer. You can implement advanced patterns in SQLAlchemy or an- other database tool, introduce non-relational data persistence as appropriate, and take advantage of framework-agnostic tools built for WSGI, the Python web interface. Flask includes many hooks to customize its behavior. Should you need more cus- tomization, the Flask class is built for subclassing. If you are interested in that, check out the Becoming Big chapter. If you are curious about the Flask design principles, head over to the section about Design Decisions in Flask. Continue to Installation, the Quickstart, or the Foreword for Experienced Programmers. 4 CHAPTER 2 Foreword for Experienced Programmers Thread-Locals in Flask One of the design decisions in Flask was that simple tasks should be simple; they should not take a lot of code and yet they should not limit you. Because of that, Flask has a few design choices that some people might find surprising or unorthodox. For example, Flask uses thread-local objects internally so that you don’t have to pass ob- jects around from function to function within a request in order to stay threadsafe. This approach is convenient, but requires a valid request context for dependency in- jection or when attempting to reuse code which uses a value pegged to the request. The Flask project is honest about thread-locals, does not hide them, and calls out in the code and documentation where they are used. Develop for the Web with Caution Always keep security in mind when building web applications. If you write a web application, you are probably allowing users to register and leave their data on your server. The users are entrusting you with data. And even if you are the only user that might leave data in your application, you still want that data to be stored securely. Unfortunately, there are many ways the security of a web application can be com- promised. Flask protects you against one of the most common security problems of modern web applications: cross-site scripting (XSS). Unless you deliberately mark in- secure HTML as secure, Flask and the underlying Jinja2 template engine have you covered. But there are many more ways to cause security problems. 5 The documentation will warn you about aspects of web development that require at- tention to security. Some of these security concerns are far more complex than one might think, and we all sometimes underestimate the likelihood that a vulnerability will be exploited - until a clever attacker figures out a way to exploit our applications. And don’t think that your application is not important enough to attract an attacker. Depending on the kind of attack, chances are that automated bots are probing for ways to fill your database with spam, links to malicious software, and the like. Flask is no different from any other framework in that you the developer must build with caution, watching for exploits when building to your requirements. Python 3 Support in Flask Flask, its dependencies, and most Flask extensions all support Python 3. If you want to use Flask with Python 3 have a look at the Python 3 Support page. Continue to Installation or the Quickstart. 6 CHAPTER 3 Installation Python Version We recommend using the latest version of Python 3. Flask supports Python 3.3 and newer, Python 2.6 and newer, and PyPy. Dependencies These distributions will be installed automatically when installing Flask. • Werkzeug implements WSGI, the standard Python interface between applica- tions and servers. • Jinja is a template language that renders the pages your application serves. • MarkupSafe comes with Jinja. It escapes untrusted input when rendering tem- plates to avoid injection attacks. • ItsDangerous securely signs data to ensure its integrity. This is used to protect Flask’s session cookie. • Click is a framework for writing command line applications. It provides the flask command and allows adding custom management commands. 7 Optional dependencies These distributions will not be installed automatically. Flask will detect and use them if you install them. • Blinker provides support for Signals. • SimpleJSON is a fast JSON implementation that is compatible with Python’s json module. It is preferred for JSON operations if it is installed. • python-dotenv enables support for Loading Environment Variables From .env Files when running flask commands. Virtual environments Use a virtual environment to manage the dependencies for your project, both in de- velopment and in production. What problem does a virtual environment solve? The more Python projects you have, the more likely it is that you need to work with different versions of Python libraries, or even Python itself. Newer versions of libraries for one project can break compatibility in another project. Virtual environments are independent groups of Python libraries, one for each project. Packages installed for one project will not affect other projects or the operating sys- tem’s packages. Python 3 comes bundled with the venv module to create virtual environments. If you’re using a modern version of Python, you can continue on to the next section. If you’re using Python 2, see Install virtualenv first. Create an environment Create a project folder and a venv folder within: mkdir myproject cd myproject python3 -m venv venv On Windows: py -3 -m venv venv If you needed to install virtualenv because you are on an older version of Python, use the following command instead: virtualenv venv On Windows: 8 \Python27\Scripts\virtualenv.exe venv Activate the environment Before you work on your project, activate the corresponding environment: . venv/bin/activate On Windows: venv\Scripts\activate Your shell prompt will change to show the name of the activated environment. Install Flask Within the activated environment, use the following command to install Flask: pip install Flask Living on the edge If you want to work with the latest Flask code before it’s released, install or update the code from the master branch: pip install -U https://github.com/pallets/flask/archive/master.tar.gz Install virtualenv If you are using Python 2, the venv module is not available. Instead, install virtualenv. On Linux, virtualenv is provided by your package manager: # Debian, Ubuntu sudo apt-get install python-virtualenv # CentOS, Fedora sudo yum install python-virtualenv # Arch sudo pacman -S python-virtualenv If you are on Mac OS X or Windows, download get-pip.py, then: 9 sudo python2 Downloads/get-pip.py sudo python2 -m pip install virtualenv On Windows, as an administrator: \Python27\python.exe Downloads\get-pip.py \Python27\python.exe -m pip install virtualenv Now you can continue to Create an environment.