Flask Docs
Flask Docs
Flask Docs
Release 0.11-dev
April 10, 2014
CONTENTS
I Users Guide 1
1 Foreword 3
1.1 What does micro mean? . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Conguration and Conventions . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Growing with Flask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2 Foreword for Experienced Programmers 5
2.1 Thread-Locals in Flask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 Develop for the Web with Caution . . . . . . . . . . . . . . . . . . . . . . 5
2.3 The Status of Python 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3 Installation 7
3.1 virtualenv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.2 System-Wide Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.3 Living on the Edge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.4 pip and distribute on Windows . . . . . . . . . . . . . . . . . . . . . . . . 9
4 Quickstart 11
4.1 A Minimal Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
4.2 Debug Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
4.3 Routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
4.4 Static Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
4.5 Rendering Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
4.6 Accessing Request Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
4.7 Redirects and Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
4.8 About Responses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
4.9 Sessions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
4.10 Message Flashing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
4.11 Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
4.12 Hooking in WSGI Middlewares . . . . . . . . . . . . . . . . . . . . . . . 26
4.13 Deploying to a Web Server . . . . . . . . . . . . . . . . . . . . . . . . . . 26
5 Tutorial 27
5.1 Introducing Flaskr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
5.2 Step 0: Creating The Folders . . . . . . . . . . . . . . . . . . . . . . . . . 28
5.3 Step 1: Database Schema . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
i
5.4 Step 2: Application Setup Code . . . . . . . . . . . . . . . . . . . . . . . . 29
5.5 Step 3: Database Connections . . . . . . . . . . . . . . . . . . . . . . . . . 31
5.6 Step 4: Creating The Database . . . . . . . . . . . . . . . . . . . . . . . . 32
5.7 Step 5: The View Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 34
5.8 Step 6: The Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
5.9 Step 7: Adding Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
5.10 Bonus: Testing the Application . . . . . . . . . . . . . . . . . . . . . . . . 38
6 Templates 39
6.1 Jinja Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
6.2 Standard Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
6.3 Standard Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
6.4 Controlling Autoescaping . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
6.5 Registering Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
6.6 Context Processors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
7 Testing Flask Applications 43
7.1 The Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
7.2 The Testing Skeleton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
7.3 The First Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
7.4 Logging In and Out . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
7.5 Test Adding Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
7.6 Other Testing Tricks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
7.7 Faking Resources and Context . . . . . . . . . . . . . . . . . . . . . . . . 47
7.8 Keeping the Context Around . . . . . . . . . . . . . . . . . . . . . . . . . 48
7.9 Accessing and Modifying Sessions . . . . . . . . . . . . . . . . . . . . . . 49
8 Logging Application Errors 51
8.1 Error Mails . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
8.2 Logging to a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
8.3 Controlling the Log Format . . . . . . . . . . . . . . . . . . . . . . . . . . 53
8.4 Other Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
9 Debugging Application Errors 57
9.1 When in Doubt, Run Manually . . . . . . . . . . . . . . . . . . . . . . . . 57
9.2 Working with Debuggers . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
10 Conguration Handling 59
10.1 Conguration Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
10.2 Builtin Conguration Values . . . . . . . . . . . . . . . . . . . . . . . . . 60
10.3 Conguring from Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
10.4 Conguration Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . 63
10.5 Development / Production . . . . . . . . . . . . . . . . . . . . . . . . . . 63
10.6 Instance Folders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
11 Signals 67
11.1 Subscribing to Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
11.2 Creating Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
11.3 Sending Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
ii
11.4 Signals and Flasks Request Context . . . . . . . . . . . . . . . . . . . . . 70
11.5 Decorator Based Signal Subscriptions . . . . . . . . . . . . . . . . . . . . 70
11.6 Core Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
12 Pluggable Views 75
12.1 Basic Principle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
12.2 Method Hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
12.3 Method Based Dispatching . . . . . . . . . . . . . . . . . . . . . . . . . . 77
12.4 Decorating Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
12.5 Method Views for APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
13 The Application Context 81
13.1 Purpose of the Application Context . . . . . . . . . . . . . . . . . . . . . 81
13.2 Creating an Application Context . . . . . . . . . . . . . . . . . . . . . . . 82
13.3 Locality of the Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
13.4 Context Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
14 The Request Context 85
14.1 Diving into Context Locals . . . . . . . . . . . . . . . . . . . . . . . . . . 85
14.2 How the Context Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
14.3 Callbacks and Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
14.4 Teardown Callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
14.5 Notes On Proxies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
14.6 Context Preservation on Error . . . . . . . . . . . . . . . . . . . . . . . . 88
15 Modular Applications with Blueprints 91
15.1 Why Blueprints? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
15.2 The Concept of Blueprints . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
15.3 My First Blueprint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
15.4 Registering Blueprints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
15.5 Blueprint Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
15.6 Building URLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
16 Flask Extensions 97
16.1 Finding Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
16.2 Using Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
16.3 Flask Before 0.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
17 Working with the Shell 99
17.1 Creating a Request Context . . . . . . . . . . . . . . . . . . . . . . . . . . 99
17.2 Firing Before/After Request . . . . . . . . . . . . . . . . . . . . . . . . . 100
17.3 Further Improving the Shell Experience . . . . . . . . . . . . . . . . . . . 100
18 Patterns for Flask 101
18.1 Larger Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
18.2 Application Factories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
18.3 Application Dispatching . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
18.4 Implementing API Exceptions . . . . . . . . . . . . . . . . . . . . . . . . 109
18.5 Using URL Processors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
iii
18.6 Deploying with Distribute . . . . . . . . . . . . . . . . . . . . . . . . . . 112
18.7 Deploying with Fabric . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
18.8 Using SQLite 3 with Flask . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
18.9 SQLAlchemy in Flask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
18.10 Uploading Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
18.11 Caching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
18.12 View Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
18.13 Form Validation with WTForms . . . . . . . . . . . . . . . . . . . . . . . 133
18.14 Template Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
18.15 Message Flashing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
18.16 AJAX with jQuery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
18.17 Custom Error Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
18.18 Lazily Loading Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
18.19 MongoKit in Flask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
18.20 Adding a favicon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
18.21 Streaming Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
18.22 Deferred Request Callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . 150
18.23 Adding HTTP Method Overrides . . . . . . . . . . . . . . . . . . . . . . 151
18.24 Request Content Checksums . . . . . . . . . . . . . . . . . . . . . . . . . 152
18.25 Celery Based Background Tasks . . . . . . . . . . . . . . . . . . . . . . . 153
19 Deployment Options 157
19.1 mod_wsgi (Apache) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
19.2 Standalone WSGI Containers . . . . . . . . . . . . . . . . . . . . . . . . . 160
19.3 uWSGI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
19.4 FastCGI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
19.5 CGI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
20 Becoming Big 171
20.1 Read the Source. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
20.2 Hook. Extend. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
20.3 Subclass. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
20.4 Wrap with middleware. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
20.5 Fork. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
20.6 Scale like a pro. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
20.7 Discuss with the community. . . . . . . . . . . . . . . . . . . . . . . . . . 173
II API Reference 175
21 API 177
21.1 Application Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
21.2 Blueprint Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
21.3 Incoming Request Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
21.4 Response Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
21.5 Sessions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
21.6 Session Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
21.7 Test Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
21.8 Application Globals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
iv
21.9 Useful Functions and Classes . . . . . . . . . . . . . . . . . . . . . . . . . 211
21.10 Message Flashing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
21.11 JSON Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
21.12 Template Rendering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
21.13 Conguration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
21.14 Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
21.15 Stream Helpers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
21.16 Useful Internals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
21.17 Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
21.18 Class-Based Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
21.19 URL Route Registrations . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
21.20 View Function Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
III Additional Notes 235
22 Design Decisions in Flask 237
22.1 The Explicit Application Object . . . . . . . . . . . . . . . . . . . . . . . . 237
22.2 The Routing System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
22.3 One Template Engine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
22.4 Micro with Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
22.5 Thread Locals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
22.6 What Flask is, What Flask is Not . . . . . . . . . . . . . . . . . . . . . . . 240
23 HTML/XHTML FAQ 241
23.1 History of XHTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
23.2 History of HTML5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
23.3 HTML versus XHTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
23.4 What does strict mean? . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
23.5 New technologies in HTML5 . . . . . . . . . . . . . . . . . . . . . . . . . 244
23.6 What should be used? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
24 Security Considerations 245
24.1 Cross-Site Scripting (XSS) . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
24.2 Cross-Site Request Forgery (CSRF) . . . . . . . . . . . . . . . . . . . . . . 246
24.3 JSON Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
25 Unicode in Flask 249
25.1 Automatic Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
25.2 The Golden Rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
25.3 Encoding and Decoding Yourself . . . . . . . . . . . . . . . . . . . . . . . 250
25.4 Conguring Editors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
26 Flask Extension Development 253
26.1 Anatomy of an Extension . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
26.2 Hello Flaskext! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
26.3 Initializing Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
26.4 The Extension Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
26.5 Using _app_ctx_stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
v
26.6 Teardown Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
26.7 Learn from Others . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
26.8 Approved Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
26.9 Extension Import Transition . . . . . . . . . . . . . . . . . . . . . . . . . 260
27 Pocoo Styleguide 261
27.1 General Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
27.2 Expressions and Statements . . . . . . . . . . . . . . . . . . . . . . . . . . 262
27.3 Naming Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
27.4 Docstrings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
27.5 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
28 Python 3 Support 265
28.1 Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
28.2 API Stability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
28.3 Few Users . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
28.4 Small Ecosystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
28.5 Recommendations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
29 Upgrading to Newer Releases 267
29.1 Version 0.10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
29.2 Version 0.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
29.3 Version 0.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
29.4 Version 0.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
29.5 Version 0.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
29.6 Version 0.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
29.7 Version 0.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
29.8 Version 0.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
30 Flask Changelog 275
30.1 Version 1.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
30.2 Version 0.10.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
30.3 Version 0.10.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
30.4 Version 0.10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
30.5 Version 0.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
30.6 Version 0.8.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
30.7 Version 0.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
30.8 Version 0.7.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
30.9 Version 0.7.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
30.10 Version 0.7.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
30.11 Version 0.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
30.12 Version 0.6.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
30.13 Version 0.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
30.14 Version 0.5.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
30.15 Version 0.5.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
30.16 Version 0.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
30.17 Version 0.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
30.18 Version 0.3.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
30.19 Version 0.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
vi
30.20 Version 0.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
30.21 Version 0.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
31 License 287
31.1 Authors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
31.2 General License Denitions . . . . . . . . . . . . . . . . . . . . . . . . . . 288
31.3 Flask License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
31.4 Flask Artwork License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
Index 291
vii
viii
Part I
USERS 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
ONE
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.
1.1 What does micro mean?
Micro does not mean that your whole web application has to t into a single Python
le, 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 wont 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 dont.
By default, Flask does not include a database abstraction layer, formvalidation 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 its ready for production use on a variety of needs.
1.2 Conguration and Conventions
Flask has many conguration values, with sensible defaults, and a few conventions
when getting started. By convention templates and static les are stored in subdirec-
tories within the applications Python source tree, with the names templates and static
respectively. While this can be changed you usually dont have to, especially when
getting started.
3
1.3 Growing with Flask
Once you have Flask up and running, youll nd 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
TWO
FOREWORD FOR EXPERIENCED
PROGRAMMERS
2.1 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 few design choices that some people might nd surprising or unorthodox. For ex-
ample, Flask uses thread-local objects internally so that you dont have to pass objects
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 injection
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.
2.2 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.
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 gures out a way to exploit our applications.
And dont think that your application is not important enough to attract an attacker.
5
Depending on the kind of attack, chances are that automated bots are probing for ways
to ll 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.
2.3 The Status of Python 3
Currently the Python community is in the process of improving libraries to support
the new iteration of the Python programming language. While the situation is greatly
improving there are still some issues that make it hard for users to switch over to
Python 3 just now. These problems are partially caused by changes in the language
that went unreviewed for too long, partially also because we have not quite worked
out how the lower- level API should change to account for the Unicode differences in
Python 3.
We strongly recommend using Python 2.6 and 2.7 with activated Python 3 warnings
during development. If you plan on upgrading to Python 3 in the near future we
strongly recommend that you read How to write forwards compatible Python code.
If you do want to dive into Python 3 already have a look at the Python 3 Support page.
Continue to Installation or the Quickstart.
6
CHAPTER
THREE
INSTALLATION
Flask depends on two external libraries, Werkzeug and Jinja2. Werkzeug is a toolkit
for WSGI, the standard Python interface between web applications and a variety of
servers for both development and deployment. Jinja2 renders templates.
So howdo you get all that on your computer quickly? There are many ways you could
do that, but the most kick-ass method is virtualenv, so lets have a look at that rst.
You will need Python 2.6 or higher to get started, so be sure to have an up-to-date
Python 2.x installation. For using Flask with Python 3 have a look at Python 3 Support.
3.1 virtualenv
Virtualenv is probably what you want to use during development, and if you have
shell access to your production machines, youll probably want to use it there, too.
What problem does virtualenv solve? If you like Python as much as I do, chances are
you want to use it for other projects besides Flask-based web applications. But the
more projects you have, the more likely it is that you will be working with different
versions of Python itself, or at least different versions of Python libraries. Lets face it:
quite often libraries break backwards compatibility, and its unlikely that any serious
application will have zero dependencies. So what do you do if two or more of your
projects have conicting dependencies?
Virtualenv to the rescue! Virtualenv enables multiple side-by-side installations of
Python, one for each project. It doesnt actually install separate copies of Python, but
it does provide a clever way to keep different project environments isolated. Lets see
how virtualenv works.
If you are on Mac OS X or Linux, chances are that one of the following two commands
will work for you:
$ sudo easy_install virtualenv
or even better:
$ sudo pip install virtualenv
7
One of these will probably install virtualenv on your system. Maybe its even in your
package manager. If you use Ubuntu, try:
$ sudo apt-get install python-virtualenv
If you are on Windows and dont have the easy_install command, you must install it
rst. Check the pip and distribute on Windows section for more information about how
to do that. Once you have it installed, run the same commands as above, but without
the sudo prex.
Once you have virtualenv installed, just re up a shell and create your own environ-
ment. I usually create a project folder and a venv folder within:
$ mkdir myproject
$ cd myproject
$ virtualenv venv
New python executable in venv/bin/python
Installing distribute............done.
Now, whenever you want to work on a project, you only have to activate the corre-
sponding environment. On OS X and Linux, do the following:
$ . venv/bin/activate
If you are a Windows user, the following command is for you:
$ venv\scripts\activate
Either way, you should now be using your virtualenv (notice how the prompt of your
shell has changed to show the active environment).
Now you can just enter the following command to get Flask activated in your vir-
tualenv:
$ pip install Flask
A few seconds later and you are good to go.
3.2 System-Wide Installation
This is possible as well, though I do not recommend it. Just run pip with root privileges:
$ sudo pip install Flask
(On Windows systems, run it in a command-prompt windowwith administrator priv-
ileges, and leave out sudo.)
8
3.3 Living on the Edge
If you want to work with the latest version of Flask, there are two ways: you can either
let pip pull in the development version, or you can tell it to operate on a git checkout.
Either way, virtualenv is recommended.
Get the git checkout in a new virtualenv and run in development mode:
$ git clone http://github.com/mitsuhiko/flask.git
Initialized empty Git repository in ~/dev/flask/.git/
$ cd flask
$ virtualenv venv --distribute
New python executable in venv/bin/python
Installing distribute............done.
$ . venv/bin/activate
$ python setup.py develop
...
Finished processing dependencies for Flask
This will pull in the dependencies and activate the git head as the current version
inside the virtualenv. Then all you have to do is run git pull origin to update to the
latest version.
To just get the development version without git, do this instead:
$ mkdir flask
$ cd flask
$ virtualenv venv --distribute
$ . venv/bin/activate
New python executable in venv/bin/python
Installing distribute............done.
$ pip install Flask==dev
...
Finished processing dependencies for Flask==dev
3.4 pip and distribute on Windows
On Windows, installation of easy_install is a little bit trickier, but still quite easy. The
easiest way to do it is to download the distribute_setup.py le and run it. The easiest
way to run the le is to open your downloads folder and double-click on the le.
Next, add the easy_install command and other Python scripts to the command search
path, by adding your Python installations Scripts folder to the PATH environment
variable. To do that, right-click on the Computer icon on the Desktop or in the
Start menu, and choose Properties. Then click on Advanced System settings (in
Windows XP, click on the Advanced tab instead). Then click on the Environment
variables button. Finally, double-click on the Path variable in the System vari-
ables section, and add the path of your Python interpreters Scripts folder. Be sure to
9
delimit it from existing values with a semicolon. Assuming you are using Python 2.7
on the default path, add the following value:
;C:\Python27\Scripts
And you are done! To check that it worked, open the Command Prompt and exe-
cute easy_install. If you have User Account Control enabled on Windows Vista or
Windows 7, it should prompt you for administrator privileges.
Now that you have easy_install, you can use it to install pip:
> easy_install pip
10
CHAPTER
FOUR
QUICKSTART
Eager to get started? This page gives a good introduction to Flask. It assumes you
already have Flask installed. If you do not, head over to the Installation section.
4.1 A Minimal Application
A minimal Flask application looks something like this:
from flask import Flask
app = Flask(__name__)
@app.route(/)
def hello_world():
return Hello World!
if __name__ == __main__:
app.run()
Just save it as hello.py (or something similar) and run it with your Python interpreter.
Make sure to not call your application ask.py because this would conict with Flask
itself.
$ python hello.py
* Running on http://127.0.0.1:5000/
Now head over to http://127.0.0.1:5000/, and you should see your hello world greet-
ing.
So what did that code do?
1. First we imported the Flask class. An instance of this class will be our WSGI
application.
2. Next we create an instance of this class. The rst argument is the name of the
applications module or package. If you are using a single module (as in this
example), you should use __name__ because depending on if its started as ap-
plication or imported as module the name will be different (__main__ versus
the actual import name). This is needed so that Flask knows where to look for
11
templates, static les, and so on. For more information have a look at the Flask
documentation.
3. We then use the route() decorator to tell Flask what URL should trigger our
function.
4. The function is given a name which is also used to generate URLs for that partic-
ular function, and returns the message we want to display in the users browser.
5. Finally we use the run() function to run the local server with our application.
The if __name__ == __main__: makes sure the server only runs if the script
is executed directly from the Python interpreter and not used as an imported
module.
To stop the server, hit control-C.
Externally Visible Server
If you run the server you will notice that the server is only accessible from your own
computer, not from any other in the network. This is the default because in debugging
mode a user of the application can execute arbitrary Python code on your computer.
If you have debug disabled or trust the users on your network, you can make the server
publicly available simply by changing the call of the run() method to look like this:
app.run(host=0.0.0.0)
This tells your operating system to listen on all public IPs.
4.2 Debug Mode
The run() method is nice to start a local development server, but you would have to
restart it manually after each change to your code. That is not very nice and Flask can
do better. If you enable debug support the server will reload itself on code changes,
and it will also provide you with a helpful debugger if things go wrong.
There are two ways to enable debugging. Either set that ag on the application object:
app.debug = True
app.run()
Or pass it as a parameter to run:
app.run(debug=True)
Both methods have the exact same effect.
Attention
Even though the interactive debugger does not work in forking environments (which
makes it nearly impossible to use on production servers), it still allows the execution
12
of arbitrary code. This makes it a major security risk and therefore it must never be
used on production machines.
Screenshot of the debugger in action:
Have another debugger in mind? See Working with Debuggers.
4.3 Routing
Modern web applications have beautiful URLs. This helps people remember the
URLs, which is especially handy for applications that are used from mobile devices
with slower network connections. If the user can directly go to the desired page with-
out having to hit the index page it is more likely they will like the page and come back
next time.
As you have seen above, the route() decorator is used to bind a function to a URL.
Here are some basic examples:
@app.route(/)
def index():
13
return Index Page
@app.route(/hello)
def hello():
return Hello World
But there is more to it! You can make certain parts of the URL dynamic and attach
multiple rules to a function.
4.3.1 Variable Rules
To add variable parts to a URL you can mark these special sections as
<variable_name>. Such a part is then passed as a keyword argument to
your function. Optionally a converter can be used by specifying a rule with
<converter:variable_name>. Here are some nice examples:
@app.route(/user/<username>)
def show_user_profile(username):
# show the user profile for that user
return User %s % username
@app.route(/post/<int:post_id>)
def show_post(post_id):
# show the post with the given id, the id is an integer
return Post %d % post_id
The following converters exist:
int accepts integers
oat like int but for oating point values
path like the default but also accepts slashes
Unique URLs / Redirection Behavior
Flasks URL rules are based on Werkzeugs routing module. The idea behind that
module is to ensure beautiful and unique URLs based on precedents laid down by
Apache and earlier HTTP servers.
Take these two rules:
@app.route(/projects/)
def projects():
return The project page
@app.route(/about)
def about():
return The about page
Though they look rather similar, they differ in their use of the trailing slash in the URL
denition. In the rst case, the canonical URL for the projects endpoint has a trailing
slash. In that sense, it is similar to a folder on a le system. Accessing it without a
trailing slash will cause Flask to redirect to the canonical URL with the trailing slash.
14
In the second case, however, the URL is dened without a trailing slash, rather like the
pathname of a le on UNIX-like systems. Accessing the URL with a trailing slash will
produce a 404 Not Found error.
This behavior allows relative URLs to continue working even if the trailing slash is
omitted, consistent with how Apache and other servers work. Also, the URLs will
stay unique, which helps search engines avoid indexing the same page twice.
4.3.2 URL Building
If it can match URLs, can Flask also generate them? Of course it can. To build a URL
to a specic function you can use the url_for() function. It accepts the name of the
function as rst argument and a number of keyword arguments, each corresponding
to the variable part of the URL rule. Unknown variable parts are appended to the URL
as query parameters. Here are some examples:
>>> from flask import Flask, url_for
>>> app = Flask(__name__)
>>> @app.route(/)
... def index(): pass
...
>>> @app.route(/login)
... def login(): pass
...
>>> @app.route(/user/<username>)
... def profile(username): pass
...
>>> with app.test_request_context():
... print url_for(index)
... print url_for(login)
... print url_for(login, next=/)
... print url_for(profile, username=John Doe)
...
/
/login
/login?next=/
/user/John%20Doe
(This also uses the test_request_context() method, explained below. It tells Flask
to behave as though it is handling a request, even though we are interacting with it
through a Python shell. Have a look at the explanation below. Context Locals).
Why would you want to build URLs using the URL reversing function url_for() in-
stead of hard-coding them into your templates? There are three good reasons for this:
1. Reversing is often more descriptive than hard-coding the URLs. More impor-
tantly, it allows you to change URLs in one go, without having to remember to
change URLs all over the place.
15
2. URL building will handle escaping of special characters and Unicode data trans-
parently for you, so you dont have to deal with them.
3. If your application is placed outside the URL root (say, in /myapplication instead
of /), url_for() will handle that properly for you.
4.3.3 HTTP Methods
HTTP (the protocol web applications are speaking) knows different methods for ac-
cessing URLs. By default, a route only answers to GET requests, but that can be
changed by providing the methods argument to the route() decorator. Here are some
examples:
from flask import request
@app.route(/login, methods=[GET, POST])
def login():
if request.method == POST:
do_the_login()
else:
show_the_login_form()
If GET is present, HEAD will be added automatically for you. You dont have to deal
with that. It will also make sure that HEADrequests are handled as the HTTP RFC(the
document describing the HTTP protocol) demands, so you can completely ignore that
part of the HTTP specication. Likewise, as of Flask 0.6, OPTIONS is implemented for
you automatically as well.
You have no idea what an HTTP method is? Worry not, here is a quick introduction to
HTTP methods and why they matter:
The HTTP method (also often called the verb) tells the server what the clients wants
to do with the requested page. The following methods are very common:
GET The browser tells the server to just get the information stored on that page and
send it. This is probably the most common method.
HEAD The browser tells the server to get the information, but it is only interested in
the headers, not the content of the page. An application is supposed to handle
that as if a GET request was received but to not deliver the actual content. In
Flask you dont have to deal with that at all, the underlying Werkzeug library
handles that for you.
POST The browser tells the server that it wants to post some new information to that
URL and that the server must ensure the data is stored and only stored once.
This is how HTML forms usually transmit data to the server.
PUT Similar to POST but the server might trigger the store procedure multiple times
by overwriting the old values more than once. Now you might be asking why
this is useful, but there are some good reasons to do it this way. Consider that
the connection is lost during transmission: in this situation a systembetween the
browser and the server might receive the request safely a second time without
16
breaking things. With POST that would not be possible because it must only be
triggered once.
DELETE Remove the information at the given location.
OPTIONS Provides a quick way for a client to gure out which methods are sup-
ported by this URL. Starting with Flask 0.6, this is implemented for you auto-
matically.
Now the interesting part is that in HTML4 and XHTML1, the only methods a form
can submit to the server are GET and POST. But with JavaScript and future HTML
standards you can use the other methods as well. Furthermore HTTP has become
quite popular lately and browsers are no longer the only clients that are using HTTP.
For instance, many revision control systems use it.
4.4 Static Files
Dynamic web applications also need static les. Thats usually where the CSS and
JavaScript les are coming from. Ideally your web server is congured to serve them
for you, but during development Flask can do that as well. Just create a folder called
static in your package or next to your module and it will be available at /static on the
application.
To generate URLs for static les, use the special static endpoint name:
url_for(static, filename=style.css)
The le has to be stored on the lesystem as static/style.css.
4.5 Rendering Templates
Generating HTML from within Python is not fun, and actually pretty cumbersome be-
cause you have to do the HTML escaping on your own to keep the application secure.
Because of that Flask congures the Jinja2 template engine for you automatically.
To render a template you can use the render_template() method. All you have to do
is provide the name of the template and the variables you want to pass to the template
engine as keyword arguments. Heres a simple example of how to render a template:
from flask import render_template
@app.route(/hello/)
@app.route(/hello/<name>)
def hello(name=None):
return render_template(hello.html, name=name)
Flask will look for templates in the templates folder. So if your application is a module,
this folder is next to that module, if its a package its actually inside your package:
17
Case 1: a module:
/application.py
/templates
/hello.html
Case 2: a package:
/application
/__init__.py
/templates
/hello.html
For templates you can use the full power of Jinja2 templates. Head over to the ofcial
Jinja2 Template Documentation for more information.
Here is an example template:
<!doctype html>
<title>Hello from Flask</title>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello World!</h1>
{% endif %}
Inside templates you also have access to the request, session and g
1
objects as well
as the get_flashed_messages() function.
Templates are especially useful if inheritance is used. If you want to know how that
works, head over to the Template Inheritance pattern documentation. Basically tem-
plate inheritance makes it possible to keep certain elements on each page (like header,
navigation and footer).
Automatic escaping is enabled, so if name contains HTML it will be escaped automat-
ically. If you can trust a variable and you know that it will be safe HTML (for example
because it came from a module that converts wiki markup to HTML) you can mark
it as safe by using the Markup class or by using the |safe lter in the template. Head
over to the Jinja 2 documentation for more examples.
Here is a basic introduction to how the Markup class works:
>>> from flask import Markup
>>> Markup(<strong>Hello %s!</strong>) % <blink>hacker</blink>
Markup(u<strong>Hello <blink>hacker</blink>!</strong>)
>>> Markup.escape(<blink>hacker</blink>)
Markup(u<blink>hacker</blink>)
>>> Markup(<em>Marked up</em> » HTML).striptags()
uMarked up \xbb HTML
Changed in version 0.5: Autoescaping is no longer enabled for all templates. The
1
Unsure what that g object is? Its something in which you can store information for your own needs,
check the documentation of that object (g) and the Using SQLite 3 with Flask for more information.
18
following extensions for templates trigger autoescaping: .html, .htm, .xml, .xhtml.
Templates loaded from a string will have autoescaping disabled.
4.6 Accessing Request Data
For web applications its crucial to react to the data a client sent to the server. In Flask
this information is provided by the global request object. If you have some experience
with Python you might be wondering how that object can be global and how Flask
manages to still be threadsafe. The answer is context locals:
4.6.1 Context Locals
Insider Information
If you want to understand how that works and how you can implement tests with
context locals, read this section, otherwise just skip it.
Certain objects in Flask are global objects, but not of the usual kind. These objects are
actually proxies to objects that are local to a specic context. What a mouthful. But
that is actually quite easy to understand.
Imagine the context being the handling thread. Arequest comes in and the web server
decides to spawn a new thread (or something else, the underlying object is capable
of dealing with concurrency systems other than threads). When Flask starts its inter-
nal request handling it gures out that the current thread is the active context and
binds the current application and the WSGI environments to that context (thread). It
does that in an intelligent way so that one application can invoke another application
without breaking.
So what does this mean to you? Basically you can completely ignore that this is the
case unless you are doing something like unit testing. You will notice that code which
depends on a request object will suddenly break because there is no request object. The
solution is creating a request object yourself and binding it to the context. The easiest
solution for unit testing is to use the test_request_context() context manager. In
combination with the with statement it will bind a test request so that you can interact
with it. Here is an example:
from flask import request
with app.test_request_context(/hello, method=POST):
# now you can do something with the request until the
# end of the with block, such as basic assertions:
assert request.path == /hello
assert request.method == POST
The other possibility is passing a whole WSGI environment to the request_context()
method:
19
from flask import request
with app.request_context(environ):
assert request.method == POST
4.6.2 The Request Object
The request object is documented in the API section and we will not cover it here in
detail (see request). Here is a broad overviewof some of the most common operations.
First of all you have to import it from the ask module:
from flask import request
The current request method is available by using the method attribute. To access form
data (data transmitted in a POST or PUT request) you can use the form attribute. Here
is a full example of the two attributes mentioned above:
@app.route(/login, methods=[POST, GET])
def login():
error = None
if request.method == POST:
if valid_login(request.form[username],
request.form[password]):
return log_the_user_in(request.form[username])
else:
error = Invalid username/password
# the code below is executed if the request method
# was GET or the credentials were invalid
return render_template(login.html, error=error)
What happens if the key does not exist in the form attribute? In that case a special
KeyError is raised. You can catch it like a standard KeyError but if you dont do that, a
HTTP 400 Bad Request error page is shown instead. So for many situations you dont
have to deal with that problem.
To access parameters submitted in the URL (?key=value) you can use the args at-
tribute:
searchword = request.args.get(key, )
We recommend accessing URL parameters with get or by catching the KeyError be-
cause users might change the URL and presenting them a 400 bad request page in that
case is not user friendly.
For a full list of methods and attributes of the request object, head over to the request
documentation.
20
4.6.3 File Uploads
You can handle uploaded les with Flask easily. Just make sure not to forget to
set the enctype="multipart/form-data" attribute on your HTML form, otherwise the
browser will not transmit your les at all.
Uploaded les are stored in memory or at a temporary location on the lesystem. You
can access those les by looking at the files attribute on the request object. Each
uploaded le is stored in that dictionary. It behaves just like a standard Python file
object, but it also has a save() method that allows you to store that le on the lesys-
tem of the server. Here is a simple example showing how that works:
from flask import request
@app.route(/upload, methods=[GET, POST])
def upload_file():
if request.method == POST:
f = request.files[the_file]
f.save(/var/www/uploads/uploaded_file.txt)
...
If you want to know how the le was named on the client before it was uploaded to
your application, you can access the filename attribute. However please keep in mind
that this value can be forged so never ever trust that value. If you want to use the le-
name of the client to store the le on the server, pass it through the secure_filename()
function that Werkzeug provides for you:
from flask import request
from werkzeug import secure_filename
@app.route(/upload, methods=[GET, POST])
def upload_file():
if request.method == POST:
f = request.files[the_file]
f.save(/var/www/uploads/ + secure_filename(f.filename))
...
For some better examples, checkout the Uploading Files pattern.
4.6.4 Cookies
To access cookies you can use the cookies attribute. To set cookies you can use the
set_cookie method of response objects. The cookies attribute of request objects is a
dictionary with all the cookies the client transmits. If you want to use sessions, do not
use the cookies directly but instead use the Sessions in Flask that add some security on
top of cookies for you.
Reading cookies:
from flask import request
21
@app.route(/)
def index():
username = request.cookies.get(username)
# use cookies.get(key) instead of cookies[key] to not get a
# KeyError if the cookie is missing.
Storing cookies:
from flask import make_response
@app.route(/)
def index():
resp = make_response(render_template(...))
resp.set_cookie(username, the username)
return resp
Note that cookies are set on response objects. Since you normally just return strings
from the view functions Flask will convert them into response objects for you. If you
explicitly want to do that you can use the make_response() function and then modify
it.
Sometimes you might want to set a cookie at a point where the response object does
not exist yet. This is possible by utilizing the Deferred Request Callbacks pattern.
For this also see About Responses.
4.7 Redirects and Errors
To redirect a user to another endpoint, use the redirect() function; to abort a request
early with an error code, use the abort() function:
from flask import abort, redirect, url_for
@app.route(/)
def index():
return redirect(url_for(login))
@app.route(/login)
def login():
abort(401)
this_is_never_executed()
This is a rather pointless example because a user will be redirected from the index to
a page they cannot access (401 means access denied) but it shows how that works.
By default a black and white error page is shown for each error code. If you want to
customize the error page, you can use the errorhandler() decorator:
from flask import render_template
22
@app.errorhandler(404)
def page_not_found(error):
return render_template(page_not_found.html), 404
Note the 404 after the render_template() call. This tells Flask that the status code of
that page should be 404 which means not found. By default 200 is assumed which
translates to: all went well.
4.8 About Responses
The return value from a view function is automatically converted into a response ob-
ject for you. If the return value is a string its converted into a response object with the
string as response body, a 200 OK status code and a text/html mimetype. The logic
that Flask applies to converting return values into response objects is as follows:
1. If a response object of the correct type is returned its directly returned from the
view.
2. If its a string, a response object is created with that data and the default param-
eters.
3. If a tuple is returned the items in the tuple can provide extra information.
Such tuples have to be in the form (response, status, headers) or (response,
headers) where at least one itemhas to be in the tuple. The status value will over-
ride the status code and headers can be a list or dictionary of additional header
values.
4. If none of that works, Flask will assume the return value is a valid WSGI appli-
cation and convert that into a response object.
If you want to get hold of the resulting response object inside the view you can use the
make_response() function.
Imagine you have a view like this:
@app.errorhandler(404)
def not_found(error):
return render_template(error.html), 404
You just need to wrap the return expression with make_response() and get the re-
sponse object to modify it, then return it:
@app.errorhandler(404)
def not_found(error):
resp = make_response(render_template(error.html), 404)
resp.headers[X-Something] = A value
return resp
23
4.9 Sessions
In addition to the request object there is also a second object called session which
allows you to store information specic to a user from one request to the next. This is
implemented on top of cookies for you and signs the cookies cryptographically. What
this means is that the user could look at the contents of your cookie but not modify it,
unless they know the secret key used for signing.
In order to use sessions you have to set a secret key. Here is how sessions work:
from flask import Flask, session, redirect, url_for, escape, request
app = Flask(__name__)
@app.route(/)
def index():
if username in session:
return Logged in as %s % escape(session[username])
return You are not logged in
@app.route(/login, methods=[GET, POST])
def login():
if request.method == POST:
session[username] = request.form[username]
return redirect(url_for(index))
return
<form action="" method="post">
<p><input type=text name=username>
<p><input type=submit value=Login>
</form>
@app.route(/logout)
def logout():
# remove the username from the session if its there
session.pop(username, None)
return redirect(url_for(index))
# set the secret key. keep this really secret:
app.secret_key = A0Zr98j/3yX R~XHH!jmN]LWX/,?RT
The escape() mentioned here does escaping for you if you are not using the template
engine (as in this example).
How to generate good secret keys
The problem with random is that its hard to judge what is truly random. And a secret
key should be as random as possible. Your operating system has ways to generate
pretty random stuff based on a cryptographic random generator which can be used to
get such a key:
24
>>> import os
>>> os.urandom(24)
\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8
Just take that thing and copy/paste it into your code and youre done.
A note on cookie-based sessions: Flask will take the values you put into the session
object and serialize them into a cookie. If you are nding some values do not per-
sist across requests, cookies are indeed enabled, and you are not getting a clear error
message, check the size of the cookie in your page responses compared to the size
supported by web browsers.
4.10 Message Flashing
Good applications and user interfaces are all about feedback. If the user does not get
enough feedback they will probably end up hating the application. Flask provides a
really simple way to give feedback to a user with the ashing system. The ashing
system basically makes it possible to record a message at the end of a request and
access it on the next (and only the next) request. This is usually combined with a
layout template to expose the message.
To ash a message use the flash() method, to get hold of the messages you can use
get_flashed_messages() which is also available in the templates. Check out the Mes-
sage Flashing for a full example.
4.11 Logging
New in version 0.3.
Sometimes you might be in a situation where you deal with data that should be correct,
but actually is not. For example you may have some client-side code that sends an
HTTP request to the server but its obviously malformed. This might be caused by
a user tampering with the data, or the client code failing. Most of the time its okay
to reply with 400 Bad Request in that situation, but sometimes that wont do and the
code has to continue working.
You may still want to log that something shy happened. This is where loggers come
in handy. As of Flask 0.3 a logger is precongured for you to use.
Here are some example log calls:
app.logger.debug(A value for debugging)
app.logger.warning(A warning occurred (%d apples), 42)
app.logger.error(An error occurred)
The attached logger is a standard logging Logger, so head over to the ofcial logging
documentation for more information.
25
4.12 Hooking in WSGI Middlewares
If you want to add a WSGI middleware to your application you can wrap the internal
WSGI application. For example if you want to use one of the middlewares from the
Werkzeug package to work around bugs in lighttpd, you can do it like this:
from werkzeug.contrib.fixers import LighttpdCGIRootFix
app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)
4.13 Deploying to a Web Server
Ready to deploy your newFlask app? To wrap up the quickstart, you can immediately
deploy to a hosted platform, all of which offer a free plan for small projects:
Deploying Flask on Heroku
Deploying WSGI on dotCloud with Flask-specic notes
Other places where you can host your Flask app:
Deploying Flask on Webfaction
Deploying Flask on Google App Engine
Sharing your Localhost Server with Localtunnel
If you manage your own hosts and would like to host yourself, see the chapter on
Deployment Options.
26
CHAPTER
FIVE
TUTORIAL
You want to develop an application with Python and Flask? Here you have the chance
to learn that by example. In this tutorial we will create a simple microblog application.
It only supports one user that can create text-only entries and there are no feeds or
comments, but it still features everything you need to get started. We will use Flask
and SQLite as database which comes out of the box with Python, so there is nothing
else you need.
If you want the full sourcecode in advance or for comparison, check out the example
source.
5.1 Introducing Flaskr
We will call our blogging application askr here, feel free to choose a less web-2.0-ish
name ;) Basically we want it to do the following things:
1. let the user sign in and out with credentials specied in the conguration. Only
one user is supported.
2. when the user is logged in they can add new entries to the page consisting of a
text-only title and some HTML for the text. This HTML is not sanitized because
we trust the user here.
3. the page shows all entries so far in reverse order (newest on top) and the user
can add new ones from there if logged in.
We will be using SQLite3 directly for that application because its good enough for
an application of that size. For larger applications however it makes a lot of sense to
use SQLAlchemy that handles database connections in a more intelligent way, allows
you to target different relational databases at once and more. You might also want to
consider one of the popular NoSQL databases if your data is more suited for those.
Here a screenshot from the nal application:
27
Continue with Step 0: Creating The Folders.
5.2 Step 0: Creating The Folders
Before we get started, lets create the folders needed for this application:
/flaskr
/static
/templates
The askr folder is not a python package, but just something where we drop our les.
We will then put our database schema as well as main module into this folder. It is
done in the following way. The les inside the static folder are available to users of
the application via HTTP. This is the place where css and javascript les go. Inside the
templates folder Flask will look for Jinja2 templates. The templates you create later in
the tutorial will go in this directory.
Continue with Step 1: Database Schema.
28
5.3 Step 1: Database Schema
First we want to create the database schema. Only a single table is needed for this ap-
plication and we only want to support SQLite so creating the database schema is quite
easy. Just put the following contents into a le named schema.sql in the just created
askr folder:
drop table if exists entries;
create table entries (
id integer primary key autoincrement,
title text not null,
text text not null
);
This schema consists of a single table called entries and each row in this table has an
id, a title and a text. The id is an automatically incrementing integer and a primary key,
the other two are strings that must not be null.
Continue with Step 2: Application Setup Code.
5.4 Step 2: Application Setup Code
Now that we have the schema in place we can create the application module. Lets
call it askr.py. We will place this le inside the ask folder. We will begin by adding
the imports we need and by adding the cong section. For small applications, it is
possible to drop the conguration directly into the module, and this is what we will
be doing here. However a cleaner solution would be to create a separate .ini or .py le
and load that or import the values from there.
First we add the imports in askr.py:
# all the imports
import os
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash
Next we can create our actual application and initialize it with the cong from the
same le, in askr.py:
# create our little application :)
app = Flask(__name__)
app.config.from_object(__name__)
# Load default config and override config from an environment variable
app.config.update(dict(
DATABASE=os.path.join(app.root_path, flaskr.db),
DEBUG=True,
SECRET_KEY=development key,
29
USERNAME=admin,
PASSWORD=default
))
app.config.from_envvar(FLASKR_SETTINGS, silent=True)
The Config object works similar to a dictionary so we can update it with new values.
Database Path
Operating systems know the concept of a current working directory for each process.
Unfortunately you cannot depend on this in web applications because you might have
more than one application in the same process.
For this reason the app.root_path attribute can be used to get the path to the applica-
tion. Together with the os.path module les can then easily be found. In this example
we place the database right next to it.
For a real-work application its recommended to use Instance Folders instead.
Usually, it is a good idea to load a separate, environment specic conguration le.
Flask allows you to import multiple congurations and it will use the setting dened
in the last import. This enables robust conguration setups. from_envvar() can help
achieve this.
app.cong.from_envvar(FLASKR_SETTINGS, silent=True)
Simply dene the environment variable FLASKR_SETTINGS that points to a cong le to
be loaded. The silent switch just tells Flask to not complain if no such environment
key is set.
In addition to that you can use the from_object() method on the cong object and
provide it with an import name of a module. Flask will the initialize the variable
from that module. Note that in all cases only variable names that are uppercase are
considered.
The SECRET_KEY is needed to keep the client-side sessions secure. Choose that key
wisely and as hard to guess and complex as possible. The debug ag enables or dis-
ables the interactive debugger. Never leave debug mode activated in a production system,
because it will allow users to execute code on the server!
We will also add a method that allows for easily connecting to the specied database.
This can be used to open a connection on request and also from the interactive Python
shell or a script. This will come in handy later. We create a simple database connection
through SQLite and then tell it to use the sqlite3.Row object to represent rows. This
allows us to treat the rows as if they were dictionaries instead of tuples.
def connect_db():
"""Connects to the specific database."""
rv = sqlite3.connect(app.config[DATABASE])
rv.row_factory = sqlite3.Row
return rv
30
Finally we just add a line to the bottom of the le that res up the server if we want to
run that le as a standalone application:
if __name__ == __main__:
app.run()
With that out of the way you should be able to start up the application without prob-
lems. Do this with the following command:
python flaskr.py
You will see a message telling you that server has started along with the address at
which you can access it.
When you head over to the server in your browser you will get an 404 page not found
error because we dont have any views yet. But we will focus on that a little later. First
we should get the database working.
Externally Visible Server
Want your server to be publicly available? Check out the externally visible server section
for more information.
Continue with Step 3: Database Connections.
5.5 Step 3: Database Connections
We have created a function for establishing a database connection with connect_db but
by itself thats not particularly useful. Creating and closing database connections all
the time is very inefcient, so we want to keep it around for longer. Because database
connections encapsulate a transaction we also need to make sure that only one request
at the time uses the connection. So how can we elegantly do that with Flask?
This is where the application context comes into play. So lets start there.
Flask provides us with two contexts: the application context and the request context.
For the time being all you have to knowis that there are special variables that use these.
For instance the request variable is the request object associated with the current re-
quest, whereas g is a general purpose variable associated with the current application
context. We will go into the details of this a bit later.
For the time being all you have to know is that you can store information safely on the
g object.
So when do you put it on there? To do that you can make a helper function. The rst
time the function is called it will create a database connection for the current context
and successive calls will return the already established connection:
def get_db():
"""Opens a new database connection if there is none yet for the
current application context.
31
"""
if not hasattr(g, sqlite_db):
g.sqlite_db = connect_db()
return g.sqlite_db
So now we know how to connect, but how do we properly disconnect? For that ask
provides us with the teardown_appcontext() decorator. Its executed every time the
application context tears down:
@app.teardown_appcontext
def close_db(error):
"""Closes the database again at the end of the request."""
if hasattr(g, sqlite_db):
g.sqlite_db.close()
Functions marked with teardown_appcontext() are called every time the app context
tears down. So what does this mean? Essentially the app context is created before
the request comes in and is destroyed (teared down) whenever the request nishes. A
teardown can happen because of two reasons: either everything went well (the error
parameter will be None) or an exception happend in which case the error is passed to
the teardown function.
Curious about what these contexts mean? Have a look at the The Application Context
documentation to learn more.
Continue to Step 4: Creating The Database.
Hint: Where do I put this code?
If youve been following along in this tutorial, you might be wondering where to put
the code from this step and the next. A logical place is to group these module-level
functions together, and put your new get_db and close_db functions below your ex-
isting connect_db function (following the tutorial line-by-line).
If you need a moment to nd your bearings, take a look at how the example source
is organized. In Flask, you can put all of your application code into a single Python
module. You dont have to, and if your app grows larger, its a good idea not to.
5.6 Step 4: Creating The Database
As outlined earlier, Flaskr is a database powered application, and more precisely, it is
an application powered by a relational database system. Such systems need a schema
that tells them how to store that information. So before starting the server for the rst
time its important to create that schema.
Such a schema can be created by piping the schema.sql le into the sqlite3 command as
follows:
32
sqlite3 /tmp/flaskr.db < schema.sql
The downside of this is that it requires the sqlite3 command to be installed which is
not necessarily the case on every system. This also require that we provide the path
to the database which can introduce errors. Its a good idea to add a function that
initializes the database for you to the application.
To do this we can create a function called init_db that initializes the database. Let
me show you the code rst. Just add this function below the connect_db function in
askr.py:
def init_db():
with app.app_context():
db = get_db()
with app.open_resource(schema.sql, mode=r) as f:
db.cursor().executescript(f.read())
db.commit()
So whats happening here? Remember how we learned last chapter that the applica-
tion context is created every time a request comes in? Here we dont have a request
yet, so we need to create the application context by hand. Without an application con-
text the g object does not know yet to which application it becomes as there could be
more than one!
The with app.app_context() statement establishes the application context for us. In
the body of the with statement the g object will be associated with app. At the end of
the with statement the association is released and all teardown functions are executed.
This means that our database connection is disconnected after the commit.
The open_resource() method of the application object is a convenient helper function
that will open a resource that the application provides. This function opens a le from
the resource location (your askr folder) and allows you to read from it. We are using
this here to execute a script on the database connection.
The connection object provided by SQLite can give us a cursor object. On that cur-
sor there is a method to execute a complete script. Finally we only have to commit
the changes. SQLite 3 and other transactional databases will not commit unless you
explicitly tell it to.
Now it is possible to create a database by starting up a Python shell and importing
and calling that function:
>>> from flaskr import init_db
>>> init_db()
Troubleshooting
If you get an exception later that a table cannot be found check that you did call the
init_db function and that your table names are correct (singular vs. plural for example).
Continue with Step 5: The View Functions
33
5.7 Step 5: The View Functions
Now that the database connections are working we can start writing the view func-
tions. We will need four of them:
5.7.1 Show Entries
This view shows all the entries stored in the database. It listens on the root of the
application and will select title and text from the database. The one with the highest
id (the newest entry) will be on top. The rows returned from the cursor look a bit like
tuples because we are using the sqlite3.Row row factory.
The view function will pass the entries as dicts to the show_entries.html template and
return the rendered one:
@app.route(/)
def show_entries():
db = get_db()
cur = db.execute(select title, text from entries order by id desc)
entries = cur.fetchall()
return render_template(show_entries.html, entries=entries)
5.7.2 Add New Entry
This view lets the user add new entries if they are logged in. This only responds
to POST requests, the actual form is shown on the show_entries page. If everything
worked out well we will flash() an information message to the next request and redi-
rect back to the show_entries page:
@app.route(/add, methods=[POST])
def add_entry():
if not session.get(logged_in):
abort(401)
db = get_db()
db.execute(insert into entries (title, text) values (?, ?),
[request.form[title], request.form[text]])
db.commit()
flash(New entry was successfully posted)
return redirect(url_for(show_entries))
Note that we check that the user is logged in here (the logged_in key is present in the
session and True).
Security Note
Be sure to use question marks when building SQL statements, as done in the example
above. Otherwise, your app will be vulnerable to SQL injection when you use string
formatting to build SQL statements. See Using SQLite 3 with Flask for more.
34
5.7.3 Login and Logout
These functions are used to sign the user in and out. Login checks the username and
password against the ones from the conguration and sets the logged_in key in the ses-
sion. If the user logged in successfully, that key is set to True, and the user is redirected
back to the show_entries page. In addition, a message is ashed that informs the user
that he or she was logged in successfully. If an error occurred, the template is notied
about that, and the user is asked again:
@app.route(/login, methods=[GET, POST])
def login():
error = None
if request.method == POST:
if request.form[username] != app.config[USERNAME]:
error = Invalid username
elif request.form[password] != app.config[PASSWORD]:
error = Invalid password
else:
session[logged_in] = True
flash(You were logged in)
return redirect(url_for(show_entries))
return render_template(login.html, error=error)
The logout function, on the other hand, removes that key from the session again. We
use a neat trick here: if you use the pop() method of the dict and pass a second param-
eter to it (the default), the method will delete the key from the dictionary if present or
do nothing when that key is not in there. This is helpful because now we dont have
to check if the user was logged in.
@app.route(/logout)
def logout():
session.pop(logged_in, None)
flash(You were logged out)
return redirect(url_for(show_entries))
Continue with Step 6: The Templates.
5.8 Step 6: The Templates
Nowwe should start working on the templates. If we request the URLs nowwe would
only get an exception that Flask cannot nd the templates. The templates are using
Jinja2 syntax and have autoescaping enabled by default. This means that unless you
mark a value in the code with Markup or with the |safe lter in the template, Jinja2 will
ensure that special characters such as < or > are escaped with their XML equivalents.
We are also using template inheritance which makes it possible to reuse the layout of
the website in all pages.
Put the following templates into the templates folder:
35
5.8.1 layout.html
This template contains the HTML skeleton, the header and a link to log in (or log out
if the user was already logged in). It also displays the ashed messages if there are
any. The {% block body %} block can be replaced by a block of the same name (body)
in a child template.
The session dict is available in the template as well and you can use that to check
if the user is logged in or not. Note that in Jinja you can access missing attributes
and items of objects / dicts which makes the following code work, even if there is no
logged_in key in the session:
<!doctype html>
<title>Flaskr</title>
<link rel=stylesheet type=text/css href="{{ url_for(static, filename=style.css) }}">
<div class=page>
<h1>Flaskr</h1>
<div class=metanav>
{% if not session.logged_in %}
<a href="{{ url_for(login) }}">log in</a>
{% else %}
<a href="{{ url_for(logout) }}">log out</a>
{% endif %}
</div>
{% for message in get_flashed_messages() %}
<div class=flash>{{ message }}</div>
{% endfor %}
{% block body %}{% endblock %}
</div>
5.8.2 show_entries.html
This template extends the layout.html template from above to display the mes-
sages. Note that the for loop iterates over the messages we passed in with the
render_template() function. We also tell the formto submit to your add_entry function
and use POST as HTTP method:
{% extends "layout.html" %}
{% block body %}
{% if session.logged_in %}
<form action="{{ url_for(add_entry) }}" method=post class=add-entry>
<dl>
<dt>Title:
<dd><input type=text size=30 name=title>
<dt>Text:
<dd><textarea name=text rows=5 cols=40></textarea>
<dd><input type=submit value=Share>
</dl>
</form>
{% endif %}
36
<ul class=entries>
{% for entry in entries %}
<li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}
{% else %}
<li><em>Unbelievable. No entries here so far</em>
{% endfor %}
</ul>
{% endblock %}
5.8.3 login.html
Finally the login template which basically just displays a form to allow the user to
login:
{% extends "layout.html" %}
{% block body %}
<h2>Login</h2>
{% if error %}<p class=error><strong>Error:</strong> {{ error }}{% endif %}
<form action="{{ url_for(login) }}" method=post>
<dl>
<dt>Username:
<dd><input type=text name=username>
<dt>Password:
<dd><input type=password name=password>
<dd><input type=submit value=Login>
</dl>
</form>
{% endblock %}
Continue with Step 7: Adding Style.
5.9 Step 7: Adding Style
Now that everything else works, its time to add some style to the application. Just
create a stylesheet called style.css in the static folder we created before:
body { font-family: sans-serif; background: #eee; }
a, h1, h2 { color: #377ba8; }
h1, h2 { font-family: Georgia, serif; margin: 0; }
h1 { border-bottom: 2px solid #eee; }
h2 { font-size: 1.2em; }
.page { margin: 2em auto; width: 35em; border: 5px solid #ccc;
padding: 0.8em; background: white; }
.entries { list-style: none; margin: 0; padding: 0; }
.entries li { margin: 0.8em 1.2em; }
.entries li h2 { margin-left: -1em; }
.add-entry { font-size: 0.9em; border-bottom: 1px solid #ccc; }
37
.add-entry dl { font-weight: bold; }
.metanav { text-align: right; font-size: 0.8em; padding: 0.3em;
margin-bottom: 1em; background: #fafafa; }
.flash { background: #cee5F5; padding: 0.5em;
border: 1px solid #aacbe2; }
.error { background: #f0d6d6; padding: 0.5em; }
Continue with Bonus: Testing the Application.
5.10 Bonus: Testing the Application
Now that you have nished the application and everything works as expected, its
probably not a bad idea to add automated tests to simplify modications in the future.
The application above is used as a basic example of how to perform unittesting in the
Testing Flask Applications section of the documentation. Go there to see how easy it is
to test Flask applications.
38
CHAPTER
SIX
TEMPLATES
Flask leverages Jinja2 as template engine. You are obviously free to use a different tem-
plate engine, but you still have to install Jinja2 to run Flask itself. This requirement is
necessary to enable rich extensions. An extension can depend on Jinja2 being present.
This section only gives a very quick introduction into how Jinja2 is integrated into
Flask. If you want information on the template engines syntax itself, head over to the
ofcial Jinja2 Template Documentation for more information.
6.1 Jinja Setup
Unless customized, Jinja2 is congured by Flask as follows:
autoescaping is enabled for all templates ending in .html, .htm, .xml as well as
.xhtml
a template has the ability to opt in/out autoescaping with the {% autoescape %}
tag.
Flask inserts a couple of global functions and helpers into the Jinja2 context, ad-
ditionally to the values that are present by default.
6.2 Standard Context
The following global variables are available within Jinja2 templates by default:
config
The current conguration object (flask.config)
New in version 0.6.
Changed in version 0.10: This is now always available, even in imported tem-
plates.
request
The current request object (flask.request). This variable is unavailable if the
template was rendered without an active request context.
39
session
The current session object (flask.session). This variable is unavailable if the
template was rendered without an active request context.
g
The request-bound object for global variables (flask.g). This variable is unavail-
able if the template was rendered without an active request context.
url_for()
The flask.url_for() function.
get_flashed_messages()
The flask.get_flashed_messages() function.
The Jinja Context Behavior
These variables are added to the context of variables, they are not global variables.
The difference is that by default these will not show up in the context of imported
templates. This is partially caused by performance considerations, partially to keep
things explicit.
What does this mean for you? If you have a macro you want to import, that needs to
access the request object you have two possibilities:
1. you explicitly pass the request to the macro as parameter, or the attribute of the
request object you are interested in.
2. you import the macro with context.
Importing with context looks like this:
{% from _helpers.html import my_macro with context %}
6.3 Standard Filters
These lters are available in Jinja2 additionally to the lters provided by Jinja2 itself:
tojson()
This function converts the given object into JSON representation. This is for
example very helpful if you try to generate JavaScript on the y.
Note that inside script tags no escaping must take place, so make sure to disable
escaping with |safe before Flask 0.10 if you intend to use it inside script tags:
<script type=text/javascript>
doSomethingWith({{ user.username|tojson|safe }});
</script>
40
6.4 Controlling Autoescaping
Autoescaping is the concept of automatically escaping special characters of you. Spe-
cial characters in the sense of HTML (or XML, and thus XHTML) are &, >, <, " as well
as . Because these characters carry specic meanings in documents on their own you
have to replace themby so called entities if you want to use themfor text. Not doing
so would not only cause user frustration by the inability to use these characters in text,
but can also lead to security problems. (see Cross-Site Scripting (XSS))
Sometimes however you will need to disable autoescaping in templates. This can be
the case if you want to explicitly inject HTML into pages, for example if they come
from a system that generate secure HTML like a markdown to HTML converter.
There are three ways to accomplish that:
In the Python code, wrap the HTML string in a Markup object before passing it to
the template. This is in general the recommended way.
Inside the template, use the |safe lter to explicitly mark a string as safe HTML
({{ myvariable|safe }})
Temporarily disable the autoescape system altogether.
To disable the autoescape system in templates, you can use the {% autoescape %}
block:
{% autoescape false %}
<p>autoescaping is disabled here
<p>{{ will_not_be_escaped }}
{% endautoescape %}
Whenever you do this, please be very cautious about the variables you are using in
this block.
6.5 Registering Filters
If you want to register your own lters in Jinja2 you have two ways to do that.
You can either put them by hand into the jinja_env of the application or use the
template_filter() decorator.
The two following examples work the same and both reverse an object:
@app.template_filter(reverse)
def reverse_filter(s):
return s[::-1]
def reverse_filter(s):
return s[::-1]
app.jinja_env.filters[reverse] = reverse_filter
41
In case of the decorator the argument is optional if you want to use the function name
as name of the lter. Once registered, you can use the lter in your templates in the
same way as Jinja2s builtin lters, for example if you have a Python list in context
called mylist:
{% for x in mylist | reverse %}
{% endfor %}
6.6 Context Processors
To inject newvariables automatically into the context of a template, context processors
exist in Flask. Context processors run before the template is rendered and have the
ability to inject new values into the template context. A context processor is a function
that returns a dictionary. The keys and values of this dictionary are then merged with
the template context, for all templates in the app:
@app.context_processor
def inject_user():
return dict(user=g.user)
The context processor above makes a variable called user available in the template
with the value of g.user. This example is not very interesting because g is available in
templates anyways, but it gives an idea how this works.
Variables are not limited to values; a context processor can also make functions avail-
able to templates (since Python allows passing around functions):
@app.context_processor
def utility_processor():
def format_price(amount, currency=u):
return u{0:.2f}{1}.format(amount, currency)
return dict(format_price=format_price)
The context processor above makes the format_price function available to all templates:
{{ format_price(0.33) }}
You could also build format_price as a template lter (see Registering Filters), but this
demonstrates how to pass functions in a context processor.
42
CHAPTER
SEVEN
TESTING FLASK APPLICATIONS
Something that is untested is broken.
The origin of this quote is unknown and while it is not entirely correct, it is also not
far from the truth. Untested applications make it hard to improve existing code and
developers of untested applications tend to become pretty paranoid. If an application
has automated tests, you can safely make changes and instantly know if anything
breaks.
Flask provides a way to test your application by exposing the Werkzeug test Client
and handling the context locals for you. You can then use that with your favourite
testing solution. In this documentation we will use the unittest package that comes
pre-installed with Python.
7.1 The Application
First, we need an application to test; we will use the application from the Tutorial. If
you dont have that application yet, get the sources from the examples.
7.2 The Testing Skeleton
In order to test the application, we add a second module (askr_tests.py) and create a
unittest skeleton there:
import os
import flaskr
import unittest
import tempfile
class FlaskrTestCase(unittest.TestCase):
def setUp(self):
self.db_fd, flaskr.app.config[DATABASE] = tempfile.mkstemp()
flaskr.app.config[TESTING] = True
self.app = flaskr.app.test_client()
43
flaskr.init_db()
def tearDown(self):
os.close(self.db_fd)
os.unlink(flaskr.app.config[DATABASE])
if __name__ == __main__:
unittest.main()
The code in the setUp() method creates a newtest client and initializes a newdatabase.
This function is called before each individual test function is run. To delete the
database after the test, we close the le and remove it from the lesystem in the
tearDown() method. Additionally during setup the TESTING cong ag is activated.
What it does is disabling the error catching during request handling so that you get
better error reports when performing test requests against the application.
This test client will give us a simple interface to the application. We can trigger test
requests to the application, and the client will also keep track of cookies for us.
Because SQLite3 is lesystem-based we can easily use the temple module to create a
temporary database and initialize it. The mkstemp() function does two things for us: it
returns a low-level le handle and a random le name, the latter we use as database
name. We just have to keep the db_fd around so that we can use the os.close() func-
tion to close the le.
If we now run the test suite, we should see the following output:
$ python flaskr_tests.py
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
Even though it did not run any actual tests, we already know that our askr applica-
tion is syntactically valid, otherwise the import would have died with an exception.
7.3 The First Test
Now its time to start testing the functionality of the application. Lets check that the
application shows No entries here so far if we access the root of the application (/).
To do this, we add a new test method to our class, like this:
class FlaskrTestCase(unittest.TestCase):
def setUp(self):
self.db_fd, flaskr.app.config[DATABASE] = tempfile.mkstemp()
self.app = flaskr.app.test_client()
flaskr.init_db()
44
def tearDown(self):
os.close(self.db_fd)
os.unlink(flaskr.app.config[DATABASE])
def test_empty_db(self):
rv = self.app.get(/)
assert No entries here so far in rv.data
Notice that our test functions begin with the word test; this allows unittest to auto-
matically identify the method as a test to run.
By using self.app.get we can send an HTTP GET request to the application with the
given path. The return value will be a response_class object. We can now use the
data attribute to inspect the return value (as string) from the application. In this case,
we ensure that No entries here so far is part of the output.
Run it again and you should see one passing test:
$ python flaskr_tests.py
.
----------------------------------------------------------------------
Ran 1 test in 0.034s
OK
7.4 Logging In and Out
The majority of the functionality of our application is only available for the adminis-
trative user, so we need a way to log our test client in and out of the application. To do
this, we re some requests to the login and logout pages with the required form data
(username and password). And because the login and logout pages redirect, we tell
the client to follow_redirects.
Add the following two methods to your FlaskrTestCase class:
def login(self, username, password):
return self.app.post(/login, data=dict(
username=username,
password=password
), follow_redirects=True)
def logout(self):
return self.app.get(/logout, follow_redirects=True)
Now we can easily test that logging in and out works and that it fails with invalid
credentials. Add this new test to the class:
def test_login_logout(self):
rv = self.login(admin, default)
assert You were logged in in rv.data
45
rv = self.logout()
assert You were logged out in rv.data
rv = self.login(adminx, default)
assert Invalid username in rv.data
rv = self.login(admin, defaultx)
assert Invalid password in rv.data
7.5 Test Adding Messages
We should also test that adding messages works. Add a new test method like this:
def test_messages(self):
self.login(admin, default)
rv = self.app.post(/add, data=dict(
title=<Hello>,
text=<strong>HTML</strong> allowed here
), follow_redirects=True)
assert No entries here so far not in rv.data
assert <Hello> in rv.data
assert <strong>HTML</strong> allowed here in rv.data
Here we check that HTML is allowed in the text but not in the title, which is the in-
tended behavior.
Running that should now give us three passing tests:
$ python flaskr_tests.py
...
----------------------------------------------------------------------
Ran 3 tests in 0.332s
OK
For more complex tests with headers and status codes, check out the MiniTwit Exam-
ple from the sources which contains a larger test suite.
7.6 Other Testing Tricks
Besides using the test client as shown above, there is also the test_request_context()
method that can be used in combination with the with statement to activate a request
context temporarily. With this you can access the request, g and session objects like
in view functions. Here is a full example that demonstrates this approach:
app = flask.Flask(__name__)
with app.test_request_context(/?name=Peter):
assert flask.request.path == /
assert flask.request.args[name] == Peter
46
All the other objects that are context bound can be used in the same way.
If you want to test your application with different congurations and there does not
seem to be a good way to do that, consider switching to application factories (see
Application Factories).
Note however that if you are using a test request context, the before_request()
functions are not automatically called same for after_request() functions. How-
ever teardown_request() functions are indeed executed when the test request context
leaves the with block. If you do want the before_request() functions to be called as
well, you need to call preprocess_request() yourself:
app = flask.Flask(__name__)
with app.test_request_context(/?name=Peter):
app.preprocess_request()
...
This can be necessary to open database connections or something similar depending
on how your application was designed.
If you want to call the after_request() functions you need to call into
process_response() which however requires that you pass it a response object:
app = flask.Flask(__name__)
with app.test_request_context(/?name=Peter):
resp = Response(...)
resp = app.process_response(resp)
...
This in general is less useful because at that point you can directly start using the test
client.
7.7 Faking Resources and Context
New in version 0.10.
A very common pattern is to store user authorization information and database con-
nections on the application context or the flask.g object. The general pattern for this is
to put the object on there on rst usage and then to remove it on a teardown. Imagine
for instance this code to get the current user:
def get_user():
user = getattr(g, user, None)
if user is None:
user = fetch_current_user_from_database()
g.user = user
return user
47
For a test it would be nice to override this user from the outside without hav-
ing to change some code. This can trivially be accomplished with hooking the
flask.appcontext_pushed signal:
from contextlib import contextmanager
from flask import appcontext_pushed
@contextmanager
def user_set(app, user):
def handler(sender, **kwargs):
g.user = user
with appcontext_pushed.connected_to(handler, app):
yield
And then to use it:
from flask import json, jsonify
@app.route(/users/me)
def users_me():
return jsonify(username=g.user.username)
with user_set(app, my_user):
with app.test_client() as c:
resp = c.get(/users/me)
data = json.loads(resp.data)
self.assert_equal(data[username], my_user.username)
7.8 Keeping the Context Around
New in version 0.4.
Sometimes it is helpful to trigger a regular request but still keep the context around
for a little longer so that additional introspection can happen. With Flask 0.4 this is
possible by using the test_client() with a with block:
app = flask.Flask(__name__)
with app.test_client() as c:
rv = c.get(/?tequila=42)
assert request.args[tequila] == 42
If you were to use just the test_client() without the with block, the assert would fail
with an error because request is no longer available (because you are trying to use it
outside of the actual request).
48
7.9 Accessing and Modifying Sessions
New in version 0.8.
Sometimes it can be very helpful to access or modify the sessions from the test client.
Generally there are two ways for this. If you just want to ensure that a session has
certain keys set to certain values you can just keep the context around and access
flask.session:
with app.test_client() as c:
rv = c.get(/)
assert flask.session[foo] == 42
This however does not make it possible to also modify the session or to access the ses-
sion before a request was red. Starting with Flask 0.8 we provide a so called session
transaction which simulates the appropriate calls to open a session in the context of
the test client and to modify it. At the end of the transaction the session is stored. This
works independently of the session backend used:
with app.test_client() as c:
with c.session_transaction() as sess:
sess[a_key] = a value
# once this is reached the session was stored
Note that in this case you have to use the sess object instead of the flask.session
proxy. The object however itself will provide the same interface.
49
50
CHAPTER
EIGHT
LOGGING APPLICATION ERRORS
New in version 0.3.
Applications fail, servers fail. Sooner or later you will see an exception in production.
Even if your code is 100%correct, you will still see exceptions fromtime to time. Why?
Because everything else involved will fail. Here some situations where perfectly ne
code can lead to server errors:
the client terminated the request early and the application was still reading from
the incoming data.
the database server was overloaded and could not handle the query.
a lesystem is full
a harddrive crashed
a backend server overloaded
a programming error in a library you are using
network connection of the server to another system failed.
And thats just a small sample of issues you could be facing. So how do we deal with
that sort of problem? By default if your application runs in production mode, Flask
will display a very simple page for you and log the exception to the logger.
But there is more you can do, and we will cover some better setups to deal with errors.
8.1 Error Mails
If the application runs in production mode (which it will do on your server) you wont
see any log messages by default. Why is that? Flask tries to be a zero-conguration
framework. Where should it drop the logs for you if there is no conguration? Guess-
ing is not a good idea because chances are, the place it guessed is not the place where
the user has permission to create a logle. Also, for most small applications nobody
will look at the logs anyways.
In fact, I promise you right nowthat if you congure a logle for the application errors
you will never look at it except for debugging an issue when a user reported it for you.
51
What you want instead is a mail the second the exception happened. Then you get an
alert and you can do something about it.
Flask uses the Python builtin logging system, and it can actually send you mails for
errors which is probably what you want. Here is how you can congure the Flask
logger to send you mails for exceptions:
ADMINS = [[email protected]]
if not app.debug:
import logging
from logging.handlers import SMTPHandler
mail_handler = SMTPHandler(127.0.0.1,
[email protected],
ADMINS, YourApplication Failed)
mail_handler.setLevel(logging.ERROR)
app.logger.addHandler(mail_handler)
So what just happened? We created a new SMTPHandler that will send mails with
the mail server listening on 127.0.0.1 to all the ADMINS from the address server-
[email protected] with the subject YourApplication Failed. If your mail server re-
quires credentials, these can also be provided. For that check out the documentation
for the SMTPHandler.
We also tell the handler to only send errors and more critical messages. Because we
certainly dont want to get a mail for warnings or other useless logs that might happen
during request handling.
Before you run that in production, please also look at Controlling the Log Format to put
more information into that error mail. That will save you from a lot of frustration.
8.2 Logging to a File
Even if you get mails, you probably also want to log warnings. Its a good idea to keep
as much information around that might be required to debug a problem. Please note
that Flask itself will not issue any warnings in the core system, so its your responsi-
bility to warn in the code if something seems odd.
There are a couple of handlers provided by the logging system out of the box but not
all of them are useful for basic error logging. The most interesting are probably the
following:
FileHandler - logs messages to a le on the lesystem.
RotatingFileHandler - logs messages to a le on the lesystem and will rotate
after a certain number of messages.
NTEventLogHandler - will log to the system event log of a Windows system. If
you are deploying on a Windows box, this is what you want to use.
SysLogHandler - sends logs to a UNIX syslog.
52
Once you picked your log handler, do like you did with the SMTP handler above, just
make sure to use a lower setting (I would recommend WARNING):
if not app.debug:
import logging
from themodule import TheHandlerYouWant
file_handler = TheHandlerYouWant(...)
file_handler.setLevel(logging.WARNING)
app.logger.addHandler(file_handler)
8.3 Controlling the Log Format
By default a handler will only write the message string into a le or send you that
message as mail. A log record stores more information, and it makes a lot of sense to
congure your logger to also contain that information so that you have a better idea
of why that error happened, and more importantly, where it did.
A formatter can be instantiated with a format string. Note that tracebacks are ap-
pended to the log entry automatically. You dont have to do that in the log formatter
format string.
Here some example setups:
8.3.1 Email
from logging import Formatter
mail_handler.setFormatter(Formatter(
Message type: %(levelname)s
Location: %(pathname)s:%(lineno)d
Module: %(module)s
Function: %(funcName)s
Time: %(asctime)s
Message:
%(message)s
))
8.3.2 File logging
from logging import Formatter
file_handler.setFormatter(Formatter(
%(asctime)s %(levelname)s: %(message)s
[in %(pathname)s:%(lineno)d]
))
53
8.3.3 Complex Log Formatting
Here is a list of useful formatting variables for the format string. Note that this list is
not complete, consult the ofcial documentation of the logging package for a full list.
Format Description
%(levelname)s Text logging level for the message (DEBUG, INFO, WARNING,
ERROR, CRITICAL).
%(pathname)s Full pathname of the source le where the logging call was issued
(if available).
%(filename)s Filename portion of pathname.
%(module)s Module (name portion of lename).
%(funcName)s Name of function containing the logging call.
%(lineno)d Source line number where the logging call was issued (if avail-
able).
%(asctime)s Human-readable time when the LogRecord was created. By de-
fault this is of the form "2003-07-08 16:49:45,896" (the num-
bers after the comma are millisecond portion of the time). This
can be changed by subclassing the formatter and overriding the
formatTime() method.
%(message)s The logged message, computed as msg % args
If you want to further customize the formatting, you can subclass the formatter. The
formatter has three interesting methods:
format(): handles the actual formatting. It is passed a LogRecord object and has to
return the formatted string.
formatTime(): called for asctime formatting. If you want a different time format you
can override this method.
formatException() called for exception formatting. It is passed an exc_info tuple and
has to return a string. The default is usually ne, you dont have to override it.
For more information, head over to the ofcial documentation.
8.4 Other Libraries
So far we only congured the logger your application created itself. Other libraries
might log themselves as well. For example, SQLAlchemy uses logging heavily in its
core. While there is a method to congure all loggers at once in the logging package, I
would not recommend using it. There might be a situation in which you want to have
multiple separate applications running side by side in the same Python interpreter and
then it becomes impossible to have different logging setups for those.
Instead, I would recommend guring out which loggers you are interested in, getting
the loggers with the getLogger() function and iterating over them to attach handlers:
from logging import getLogger
loggers = [app.logger, getLogger(sqlalchemy),
54
getLogger(otherlibrary)]
for logger in loggers:
logger.addHandler(mail_handler)
logger.addHandler(file_handler)
55
56
CHAPTER
NINE
DEBUGGING APPLICATION ERRORS
For production applications, congure your application with logging and notications
as described in Logging Application Errors. This section provides pointers when de-
bugging deployment conguration and digging deeper with a full-featured Python
debugger.
9.1 When in Doubt, Run Manually
Having problems getting your application congured for production? If you have
shell access to your host, verify that you can run your application manually from the
shell in the deployment environment. Be sure to run under the same user account
as the congured deployment to troubleshoot permission issues. You can use Flasks
builtin development server with debug=True on your production host, which is helpful
in catching conguration issues, but be sure to do this temporarily in a controlled
environment. Do not run in production with debug=True.
9.2 Working with Debuggers
To dig deeper, possibly to trace code execution, Flask provides a debugger out of the
box (see Debug Mode). If you would like to use another Python debugger, note that
debuggers interfere with each other. You have to set some options in order to use your
favorite debugger:
debug - whether to enable debug mode and catch exceptions
use_debugger - whether to use the internal Flask debugger
use_reloader - whether to reload and fork the process on exception
debug must be True (i.e., exceptions must be caught) in order for the other two options
to have any value.
If youre using Aptana/Eclipse for debugging youll need to set both use_debugger
and use_reloader to False.
57
A possible useful pattern for conguration is to set the following in your cong.yaml
(change the block as appropriate for your application, of course):
FLASK:
DEBUG: True
DEBUG_WITH_APTANA: True
Then in your applications entry-point (main.py), you could have something like:
if __name__ == "__main__":
# To allow aptana to receive errors, set use_debugger=False
app = create_app(config="config.yaml")
if app.debug: use_debugger = True
try:
# Disable Flasks debugger if external debugger is requested
use_debugger = not(app.config.get(DEBUG_WITH_APTANA))
except:
pass
app.run(use_debugger=use_debugger, debug=app.debug,
use_reloader=use_debugger, host=0.0.0.0)
58
CHAPTER
TEN
CONFIGURATION HANDLING
New in version 0.3.
Applications need some kind of conguration. There are different settings you might
want to change depending on the application environment like toggling the debug
mode, setting the secret key, and other such environment-specic things.
The way Flask is designed usually requires the conguration to be available when the
application starts up. You can hardcode the conguration in the code, which for many
small applications is not actually that bad, but there are better ways.
Independent of how you load your cong, there is a cong object available which
holds the loaded conguration values: The config attribute of the Flask object. This
is the place where Flask itself puts certain conguration values and also where exten-
sions can put their conguration values. But this is also where you can have your own
conguration.
10.1 Conguration Basics
The config is actually a subclass of a dictionary and can be modied just like any
dictionary:
app = Flask(__name__)
app.config[DEBUG] = True
Certain conguration values are also forwarded to the Flask object so you can read
and write them from there:
app.debug = True
To update multiple keys at once you can use the dict.update() method:
app.config.update(
DEBUG=True,
SECRET_KEY=...
)
59
10.2 Builtin Conguration Values
The following conguration values are used internally by Flask:
60
DEBUG enable/disable debug mode
TESTING enable/disable testing mode
PROPAGATE_EXCEPTIONS explicitly enable or disable the propagation of
exceptions. If not set or explicitly set to None
this is implicitly true if either TESTINGor DE-
BUG is true.
PRESERVE_CONTEXT_ON_EXCEPTION By default if the application is in debug mode
the request context is not popped on excep-
tions to enable debuggers to introspect the
data. This can be disabled by this key. You
can also use this setting to force-enable it for
non debug execution which might be useful to
debug production applications (but also very
risky).
SECRET_KEY the secret key
SESSION_COOKIE_NAME the name of the session cookie
SESSION_COOKIE_DOMAIN the domain for the session cookie. If this is not
set, the cookie will be valid for all subdomains
of SERVER_NAME.
SESSION_COOKIE_PATH the path for the session cookie. If this is
not set the cookie will be valid for all of
APPLICATION_ROOT or if that is not set for /.
SESSION_COOKIE_HTTPONLY controls if the cookie should be set with the
httponly ag. Defaults to True.
SESSION_COOKIE_SECURE controls if the cookie should be set with the
secure ag. Defaults to False.
PERMANENT_SESSION_LIFETIME the lifetime of a permanent session as
datetime.timedelta object. Starting with
Flask 0.8 this can also be an integer represent-
ing seconds.
SESSION_REFRESH_EACH_REQUEST this ag controls how permanent sessions are
refreshed. If set to True (which is the de-
fault) then the cookie is refreshed each request
which automatically bumps the lifetime. If set
to False a set-cookie header is only sent if the
session is modied. Non permanent sessions
are not affected by this.
USE_X_SENDFILE enable/disable x-sendle
LOGGER_NAME the name of the logger
SERVER_NAME the name and port number of the server.
Required for subdomain support (e.g.:
myapp.dev:5000) Note that localhost does
not support subdomains so setting this to lo-
calhost does not help. Setting a SERVER_NAME
also by default enables URL generation with-
out a request context but with an application
context.
APPLICATION_ROOT If the application does not occupy a whole do-
main or subdomain this can be set to the path
where the application is congured to live.
This is for session cookie as path value. If do-
mains are used, this should be None.
MAX_CONTENT_LENGTH If set to a value in bytes, Flask will reject in-
coming requests with a content length greater
than this by returning a 413 status code.
SEND_FILE_MAX_AGE_DEFAULT: Default cache control max age to use with
send_static_file() (the default static le
handler) and send_file(), in seconds. Over-
ride this value on a per-le basis using the
get_send_file_max_age() hook on Flask or
Blueprint, respectively. Defaults to 43200 (12
hours).
TRAP_HTTP_EXCEPTIONS If this is set to True Flask will not execute the
error handlers of HTTP exceptions but instead
treat the exception like any other and bubble
it through the exception stack. This is help-
ful for hairy debugging situations where you
have to nd out where an HTTP exception is
coming from.
TRAP_BAD_REQUEST_ERRORS Werkzeugs internal data structures that deal
with request specic data will raise special
key errors that are also bad request excep-
tions. Likewise many operations can implic-
itly fail with a BadRequest exception for con-
sistency. Since its nice for debugging to know
why exactly it failed this ag can be used to
debug those situations. If this cong is set to
True you will get a regular traceback instead.
PREFERRED_URL_SCHEME The URL scheme that should be used for URL
generation if no URL scheme is available. This
defaults to http.
JSON_AS_ASCII By default Flask serialize object to ascii-
encoded JSON. If this is set to False Flask will
not encode to ASCII and output strings as-is
and return unicode strings. jsonify will auto-
matically encode it in utf-8 then for transport
for instance.
JSON_SORT_KEYS By default Flask will serialize JSON objects in
a way that the keys are ordered. This is done
in order to ensure that independent of the
hash seed of the dictionary the return value
will be consistent to not trash external HTTP
caches. You can override the default behav-
ior by changing this variable. This is not rec-
ommended but might give you a performance
improvement on the cost of cachability.
JSONIFY_PRETTYPRINT_REGULAR If this is set to True (the default) jsonify re-
sponses will be pretty printed if they are not
requested by an XMLHttpRequest object (con-
trolled by the X-Requested-With header)
61
More on SERVER_NAME
The SERVER_NAME key is used for the subdomain support. Because Flask cannot guess
the subdomain part without the knowledge of the actual server name, this is required
if you want to work with subdomains. This is also used for the session cookie.
Please keep in mind that not only Flask has the problem of not knowing what sub-
domains are, your web browser does as well. Most modern web browsers will not
allow cross-subdomain cookies to be set on a server name without dots in it. So if
your server name is localhost you will not be able to set a cookie for localhost
and every subdomain of it. Please chose a different server name in that case, like
myapplication.local and add this name + the subdomains you want to use into
your host cong or setup a local bind.
New in version 0.4: LOGGER_NAME
New in version 0.5: SERVER_NAME
New in version 0.6: MAX_CONTENT_LENGTH
New in version 0.7: PROPAGATE_EXCEPTIONS, PRESERVE_CONTEXT_ON_EXCEPTION
New in version 0.8: TRAP_BAD_REQUEST_ERRORS, TRAP_HTTP_EXCEPTIONS,
APPLICATION_ROOT, SESSION_COOKIE_DOMAIN, SESSION_COOKIE_PATH,
SESSION_COOKIE_HTTPONLY, SESSION_COOKIE_SECURE
New in version 0.9: PREFERRED_URL_SCHEME
New in version 0.10: JSON_AS_ASCII, JSON_SORT_KEYS, JSONIFY_PRETTYPRINT_REGULAR
New in version 1.0: SESSION_REFRESH_EACH_REQUEST
10.3 Conguring from Files
Conguration becomes more useful if you can store it in a separate le, ideally located
outside the actual application package. This makes packaging and distributing your
application possible via various package handling tools (Deploying with Distribute) and
nally modifying the conguration le afterwards.
So a common pattern is this:
app = Flask(__name__)
app.config.from_object(yourapplication.default_settings)
app.config.from_envvar(YOURAPPLICATION_SETTINGS)
This rst loads the conguration from the yourapplication.default_settings module and
then overrides the values with the contents of the le the YOURAPPLICATION_SETTINGS
environment variable points to. This environment variable can be set on Linux or OS
X with the export command in the shell before starting the server:
62
$ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg
$ python run-app.py
* Running on http://127.0.0.1:5000/
* Restarting with reloader...
On Windows systems use the set builtin instead:
>set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg
The conguration les themselves are actual Python les. Only values in uppercase
are actually stored in the cong object later on. So make sure to use uppercase letters
for your cong keys.
Here is an example of a conguration le:
# Example configuration
DEBUG = False
SECRET_KEY = ?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83
Make sure to load the conguration very early on, so that extensions have the ability
to access the conguration when starting up. There are other methods on the cong
object as well to load from individual les. For a complete reference, read the Config
objects documentation.
10.4 Conguration Best Practices
The downside with the approach mentioned earlier is that it makes testing a little
harder. There is no single 100% solution for this problem in general, but there are a
couple of things you can keep in mind to improve that experience:
1. create your application in a function and register blueprints on it. That way you
can create multiple instances of your application with different congurations
attached which makes unittesting a lot easier. You can use this to pass in cong-
uration as needed.
2. Do not write code that needs the conguration at import time. If you limit your-
self to request-only accesses to the conguration you can recongure the object
later on as needed.
10.5 Development / Production
Most applications need more than one conguration. There should be at least separate
congurations for the production server and the one used during development. The
easiest way to handle this is to use a default conguration that is always loaded and
part of the version control, and a separate conguration that overrides the values as
necessary as mentioned in the example above:
63
app = Flask(__name__)
app.config.from_object(yourapplication.default_settings)
app.config.from_envvar(YOURAPPLICATION_SETTINGS)
Then you just have to add a separate cong.py le and export
YOURAPPLICATION_SETTINGS=/path/to/config.py and you are done. However
there are alternative ways as well. For example you could use imports or subclassing.
What is very popular in the Django world is to make the import explicit in the cong
le by adding an from yourapplication.default_settings import * to the top of the
le and then overriding the changes by hand. You could also inspect an environment
variable like YOURAPPLICATION_MODE and set that to production, development etc and im-
port different hardcoded les based on that.
An interesting pattern is also to use classes and inheritance for conguration:
class Config(object):
DEBUG = False
TESTING = False
DATABASE_URI = sqlite://:memory:
class ProductionConfig(Config):
DATABASE_URI = mysql://user@localhost/foo
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
TESTING = True
To enable such a cong you just have to call into from_object():
app.config.from_object(configmodule.ProductionConfig)
There are many different ways and its up to you how you want to manage your con-
guration les. However here a list of good recommendations:
keep a default conguration in version control. Either populate the cong with
this default conguration or import it in your own conguration les before
overriding values.
use an environment variable to switch between the congurations. This can be
done from outside the Python interpreter and makes development and deploy-
ment much easier because you can quickly and easily switch between different
congs without having to touch the code at all. If you are working often on dif-
ferent projects you can even create your own script for sourcing that activates a
virtualenv and exports the development conguration for you.
Use a tool like fabric in production to push code and congurations separately
to the production server(s). For some details about how to do that, head over to
the Deploying with Fabric pattern.
64
10.6 Instance Folders
New in version 0.8.
Flask 0.8 introduces instance folders. Flask for a long time made it possible to refer to
paths relative to the applications folder directly (via Flask.root_path). This was also
how many developers loaded congurations stored next to the application. Unfortu-
nately however this only works well if applications are not packages in which case the
root path refers to the contents of the package.
With Flask 0.8 a new attribute was introduced: Flask.instance_path. It refers to a
new concept called the instance folder. The instance folder is designed to not be
under version control and be deployment specic. Its the perfect place to drop things
that either change at runtime or conguration les.
You can either explicitly provide the path of the instance folder when creating the
Flask application or you can let Flask autodetect the instance folder. For explicit con-
guration use the instance_path parameter:
app = Flask(__name__, instance_path=/path/to/instance/folder)
Please keep in mind that this path must be absolute when provided.
If the instance_path parameter is not provided the following default locations are used:
Uninstalled module:
/myapp.py
/instance
Uninstalled package:
/myapp
/__init__.py
/instance
Installed module or package:
$PREFIX/lib/python2.X/site-packages/myapp
$PREFIX/var/myapp-instance
$PREFIX is the prex of your Python installation. This can be /usr or the path to
your virtualenv. You can print the value of sys.prefix to see what the prex is
set to.
Since the cong object provided loading of conguration les from relative lenames
we made it possible to change the loading via lenames to be relative to the instance
path if wanted. The behavior of relative paths in cong les can be ipped between
relative to the application root (the default) to relative to instance folder via the
instance_relative_cong switch to the application constructor:
app = Flask(__name__, instance_relative_config=True)
65
Here is a full example of how to congure Flask to preload the cong from a module
and then override the cong from a le in the cong folder if it exists:
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(yourapplication.default_settings)
app.config.from_pyfile(application.cfg, silent=True)
The path to the instance folder can be found via the Flask.instance_path.
Flask also provides a shortcut to open a le from the instance folder with
Flask.open_instance_resource().
Example usage for both:
filename = os.path.join(app.instance_path, application.cfg)
with open(filename) as f:
config = f.read()
# or via open_instance_resource:
with app.open_instance_resource(application.cfg) as f:
config = f.read()
66
CHAPTER
ELEVEN
SIGNALS
New in version 0.6.
Starting with Flask 0.6, there is integrated support for signalling in Flask. This support
is provided by the excellent blinker library and will gracefully fall back if it is not
available.
What are signals? Signals help you decouple applications by sending notications
when actions occur elsewhere in the core framework or another Flask extensions. In
short, signals allow certain senders to notify subscribers that something happened.
Flask comes with a couple of signals and other extensions might provide more. Also
keep in mind that signals are intended to notify subscribers and should not encourage
subscribers to modify data. You will notice that there are signals that appear to do
the same thing like some of the builtin decorators do (eg: request_started is very
similar to before_request()). There are however difference in how they work. The
core before_request() handler for example is executed in a specic order and is able
to abort the request early by returning a response. In contrast all signal handlers are
executed in undened order and do not modify any data.
The big advantage of signals over handlers is that you can safely subscribe to them
for the split of a second. These temporary subscriptions are helpful for unittesting for
example. Say you want to know what templates were rendered as part of a request:
signals allow you to do exactly that.
11.1 Subscribing to Signals
To subscribe to a signal, you can use the connect() method of a signal. The rst ar-
gument is the function that should be called when the signal is emitted, the optional
second argument species a sender. To unsubscribe from a signal, you can use the
disconnect() method.
For all core Flask signals, the sender is the application that issued the signal. When
you subscribe to a signal, be sure to also provide a sender unless you really want to
listen for signals of all applications. This is especially true if you are developing an
extension.
67
Here for example a helper context manager that can be used to gure out in a unittest
which templates were rendered and what variables were passed to the template:
from flask import template_rendered
from contextlib import contextmanager
@contextmanager
def captured_templates(app):
recorded = []
def record(sender, template, context, **extra):
recorded.append((template, context))
template_rendered.connect(record, app)
try:
yield recorded
finally:
template_rendered.disconnect(record, app)
This can now easily be paired with a test client:
with captured_templates(app) as templates:
rv = app.test_client().get(/)
assert rv.status_code == 200
assert len(templates) == 1
template, context = templates[0]
assert template.name == index.html
assert len(context[items]) == 10
Make sure to subscribe with an extra **extra argument so that your calls dont fail if
Flask introduces new arguments to the signals.
All the template rendering in the code issued by the application app in the body of
the with block will now be recorded in the templates variable. Whenever a template is
rendered, the template object as well as context are appended to it.
Additionally there is a convenient helper method (connected_to()). that allows you
to temporarily subscribe a function to a signal with a context manager on its own.
Because the return value of the context manager cannot be specied that way one has
to pass the list in as argument:
from flask import template_rendered
def captured_templates(app, recorded, **extra):
def record(sender, template, context):
recorded.append((template, context))
return template_rendered.connected_to(record, app)
The example above would then look like this:
templates = []
with captured_templates(app, templates, **extra):
...
template, context = templates[0]
68
Blinker API Changes
The connected_to() method arrived in Blinker with version 1.1.
11.2 Creating Signals
If you want to use signals in your own application, you can use the blinker library
directly. The most common use case are named signals in a custom Namespace.. This is
what is recommended most of the time:
from blinker import Namespace
my_signals = Namespace()
Now you can create new signals like this:
model_saved = my_signals.signal(model-saved)
The name for the signal here makes it unique and also simplies debugging. You can
access the name of the signal with the name attribute.
For Extension Developers
If you are writing a Flask extension and you want to gracefully degrade for missing
blinker installations, you can do so by using the flask.signals.Namespace class.
11.3 Sending Signals
If you want to emit a signal, you can do so by calling the send() method. It accepts a
sender as rst argument and optionally some keyword arguments that are forwarded
to the signal subscribers:
class Model(object):
...
def save(self):
model_saved.send(self)
Try to always pick a good sender. If you have a class that is emitting a signal,
pass self as sender. If you emitting a signal from a random function, you can pass
current_app._get_current_object() as sender.
Passing Proxies as Senders
Never pass current_app as sender to a signal. Use
current_app._get_current_object() instead. The reason for this is that current_app
is a proxy and not the real application object.
69
11.4 Signals and Flasks Request Context
Signals fully support The Request Context when receiving signals. Context-local vari-
ables are consistently available between request_started and request_finished, so
you can rely on flask.g and others as needed. Note the limitations described in Send-
ing Signals and the request_tearing_down signal.
11.5 Decorator Based Signal Subscriptions
With Blinker 1.1 you can also easily subscribe to signals by using the new
connect_via() decorator:
from flask import template_rendered
@template_rendered.connect_via(app)
def when_template_rendered(sender, template, context, **extra):
print Template %s is rendered with %s % (template.name, context)
11.6 Core Signals
The following signals exist in Flask:
flask.template_rendered
This signal is sent when a template was successfully rendered. The signal is in-
voked with the instance of the template as template and the context as dictionary
(named context).
Example subscriber:
def log_template_renders(sender, template, context, **extra):
sender.logger.debug(Rendering template "%s" with context %s,
template.name or string template,
context)
from flask import template_rendered
template_rendered.connect(log_template_renders, app)
flask.request_started
This signal is sent before any request processing started but when the request
context was set up. Because the request context is already bound, the subscriber
can access the request with the standard global proxies such as request.
Example subscriber:
def log_request(sender, **extra):
sender.logger.debug(Request context is set up)
70
from flask import request_started
request_started.connect(log_request, app)
flask.request_finished
This signal is sent right before the response is sent to the client. It is passed the
response to be sent named response.
Example subscriber:
def log_response(sender, response, **extra):
sender.logger.debug(Request context is about to close down.
Response: %s, response)
from flask import request_finished
request_finished.connect(log_response, app)
flask.got_request_exception
This signal is sent when an exception happens during request processing. It is
sent before the standard exception handling kicks in and even in debug mode,
where no exception handling happens. The exception itself is passed to the sub-
scriber as exception.
Example subscriber:
def log_exception(sender, exception, **extra):
sender.logger.debug(Got exception during processing: %s, exception)
from flask import got_request_exception
got_request_exception.connect(log_exception, app)
flask.request_tearing_down
This signal is sent when the request is tearing down. This is always called, even
if an exception is caused. Currently functions listening to this signal are called
after the regular teardown handlers, but this is not something you can rely on.
Example subscriber:
def close_db_connection(sender, **extra):
session.close()
from flask import request_tearing_down
request_tearing_down.connect(close_db_connection, app)
As of Flask 0.9, this will also be passed an exc keyword argument that has a
reference to the exception that caused the teardown if there was one.
flask.appcontext_tearing_down
This signal is sent when the app context is tearing down. This is always called,
even if an exception is caused. Currently functions listening to this signal are
called after the regular teardown handlers, but this is not something you can
rely on.
Example subscriber:
71
def close_db_connection(sender, **extra):
session.close()
from flask import appcontext_tearing_down
appcontext_tearing_down.connect(close_db_connection, app)
This will also be passed an exc keyword argument that has a reference to the
exception that caused the teardown if there was one.
flask.appcontext_pushed
This signal is sent when an application context is pushed. The sender is the
application. This is usually useful for unittests in order to temporarily hook in
information. For instance it can be used to set a resource early onto the g object.
Example usage:
from contextlib import contextmanager
from flask import appcontext_pushed
@contextmanager
def user_set(app, user):
def handler(sender, **kwargs):
g.user = user
with appcontext_pushed.connected_to(handler, app):
yield
And in the testcode:
def test_user_me(self):
with user_set(app, john):
c = app.test_client()
resp = c.get(/users/me)
assert resp.data == username=john
New in version 0.10.
flask.appcontext_popped
This signal is sent when an application context is popped. The sender is the
application. This usually falls in line with the appcontext_tearing_down signal.
New in version 0.10.
flask.message_flashed
This signal is sent when the application is ashing a message. The messages is
sent as message keyword argument and the category as category.
Example subscriber:
recorded = []
def record(sender, message, category, **extra):
recorded.append((message, category))
from flask import message_flashed
message_flashed.connect(record, app)
72
New in version 0.10.
73
74
CHAPTER
TWELVE
PLUGGABLE VIEWS
New in version 0.7.
Flask 0.7 introduces pluggable views inspired by the generic views fromDjango which
are based on classes instead of functions. The main intention is that you can replace
parts of the implementations and this way have customizable pluggable views.
12.1 Basic Principle
Consider you have a function that loads a list of objects from the database and renders
into a template:
@app.route(/users/)
def show_users(page):
users = User.query.all()
return render_template(users.html, users=users)
This is simple and exible, but if you want to provide this view in a generic fashion
that can be adapted to other models and templates as well you might want more ex-
ibility. This is where pluggable class-based views come into place. As the rst step to
convert this into a class based view you would do this:
from flask.views import View
class ShowUsers(View):
def dispatch_request(self):
users = User.query.all()
return render_template(users.html, objects=users)
app.add_url_rule(/users/, view_func=ShowUsers.as_view(show_users))
As you can see what you have to do is to create a subclass of flask.views.View and im-
plement dispatch_request(). Then we have to convert that class into an actual view
function by using the as_view() class method. The string you pass to that function is
the name of the endpoint that view will then have. But this by itself is not helpful, so
lets refactor the code a bit:
75
from flask.views import View
class ListView(View):
def get_template_name(self):
raise NotImplementedError()
def render_template(self, context):
return render_template(self.get_template_name(), **context)
def dispatch_request(self):
context = {objects: self.get_objects()}
return self.render_template(context)
class UserView(ListView):
def get_template_name(self):
return users.html
def get_objects(self):
return User.query.all()
This of course is not that helpful for such a small example, but its good enough to
explain the basic principle. When you have a class-based view the question comes up
what self points to. The way this works is that whenever the request is dispatched a
new instance of the class is created and the dispatch_request() method is called with
the parameters from the URL rule. The class itself is instantiated with the parameters
passed to the as_view() function. For instance you can write a class like this:
class RenderTemplateView(View):
def __init__(self, template_name):
self.template_name = template_name
def dispatch_request(self):
return render_template(self.template_name)
And then you can register it like this:
app.add_url_rule(/about, view_func=RenderTemplateView.as_view(
about_page, template_name=about.html))
12.2 Method Hints
Pluggable views are attached to the application like a regular function by either using
route() or better add_url_rule(). That however also means that you would have to
provide the names of the HTTP methods the view supports when you attach this. In
order to move that information to the class you can provide a methods attribute that
has this information:
76
class MyView(View):
methods = [GET, POST]
def dispatch_request(self):
if request.method == POST:
...
...
app.add_url_rule(/myview, view_func=MyView.as_view(myview))
12.3 Method Based Dispatching
For RESTful APIs its especially helpful to execute a different function for each HTTP
method. With the flask.views.MethodView you can easily do that. Each HTTP method
maps to a function with the same name (just in lowercase):
from flask.views import MethodView
class UserAPI(MethodView):
def get(self):
users = User.query.all()
...
def post(self):
user = User.from_form_data(request.form)
...
app.add_url_rule(/users/, view_func=UserAPI.as_view(users))
That way you also dont have to provide the methods attribute. Its automatically set
based on the methods dened in the class.
12.4 Decorating Views
Since the view class itself is not the view function that is added to the routing system
it does not make much sense to decorate the class itself. Instead you either have to
decorate the return value of as_view() by hand:
def user_required(f):
"""Checks whether user is logged in or raises error 401."""
def decorator(*args, **kwargs):
if not g.user:
abort(401)
return f(*args, **kwargs)
return decorator
77
view = user_required(UserAPI.as_view(users))
app.add_url_rule(/users/, view_func=view)
Starting with Flask 0.8 there is also an alternative way where you can specify a list of
decorators to apply in the class declaration:
class UserAPI(MethodView):
decorators = [user_required]
Due to the implicit self from the callers perspective you cannot use regular view dec-
orators on the individual methods of the view however, keep this in mind.
12.5 Method Views for APIs
Web APIs are often working very closely with HTTP verbs so it makes a lot of sense
to implement such an API based on the MethodView. That said, you will notice that the
API will require different URL rules that go to the same method viewmost of the time.
For instance consider that you are exposing a user object on the web:
URL Method Description
/users/ GET Gives a list of all users
/users/ POST Creates a new user
/users/<id> GET Shows a single user
/users/<id> PUT Updates a single user
/users/<id> DELETE Deletes a single user
So how would you go about doing that with the MethodView? The trick is to take
advantage of the fact that you can provide multiple rules to the same view.
Lets assume for the moment the view would look like this:
class UserAPI(MethodView):
def get(self, user_id):
if user_id is None:
# return a list of users
pass
else:
# expose a single user
pass
def post(self):
# create a new user
pass
def delete(self, user_id):
# delete a single user
pass
def put(self, user_id):
78
# update a single user
pass
So how do we hook this up with the routing system? By adding two rules and explic-
itly mentioning the methods for each:
user_view = UserAPI.as_view(user_api)
app.add_url_rule(/users/, defaults={user_id: None},
view_func=user_view, methods=[GET,])
app.add_url_rule(/users/, view_func=user_view, methods=[POST,])
app.add_url_rule(/users/<int:user_id>, view_func=user_view,
methods=[GET, PUT, DELETE])
If you have a lot of APIs that look similar you can refactor that registration code:
def register_api(view, endpoint, url, pk=id, pk_type=int):
view_func = view.as_view(endpoint)
app.add_url_rule(url, defaults={pk: None},
view_func=view_func, methods=[GET,])
app.add_url_rule(url, view_func=view_func, methods=[POST,])
app.add_url_rule(%s<%s:%s> % (url, pk_type, pk), view_func=view_func,
methods=[GET, PUT, DELETE])
register_api(UserAPI, user_api, /users/, pk=user_id)
79
80
CHAPTER
THIRTEEN
THE APPLICATION CONTEXT
New in version 0.9.
One of the design ideas behind Flask is that there are two different states in which
code is executed. The application setup state in which the application implicitly is on
the module level. It starts when the Flask object is instantiated, and it implicitly ends
when the rst request comes in. While the application is in this state a fewassumptions
are true:
the programmer can modify the application object safely.
no request handling happened so far
you have to have a reference to the application object in order to modify it, there
is no magic proxy that can give you a reference to the application object youre
currently creating or modifying.
In contrast, during request handling, a couple of other rules exist:
while a request is active, the context local objects (flask.request and others)
point to the current request.
any code can get hold of these objects at any time.
There is a third state which is sitting in between a little bit. Sometimes you are dealing
with an application in a way that is similar to how you interact with applications
during request handling just that there is no request active. Consider for instance that
youre sitting in an interactive Python shell and interacting with the application, or a
command line application.
The application context is what powers the current_app context local.
13.1 Purpose of the Application Context
The main reason for the applications context existence is that in the past a bunch of
functionality was attached to the request context in lack of a better solution. Since one
of the pillars of Flasks design is that you can have more than one application in the
same Python process.
81
So how does the code nd the right application? In the past we recommended pass-
ing applications around explicitly, but that caused issues with libraries that were not
designed with that in mind.
A common workaround for that problem was to use the current_app proxy later on,
which was bound to the current requests application reference. Since however creat-
ing such a request context is an unnecessarily expensive operation in case there is no
request around, the application context was introduced.
13.2 Creating an Application Context
To make an application context there are two ways. The rst one is the implicit one:
whenever a request context is pushed, an application context will be created alongside
if this is necessary. As a result of that, you can ignore the existence of the application
context unless you need it.
The second way is the explicit way using the app_context() method:
from flask import Flask, current_app
app = Flask(__name__)
with app.app_context():
# within this block, current_app points to app.
print current_app.name
The application context is also used by the url_for() function in case a SERVER_NAME
was congured. This allows you to generate URLs even in the absence of a request.
13.3 Locality of the Context
The application context is created and destroyed as necessary. It never moves between
threads and it will not be shared between requests. As such it is the perfect place to
store database connection information and other things. The internal stack object is
called flask._app_ctx_stack. Extensions are free to store additional information on
the topmost level, assuming they pick a sufciently unique name and should put their
information there, instead of on the flask.g object which is reserved for user code.
For more information about that, see Flask Extension Development.
13.4 Context Usage
The context is typically used to cache resources on there that need to be created on
a per-request or usage case. For instance database connects are destined to go there.
When storing things on the application context unique names should be chosen as this
is a place that is shared between Flask applications and extensions.
82
The most common usage is to split resource management into two parts:
1. an implicit resource caching on the context.
2. a context teardown based resource deallocation.
Generally there would be a get_X() function that creates resource X if it does not ex-
ist yet and otherwise returns the same resource, and a teardown_X() function that is
registered as teardown handler.
This is an example that connects to a database:
import sqlite3
from flask import g
def get_db():
db = getattr(g, _database, None)
if db is None:
db = g._database = connect_to_database()
return db
@app.teardown_appcontext
def teardown_db(exception):
db = getattr(g, _database, None)
if db is not None:
db.close()
The rst time get_db() is called the connection will be established. To make this im-
plicit a LocalProxy can be used:
from werkzeug.local import LocalProxy
db = LocalProxy(get_db)
That way a user can directly access db which internally calls get_db().
83
84
CHAPTER
FOURTEEN
THE REQUEST CONTEXT
This document describes the behavior in Flask 0.7 which is mostly in line with the old
behavior but has some small, subtle differences.
It is recommended that you read the The Application Context chapter rst.
14.1 Diving into Context Locals
Say you have a utility function that returns the URL the user should be redirected to.
Imagine it would always redirect to the URLs next parameter or the HTTP referrer or
the index page:
from flask import request, url_for
def redirect_url():
return request.args.get(next) or \
request.referrer or \
url_for(index)
As you can see, it accesses the request object. If you try to run this from a plain Python
shell, this is the exception you will see:
>>> redirect_url()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: NoneType object has no attribute request
That makes a lot of sense because we currently do not have a request we could
access. So we have to make a request and bind it to the current context. The
test_request_context method can create us a RequestContext:
>>> ctx = app.test_request_context(/?next=http://example.com/)
This context can be used in two ways. Either with the with statement or by calling the
push() and pop() methods:
>>> ctx.push()
85
From that point onwards you can work with the request object:
>>> redirect_url()
uhttp://example.com/
Until you call pop:
>>> ctx.pop()
Because the request context is internally maintained as a stack you can push and pop
multiple times. This is very handy to implement things like internal redirects.
For more information of how to utilize the request context from the interactive Python
shell, head over to the Working with the Shell chapter.
14.2 How the Context Works
If you look into howthe Flask WSGI application internally works, you will nd a piece
of code that looks very much like this:
def wsgi_app(self, environ):
with self.request_context(environ):
try:
response = self.full_dispatch_request()
except Exception, e:
response = self.make_response(self.handle_exception(e))
return response(environ, start_response)
The method request_context() returns a new RequestContext object and uses it in
combination with the with statement to bind the context. Everything that is called
from the same thread from this point onwards until the end of the with statement will
have access to the request globals (flask.request and others).
The request context internally works like a stack: The topmost level on the stack is
the current active request. push() adds the context to the stack on the very top, pop()
removes it from the stack again. On popping the applications teardown_request()
functions are also executed.
Another thing of note is that the request context will automatically also create an appli-
cation context when its pushed and there is no application context for that application
so far.
14.3 Callbacks and Errors
What happens if an error occurs in Flask during request processing? This particular
behavior changed in 0.7 because we wanted to make it easier to understand what is
actually happening. The new behavior is quite simple:
86
1. Before each request, before_request() functions are executed. If one of these
functions return a response, the other functions are no longer called. In any case
however the return value is treated as a replacement for the views return value.
2. If the before_request() functions did not return a response, the regular request
handling kicks in and the view function that was matched has the chance to
return a response.
3. The return value of the view is then converted into an actual response object and
handed over to the after_request() functions which have the chance to replace
it or modify it in place.
4. At the end of the request the teardown_request() functions are executed. This
always happens, even in case of an unhandled exception down the road or if a
before-request handler was not executed yet or at all (for example in test envi-
ronments sometimes you might want to not execute before-request callbacks).
Now what happens on errors? In production mode if an exception is not caught, the
500 internal server handler is called. In development mode however the exception is
not further processed and bubbles up to the WSGI server. That way things like the
interactive debugger can provide helpful debug information.
An important change in 0.7 is that the internal server error is now no longer post
processed by the after request callbacks and after request callbacks are no longer guar-
anteed to be executed. This way the internal dispatching code looks cleaner and is
easier to customize and understand.
The new teardown functions are supposed to be used as a replacement for things that
absolutely need to happen at the end of request.
14.4 Teardown Callbacks
The teardown callbacks are special callbacks in that they are executed at a different
point. Strictly speaking they are independent of the actual request handling as they
are bound to the lifecycle of the RequestContext object. When the request context is
popped, the teardown_request() functions are called.
This is important to know if the life of the request context is prolonged by using the
test client in a with statement or when using the request context from the command
line:
with app.test_client() as client:
resp = client.get(/foo)
# the teardown functions are still not called at that point
# even though the response ended and you have the response
# object in your hand
# only when the code reaches this point the teardown functions
# are called. Alternatively the same thing happens if another
# request was triggered from the test client
87
Its easy to see the behavior from the command line:
>>> app = Flask(__name__)
>>> @app.teardown_request
... def teardown_request(exception=None):
... print this runs after request
...
>>> ctx = app.test_request_context()
>>> ctx.push()
>>> ctx.pop()
this runs after request
>>>
Keep in mind that teardown callbacks are always executed, even if before-request call-
backs were not executed yet but an exception happened. Certain parts of the test sys-
tem might also temporarily create a request context without calling the before-request
handlers. Make sure to write your teardown-request handlers in a way that they will
never fail.
14.5 Notes On Proxies
Some of the objects provided by Flask are proxies to other objects. The reason behind
this is that these proxies are shared between threads and they have to dispatch to the
actual object bound to a thread behind the scenes as necessary.
Most of the time you dont have to care about that, but there are some exceptions
where it is good to know that this object is an actual proxy:
The proxy objects do not fake their inherited types, so if you want to perform
actual instance checks, you have to do that on the instance that is being proxied
(see _get_current_object below).
if the object reference is important (so for example for sending Signals)
If you need to get access to the underlying object that is proxied, you can use the
_get_current_object() method:
app = current_app._get_current_object()
my_signal.send(app)
14.6 Context Preservation on Error
If an error occurs or not, at the end of the request the request context is popped and
all data associated with it is destroyed. During development however that can be
problematic as you might want to have the information around for a longer time in
case an exception occurred. In Flask 0.6 and earlier in debug mode, if an exception
occurred, the request context was not popped so that the interactive debugger can still
provide you with important information.
88
Starting with Flask 0.7 you have ner control over that behavior by setting the
PRESERVE_CONTEXT_ON_EXCEPTION conguration variable. By default its linked to the
setting of DEBUG. If the application is in debug mode the context is preserved, in pro-
duction mode its not.
Do not force activate PRESERVE_CONTEXT_ON_EXCEPTION in production mode as it will
cause your application to leak memory on exceptions. However it can be useful during
development to get the same error preserving behavior as in development mode when
attempting to debug an error that only occurs under production settings.
89
90
CHAPTER
FIFTEEN
MODULAR APPLICATIONS WITH
BLUEPRINTS
New in version 0.7.
Flask uses a concept of blueprints for making application components and supporting
common patterns within an application or across applications. Blueprints can greatly
simplify howlarge applications work and provide a central means for Flask extensions
to register operations on applications. A Blueprint object works similarly to a Flask
application object, but it is not actually an application. Rather it is a blueprint of how
to construct or extend an application.
15.1 Why Blueprints?
Blueprints in Flask are intended for these cases:
Factor an application into a set of blueprints. This is ideal for larger applications;
a project could instantiate an application object, initialize several extensions, and
register a collection of blueprints.
Register a blueprint on an application at a URL prex and/or subdomain. Pa-
rameters in the URL prex/subdomain become common view arguments (with
defaults) across all view functions in the blueprint.
Register a blueprint multiple times on an application with different URL rules.
Provide template lters, static les, templates, and other utilities through
blueprints. A blueprint does not have to implement applications or view func-
tions.
Register a blueprint on an application for any of these cases when initializing a
Flask extension.
A blueprint in Flask is not a pluggable app because it is not actually an application
its a set of operations which can be registered on an application, even multiple
times. Why not have multiple application objects? You can do that (see Application
Dispatching), but your applications will have separate congs and will be managed at
the WSGI layer.
91
Blueprints instead provide separation at the Flask level, share application cong, and
can change an application object as necessary with being registered. The downside is
that you cannot unregister a blueprint once an application was created without having
to destroy the whole application object.
15.2 The Concept of Blueprints
The basic concept of blueprints is that they record operations to execute when reg-
istered on an application. Flask associates view functions with blueprints when dis-
patching requests and generating URLs from one endpoint to another.
15.3 My First Blueprint
This is what a very basic blueprint looks like. In this case we want to implement a
blueprint that does simple rendering of static templates:
from flask import Blueprint, render_template, abort
from jinja2 import TemplateNotFound
simple_page = Blueprint(simple_page, __name__,
template_folder=templates)
@simple_page.route(/, defaults={page: index})
@simple_page.route(/<page>)
def show(page):
try:
return render_template(pages/%s.html % page)
except TemplateNotFound:
abort(404)
When you bind a function with the help of the @simple_page.route decorator the
blueprint will record the intention of registering the function show on the application
when its later registered. Additionally it will prex the endpoint of the function with
the name of the blueprint which was given to the Blueprint constructor (in this case
also simple_page).
15.4 Registering Blueprints
So how do you register that blueprint? Like this:
from flask import Flask
from yourapplication.simple_page import simple_page
app = Flask(__name__)
app.register_blueprint(simple_page)
92
If you check the rules registered on the application, you will nd these:
[<Rule /static/<filename> (HEAD, OPTIONS, GET) -> static>,
<Rule /<page> (HEAD, OPTIONS, GET) -> simple_page.show>,
<Rule / (HEAD, OPTIONS, GET) -> simple_page.show>]
The rst one is obviously from the application ifself for the static les. The other two
are for the show function of the simple_page blueprint. As you can see, they are also
prexed with the name of the blueprint and separated by a dot (.).
Blueprints however can also be mounted at different locations:
app.register_blueprint(simple_page, url_prefix=/pages)
And sure enough, these are the generated rules:
[<Rule /static/<filename> (HEAD, OPTIONS, GET) -> static>,
<Rule /pages/<page> (HEAD, OPTIONS, GET) -> simple_page.show>,
<Rule /pages/ (HEAD, OPTIONS, GET) -> simple_page.show>]
On top of that you can register blueprints multiple times though not every blueprint
might respond properly to that. In fact it depends on how the blueprint is imple-
mented if it can be mounted more than once.
15.5 Blueprint Resources
Blueprints can provide resources as well. Sometimes you might want to introduce a
blueprint only for the resources it provides.
15.5.1 Blueprint Resource Folder
Like for regular applications, blueprints are considered to be contained in a folder.
While multiple blueprints can originate from the same folder, it does not have to be
the case and its usually not recommended.
The folder is inferred from the second argument to Blueprint which is usually
__name__. This argument species what logical Python module or package corre-
sponds to the blueprint. If it points to an actual Python package that package (which is
a folder on the lesystem) is the resource folder. If its a module, the package the mod-
ule is contained in will be the resource folder. You can access the Blueprint.root_path
property to see what the resource folder is:
>>> simple_page.root_path
/Users/username/TestProject/yourapplication
To quickly open sources from this folder you can use the open_resource() function:
with simple_page.open_resource(static/style.css) as f:
code = f.read()
93
15.5.2 Static Files
A blueprint can expose a folder with static les by providing a path to a folder on the
lesystem via the static_folder keyword argument. It can either be an absolute path or
one relative to the folder of the blueprint:
admin = Blueprint(admin, __name__, static_folder=static)
By default the rightmost part of the path is where it is exposed on the web. Because
the folder is called static here it will be available at the location of the blueprint
+ /static. Say the blueprint is registered for /admin the static folder will be at
/admin/static.
The endpoint is named blueprint_name.static so you can generate URLs to it like you
would do to the static folder of the application:
url_for(admin.static, filename=style.css)
15.5.3 Templates
If you want the blueprint to expose templates you can do that by providing the tem-
plate_folder parameter to the Blueprint constructor:
admin = Blueprint(admin, __name__, template_folder=templates)
As for static les, the path can be absolute or relative to the blueprint resource folder.
The template folder is added to the searchpath of templates but with a lower prior-
ity than the actual applications template folder. That way you can easily override
templates that a blueprint provides in the actual application.
So if you have a blueprint in the folder yourapplication/admin and you
want to render the template admin/index.html and you have provided
templates as a template_folder you will have to create a le like this:
yourapplication/admin/templates/admin/index.html.
15.6 Building URLs
If you want to link from one page to another you can use the url_for() function just
like you normally would do just that you prex the URL endpoint with the name of
the blueprint and a dot (.):
url_for(admin.index)
Additionally if you are in a view function of a blueprint or a rendered template and
you want to link to another endpoint of the same blueprint, you can use relative redi-
rects by prexing the endpoint with a dot only:
94
url_for(.index)
This will link to admin.index for instance in case the current request was dispatched
to any other admin blueprint endpoint.
95
96
CHAPTER
SIXTEEN
FLASK EXTENSIONS
Flask extensions extend the functionality of Flask in various different ways. For in-
stance they add support for databases and other common tasks.
16.1 Finding Extensions
Flask extensions are listed on the Flask Extension Registry and can be downloaded
with easy_install or pip. If you add a Flask extension as dependency to your
requirements.rst or setup.py le they are usually installed with a simple command
or when your application installs.
16.2 Using Extensions
Extensions typically have documentation that goes along that shows how to use it.
There are no general rules in how extensions are supposed to behave but they are
imported from common locations. If you have an extension called Flask-Foo or
Foo-Flask it will be always importable from flask.ext.foo:
from flask.ext import foo
16.3 Flask Before 0.8
If you are using Flask 0.7 or earlier the flask.ext package will not exist, instead you
have to import from flaskext.foo or flask_foo depending on how the extension is
distributed. If you want to develop an application that supports Flask 0.7 or earlier you
should still import from the flask.ext package. We provide you with a compatibility
module that provides this package for older versions of Flask. You can download it
from github: askext_compat.py
And here is how you can use it:
97
import flaskext_compat
flaskext_compat.activate()
from flask.ext import foo
Once the flaskext_compat module is activated the flask.ext will exist and you can
start importing from there.
98
CHAPTER
SEVENTEEN
WORKING WITH THE SHELL
New in version 0.3.
One of the reasons everybody loves Python is the interactive shell. It basically allows
you to execute Python commands in real time and immediately get results back. Flask
itself does not come with an interactive shell, because it does not require any specic
setup upfront, just import your application and start playing around.
There are however some handy helpers to make playing around in the shell a more
pleasant experience. The main issue with interactive console sessions is that youre
not triggering a request like a browser does which means that g, request and others
are not available. But the code you want to test might depend on them, so what can
you do?
This is where some helper functions come in handy. Keep in mind however that these
functions are not only there for interactive shell usage, but also for unittesting and
other situations that require a faked request context.
Generally its recommended that you read the The Request Context chapter of the doc-
umentation rst.
17.1 Creating a Request Context
The easiest way to create a proper request context from the shell is by using the
test_request_context method which creates us a RequestContext:
>>> ctx = app.test_request_context()
Normally you would use the with statement to make this request object active, but in
the shell its easier to use the push() and pop() methods by hand:
>>> ctx.push()
From that point onwards you can work with the request object until you call pop:
>>> ctx.pop()
99
17.2 Firing Before/After Request
By just creating a request context, you still dont have run the code that is normally
run before a request. This might result in your database being unavailable if you are
connecting to the database in a before-request callback or the current user not being
stored on the g object etc.
This however can easily be done yourself. Just call preprocess_request():
>>> ctx = app.test_request_context()
>>> ctx.push()
>>> app.preprocess_request()
Keep in mind that the preprocess_request() function might return a response object,
in that case just ignore it.
To shutdown a request, you need to trick a bit before the after request functions (trig-
gered by process_response()) operate on a response object:
>>> app.process_response(app.response_class())
<Response 0 bytes [200 OK]>
>>> ctx.pop()
The functions registered as teardown_request() are automatically called when the
context is popped. So this is the perfect place to automatically tear down resources
that were needed by the request context (such as database connections).
17.3 Further Improving the Shell Experience
If you like the idea of experimenting in a shell, create yourself a module with stuff you
want to star import into your interactive session. There you could also dene some
more helper methods for common things such as initializing the database, dropping
tables etc.
Just put them into a module (like shelltools and import from there):
>>> from shelltools import *
100
CHAPTER
EIGHTEEN
PATTERNS FOR FLASK
Certain things are common enough that the chances are high you will nd them in
most web applications. For example quite a lot of applications are using relational
databases and user authentication. In that case, chances are they will open a database
connection at the beginning of the request and get the information of the currently
logged in user. At the end of the request, the database connection is closed again.
There are more user contributed snippets and patterns in the Flask Snippet Archives.
18.1 Larger Applications
For larger applications its a good idea to use a package instead of a module. That is
quite simple. Imagine a small application looks like this:
/yourapplication
/yourapplication.py
/static
/style.css
/templates
layout.html
index.html
login.html
...
18.1.1 Simple Packages
To convert that into a larger one, just create a newfolder yourapplication inside the exist-
ing one and move everything below it. Then rename yourapplication.py to __init__.py.
(Make sure to delete all .pyc les rst, otherwise things would most likely break)
You should then end up with something like that:
/yourapplication
/yourapplication
/__init__.py
/static
101
/style.css
/templates
layout.html
index.html
login.html
...
But how do you run your application now? The naive python
yourapplication/__init__.py will not work. Lets just say that Python does
not want modules in packages to be the startup le. But that is not a big problem,
just add a new le called runserver.py next to the inner yourapplication folder with the
following contents:
from yourapplication import app
app.run(debug=True)
What did we gain fromthis? Nowwe can restructure the application a bit into multiple
modules. The only thing you have to remember is the following quick checklist:
1. the Flask application object creation has to be in the __init__.py le. That way
each module can import it safely and the __name__ variable will resolve to the
correct package.
2. all the view functions (the ones with a route() decorator on top) have to be
imported in the __init__.py le. Not the object itself, but the module it is in.
Import the view module after the application object is created.
Heres an example __init__.py:
from flask import Flask
app = Flask(__name__)
import yourapplication.views
And this is what views.py would look like:
from yourapplication import app
@app.route(/)
def index():
return Hello World!
You should then end up with something like that:
/yourapplication
/runserver.py
/yourapplication
/__init__.py
/views.py
/static
/style.css
/templates
layout.html
102
index.html
login.html
...
Circular Imports
Every Python programmer hates them, and yet we just added some: circular imports
(Thats when two modules depend on each other. In this case views.py depends on
__init__.py). Be advised that this is a bad idea in general but here it is actually ne.
The reason for this is that we are not actually using the views in __init__.py and just
ensuring the module is imported and we are doing that at the bottom of the le.
There are still some problems with that approach but if you want to use decorators
there is no way around that. Check out the Becoming Big section for some inspiration
how to deal with that.
18.1.2 Working with Blueprints
If you have larger applications its recommended to divide them into smaller groups
where each group is implemented with the help of a blueprint. For a gentle intro-
duction into this topic refer to the Modular Applications with Blueprints chapter of the
documentation.
18.2 Application Factories
If you are already using packages and blueprints for your application (Modular Appli-
cations with Blueprints) there are a couple of really nice ways to further improve the
experience. A common pattern is creating the application object when the blueprint
is imported. But if you move the creation of this object, into a function, you can then
create multiple instances of this and later.
So why would you want to do this?
1. Testing. You can have instances of the application with different settings to test
every case.
2. Multiple instances. Imagine you want to run different versions of the same ap-
plication. Of course you could have multiple instances with different congs set
up in your webserver, but if you use factories, you can have multiple instances
of the same application running in the same application process which can be
handy.
So how would you then actually implement that?
18.2.1 Basic Factories
The idea is to set up the application in a function. Like this:
103
def create_app(config_filename):
app = Flask(__name__)
app.config.from_pyfile(config_filename)
from yourapplication.model import db
db.init_app(app)
from yourapplication.views.admin import admin
from yourapplication.views.frontend import frontend
app.register_blueprint(admin)
app.register_blueprint(frontend)
return app
The downside is that you cannot use the application object in the blueprints at import
time. You can however use it from within a request. How do you get access to the
application with the cong? Use current_app:
from flask import current_app, Blueprint, render_template
admin = Blueprint(admin, __name__, url_prefix=/admin)
@admin.route(/)
def index():
return render_template(current_app.config[INDEX_TEMPLATE])
Here we look up the name of a template in the cong.
18.2.2 Factories & Extensions
Its preferable to create your extensions and app factories so that the extension object
does not initially get bound to the application.
Using Flask-SQLAlchemy, as an example, you should not do something along those
lines:
def create_app(config_filename):
app = Flask(__name__)
app.config.from_pyfile(config_filename)
db = SQLAlchemy(app)
But, rather, in model.py (or equivalent):
db = SQLAlchemy()
and in your application.py (or equivalent):
def create_app(config_filename):
app = Flask(__name__)
app.config.from_pyfile(config_filename)
104
from yourapplication.model import db
db.init_app(app)
Using this design pattern, no application-specic state is stored on the extension ob-
ject, so one extension object can be used for multiple apps. For more information about
the design of extensions refer to Flask Extension Development.
18.2.3 Using Applications
So to use such an application you then have to create the application rst. Here an
example run.py le that runs such an application:
from yourapplication import create_app
app = create_app(/path/to/config.cfg)
app.run()
18.2.4 Factory Improvements
The factory function from above is not very clever so far, you can improve it. The
following changes are straightforward and possible:
1. make it possible to pass in conguration values for unittests so that you dont
have to create cong les on the lesystem
2. call a function from a blueprint when the application is setting up so that you
have a place to modify attributes of the application (like hooking in before /
after request handlers etc.)
3. Add in WSGI middlewares when the application is creating if necessary.
18.3 Application Dispatching
Application dispatching is the process of combining multiple Flask applications on
the WSGI level. You can not only combine Flask applications into something larger
but any WSGI application. This would even allow you to run a Django and a Flask
application in the same interpreter side by side if you want. The usefulness of this
depends on how the applications work internally.
The fundamental difference from the module approach is that in this case you are run-
ning the same or different Flask applications that are entirely isolated from each other.
They run different congurations and are dispatched on the WSGI level.
18.3.1 Working with this Document
Each of the techniques and examples below results in an application object that
can be run with any WSGI server. For production, see Deployment Options. For
105
development, Werkzeug provides a builtin server for development available at
werkzeug.serving.run_simple():
from werkzeug.serving import run_simple
run_simple(localhost, 5000, application, use_reloader=True)
Note that run_simple is not intended for use in production. Use a full-blown WSGI
server.
In order to use the interactive debuggger, debugging must be enabled both on the
application and the simple server, here is the hello world example with debugging
and run_simple:
from flask import Flask
from werkzeug.serving import run_simple
app = Flask(__name__)
app.debug = True
@app.route(/)
def hello_world():
return Hello World!
if __name__ == __main__:
run_simple(localhost, 5000, app,
use_reloader=True, use_debugger=True, use_evalex=True)
18.3.2 Combining Applications
If you have entirely separated applications and you want them to work next to
each other in the same Python interpreter process you can take advantage of the
werkzeug.wsgi.DispatcherMiddleware. The idea here is that each Flask application
is a valid WSGI application and they are combined by the dispatcher middleware into
a larger one that dispatched based on prex.
For example you could have your main application run on / and your backend inter-
face on /backend:
from werkzeug.wsgi import DispatcherMiddleware
from frontend_app import application as frontend
from backend_app import application as backend
application = DispatcherMiddleware(frontend, {
/backend: backend
})
106
18.3.3 Dispatch by Subdomain
Sometimes you might want to use multiple instances of the same application with
different congurations. Assuming the application is created inside a function and
you can call that function to instantiate it, that is really easy to implement. In order to
develop your application to support creating new instances in functions have a look
at the Application Factories pattern.
A very common example would be creating applications per subdomain. For instance
you congure your webserver to dispatch all requests for all subdomains to your
application and you then use the subdomain information to create user-specic in-
stances. Once you have your server set up to listen on all subdomains you can use a
very simple WSGI application to do the dynamic application creation.
The perfect level for abstraction in that regard is the WSGI layer. You write your own
WSGI application that looks at the request that comes and delegates it to your Flask
application. If that application does not exist yet, it is dynamically created and remem-
bered:
from threading import Lock
class SubdomainDispatcher(object):
def __init__(self, domain, create_app):
self.domain = domain
self.create_app = create_app
self.lock = Lock()
self.instances = {}
def get_application(self, host):
host = host.split(:)[0]
assert host.endswith(self.domain), Configuration error
subdomain = host[:-len(self.domain)].rstrip(.)
with self.lock:
app = self.instances.get(subdomain)
if app is None:
app = self.create_app(subdomain)
self.instances[subdomain] = app
return app
def __call__(self, environ, start_response):
app = self.get_application(environ[HTTP_HOST])
return app(environ, start_response)
This dispatcher can then be used like this:
from myapplication import create_app, get_user_for_subdomain
from werkzeug.exceptions import NotFound
def make_app(subdomain):
user = get_user_for_subdomain(subdomain)
if user is None:
107
# if there is no user for that subdomain we still have
# to return a WSGI application that handles that request.
# We can then just return the NotFound() exception as
# application which will render a default 404 page.
# You might also redirect the user to the main page then
return NotFound()
# otherwise create the application for the specific user
return create_app(user)
application = SubdomainDispatcher(example.com, make_app)
18.3.4 Dispatch by Path
Dispatching by a path on the URL is very similar. Instead of looking at the Host header
to gure out the subdomain one simply looks at the request path up to the rst slash:
from threading import Lock
from werkzeug.wsgi import pop_path_info, peek_path_info
class PathDispatcher(object):
def __init__(self, default_app, create_app):
self.default_app = default_app
self.create_app = create_app
self.lock = Lock()
self.instances = {}
def get_application(self, prefix):
with self.lock:
app = self.instances.get(prefix)
if app is None:
app = self.create_app(prefix)
if app is not None:
self.instances[prefix] = app
return app
def __call__(self, environ, start_response):
app = self.get_application(peek_path_info(environ))
if app is not None:
pop_path_info(environ)
else:
app = self.default_app
return app(environ, start_response)
The big difference between this and the subdomain one is that this one falls back to
another application if the creator function returns None:
108
from myapplication import create_app, default_app, get_user_for_prefix
def make_app(prefix):
user = get_user_for_prefix(prefix)
if user is not None:
return create_app(user)
application = PathDispatcher(default_app, make_app)
18.4 Implementing API Exceptions
Its very common to implement RESTful APIs on top of Flask. One of the rst thing
that developers run into is the realization that the builtin exceptions are not expressive
enough for APIs and that the content type of text/html they are emitting is not very
useful for API consumers.
The better solution than using abort to signal errors for invalid API usage is to im-
plement your own exception type and install an error handler for it that produces the
errors in the format the user is expecting.
18.4.1 Simple Exception Class
The basic idea is to introduce a new exception that can take a proper human readable
message, a status code for the error and some optional payload to give more context
for the error.
This is a simple example:
from flask import jsonify
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv[message] = self.message
return rv
A view can now raise that exception with an error message. Additionally some extra
payload can be provided as a dictionary through the payload parameter.
109
18.4.2 Registering an Error Handler
At that point views can raise that error, but it would immediately result in an internal
server error. The reason for this is that there is no handler registered for this error
class. That however is easy to add:
@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
18.4.3 Usage in Views
Here is how a view can use that functionality:
@app.route(/foo)
def get_foo():
raise InvalidUsage(This view is gone, status_code=410)
18.5 Using URL Processors
New in version 0.7.
Flask 0.7 introduces the concept of URL processors. The idea is that you might have
a bunch of resources with common parts in the URL that you dont always explicitly
want to provide. For instance you might have a bunch of URLs that have the language
code in it but you dont want to have to handle it in every single function yourself.
URL processors are especially helpful when combined with blueprints. We will handle
both application specic URL processors here as well as blueprint specics.
18.5.1 Internationalized Application URLs
Consider an application like this:
from flask import Flask, g
app = Flask(__name__)
@app.route(/<lang_code>/)
def index(lang_code):
g.lang_code = lang_code
...
@app.route(/<lang_code>/about)
def about(lang_code):
110
g.lang_code = lang_code
...
This is an awful lot of repetition as you have to handle the language code setting on the
g object yourself in every single function. Sure, a decorator could be used to simplify
this, but if you want to generate URLs from one function to another you would have
to still provide the language code explicitly which can be annoying.
For the latter, this is where url_defaults() functions come in. They can automatically
inject values into a call for url_for() automatically. The code below checks if the
language code is not yet in the dictionary of URL values and if the endpoint wants a
value named lang_code:
@app.url_defaults
def add_language_code(endpoint, values):
if lang_code in values or not g.lang_code:
return
if app.url_map.is_endpoint_expecting(endpoint, lang_code):
values[lang_code] = g.lang_code
The method is_endpoint_expecting() of the URL map can be used to gure out if it
would make sense to provide a language code for the given endpoint.
The reverse of that function are url_value_preprocessor()s. They are executed right
after the request was matched and can execute code based on the URL values. The
idea is that they pull information out of the values dictionary and put it somewhere
else:
@app.url_value_preprocessor
def pull_lang_code(endpoint, values):
g.lang_code = values.pop(lang_code, None)
That way you no longer have to do the lang_code assignment to g in every function.
You can further improve that by writing your own decorator that prexes URLs with
the language code, but the more beautiful solution is using a blueprint. Once the
lang_code is popped from the values dictionary and it will no longer be forwarded
to the view function reducing the code to this:
from flask import Flask, g
app = Flask(__name__)
@app.url_defaults
def add_language_code(endpoint, values):
if lang_code in values or not g.lang_code:
return
if app.url_map.is_endpoint_expecting(endpoint, lang_code):
values[lang_code] = g.lang_code
@app.url_value_preprocessor
def pull_lang_code(endpoint, values):
g.lang_code = values.pop(lang_code, None)
111
@app.route(/<lang_code>/)
def index():
...
@app.route(/<lang_code>/about)
def about():
...
18.5.2 Internationalized Blueprint URLs
Because blueprints can automatically prex all URLs with a common string its easy
to automatically do that for every function. Furthermore blueprints can have per-
blueprint URL processors which removes a whole lot of logic fromthe url_defaults()
function because it no longer has to check if the URL is really interested in a
lang_code parameter:
from flask import Blueprint, g
bp = Blueprint(frontend, __name__, url_prefix=/<lang_code>)
@bp.url_defaults
def add_language_code(endpoint, values):
values.setdefault(lang_code, g.lang_code)
@bp.url_value_preprocessor
def pull_lang_code(endpoint, values):
g.lang_code = values.pop(lang_code)
@bp.route(/)
def index():
...
@bp.route(/about)
def about():
...
18.6 Deploying with Distribute
distribute, formerly setuptools, is an extension library that is commonly used to (like
the name says) distribute Python libraries and extensions. It extends distutils, a basic
module installation system shipped with Python to also support various more com-
plex constructs that make larger applications easier to distribute:
support for dependencies: a library or application can declare a list of other
libraries it depends on which will be installed automatically for you.
112
package registry: setuptools registers your package with your Python installa-
tion. This makes it possible to query information provided by one package from
another package. The best known feature of this system is the entry point sup-
port which allows one package to declare an entry point another package can
hook into to extend the other package.
installation manager: easy_install, which comes with distribute can install other
libraries for you. You can also use pip which sooner or later will replace
easy_install which does more than just installing packages for you.
Flask itself, and all the libraries you can nd on the cheeseshop are distributed with
either distribute, the older setuptools or distutils.
In this case we assume your application is called yourapplication.py and you are not
using a module, but a package. Distributing resources with standard modules is not
supported by distribute so we will not bother with it. If you have not yet converted
your application into a package, head over to the Larger Applications pattern to see how
this can be done.
A working deployment with distribute is the rst step into more complex and more
automated deployment scenarios. If you want to fully automate the process, also read
the Deploying with Fabric chapter.
18.6.1 Basic Setup Script
Because you have Flask running, you either have setuptools or distribute available on
your system anyways. If you do not, fear not, there is a script to install it for you:
distribute_setup.py. Just download and run with your Python interpreter.
Standard disclaimer applies: you better use a virtualenv.
Your setup code always goes into a le named setup.py next to your application. The
name of the le is only convention, but because everybody will look for a le with that
name, you better not change it.
Yes, even if you are using distribute, you are importing froma package called setuptools.
distribute is fully backwards compatible with setuptools, so it also uses the same import
name.
A basic setup.py le for a Flask application looks like this:
from setuptools import setup
setup(
name=Your Application,
version=1.0,
long_description=__doc__,
packages=[yourapplication],
include_package_data=True,
zip_safe=False,
install_requires=[Flask]
)
113
Please keep in mind that you have to list subpackages explicitly. If you want distribute
to lookup the packages for you automatically, you can use the nd_packages function:
from setuptools import setup, find_packages
setup(
...
packages=find_packages()
)
Most parameters to the setup function should be self explanatory, include_package_data
and zip_safe might not be. include_package_data tells distribute to look for a MANI-
FEST.in le and install all the entries that match as package data. We will use this to
distribute the static les and templates along with the Python module (see Distribut-
ing Resources). The zip_safe ag can be used to force or prevent zip Archive creation.
In general you probably dont want your packages to be installed as zip les because
some tools do not support them and they make debugging a lot harder.
18.6.2 Distributing Resources
If you try to install the package you just created, you will notice that folders like static
or templates are not installed for you. The reason for this is that distribute does not
know which les to add for you. What you should do, is to create a MANIFEST.in le
next to your setup.py le. This le lists all the les that should be added to your tarball:
recursive-include yourapplication/templates *
recursive-include yourapplication/static *
Dont forget that even if you enlist them in your MANIFEST.in le, they wont be
installed for you unless you set the include_package_data parameter of the setup function
to True!
18.6.3 Declaring Dependencies
Dependencies are declared in the install_requires parameter as list. Each itemin that list
is the name of a package that should be pulled from PyPI on installation. By default
it will always use the most recent version, but you can also provide minimum and
maximum version requirements. Here some examples:
install_requires=[
Flask>=0.2,
SQLAlchemy>=0.6,
BrokenPackage>=0.7,<=1.0
]
I mentioned earlier that dependencies are pulled from PyPI. What if you want to de-
pend on a package that cannot be found on PyPI and wont be because it is an internal
114
package you dont want to share with anyone? Just still do as if there was a PyPI en-
try for it and provide a list of alternative locations where distribute should look for
tarballs:
dependency_links=[http://example.com/yourfiles]
Make sure that page has a directory listing and the links on the page are pointing to
the actual tarballs with their correct lenames as this is how distribute will nd the
les. If you have an internal company server that contains the packages, provide the
URL to that server there.
18.6.4 Installing / Developing
To install your application (ideally into a virtualenv) just run the setup.py script with
the install parameter. It will install your application into the virtualenvs site-packages
folder and also download and install all dependencies:
$ python setup.py install
If you are developing on the package and also want the requirements to be installed,
you can use the develop command instead:
$ python setup.py develop
This has the advantage of just installing a link to the site-packages folder instead of
copying the data over. You can then continue to work on the code without having to
run install again after each change.
18.7 Deploying with Fabric
Fabric is a tool for Python similar to Makeles but with the ability to execute com-
mands on a remote server. In combination with a properly set up Python package
(Larger Applications) and a good concept for congurations (Conguration Handling) it
is very easy to deploy Flask applications to external servers.
Before we get started, here a quick checklist of things we have to ensure upfront:
Fabric 1.0 has to be installed locally. This tutorial assumes the latest version of
Fabric.
The application already has to be a package and requires a working setup.py le
(Deploying with Distribute).
In the following example we are using mod_wsgi for the remote servers. You
can of course use your own favourite server there, but for this example we chose
Apache + mod_wsgi because its very easy to setup and has a simple way to reload
applications without root access.
115
18.7.1 Creating the rst Fable
A fable is what controls what Fabric executes. It is named fable.py and executed by
the fab command. All the functions dened in that le will show up as fab subcom-
mands. They are executed on one or more hosts. These hosts can be dened either in
the fable or on the command line. In this case we will add them to the fable.
This is a basic rst example that has the ability to upload the current sourcecode to the
server and install it into a pre-existing virtual environment:
from fabric.api import *
# the user to use for the remote commands
env.user = appuser
# the servers where the commands are executed
env.hosts = [server1.example.com, server2.example.com]
def pack():
# create a new source distribution as tarball
local(python setup.py sdist --formats=gztar, capture=False)
def deploy():
# figure out the release name and version
dist = local(python setup.py --fullname, capture=True).strip()
# upload the source tarball to the temporary folder on the server
put(dist/%s.tar.gz % dist, /tmp/yourapplication.tar.gz)
# create a place where we can unzip the tarball, then enter
# that directory and unzip it
run(mkdir /tmp/yourapplication)
with cd(/tmp/yourapplication):
run(tar xzf /tmp/yourapplication.tar.gz)
# now setup the package with our virtual environments
# python interpreter
run(/var/www/yourapplication/env/bin/python setup.py install)
# now that all is set up, delete the folder again
run(rm -rf /tmp/yourapplication /tmp/yourapplication.tar.gz)
# and finally touch the .wsgi file so that mod_wsgi triggers
# a reload of the application
run(touch /var/www/yourapplication.wsgi)
The example above is well documented and should be straightforward. Here a recap
of the most common commands fabric provides:
run - executes a command on a remote server
local - executes a command on the local machine
put - uploads a le to the remote server
cd - changes the directory on the serverside. This has to be used in combination
with the with statement.
116
18.7.2 Running Fables
Nowhowdo you execute that fable? You use the fab command. To deploy the current
version of the code on the remote server you would use this command:
$ fab pack deploy
However this requires that our server already has the /var/www/yourapplication
folder created and /var/www/yourapplication/env to be a virtual environment. Fur-
thermore are we not creating the conguration or .wsgi le on the server. So how do
we bootstrap a new server into our infrastructure?
This now depends on the number of servers we want to set up. If we just have one
application server (which the majority of applications will have), creating a command
in the fable for this is overkill. But obviously you can do that. In that case you
would probably call it setup or bootstrap and then pass the servername explicitly on the
command line:
$ fab -H newserver.example.com bootstrap
To setup a new server you would roughly do these steps:
1. Create the directory structure in /var/www:
$ mkdir /var/www/yourapplication
$ cd /var/www/yourapplication
$ virtualenv --distribute env
2. Upload a new application.wsgi le to the server and the conguration le for the
application (eg: application.cfg)
3. Create a new Apache cong for yourapplication and activate it. Make sure to
activate watching for changes of the .wsgi le so that we can automatically reload
the application by touching it. (See mod_wsgi (Apache) for more information)
So now the question is, where do the application.wsgi and application.cfg les come
from?
18.7.3 The WSGI File
The WSGI le has to import the application and also to set an environment variable so
that the application knows where to look for the cong. This is a short example that
does exactly that:
import os
os.environ[YOURAPPLICATION_CONFIG] = /var/www/yourapplication/application.cfg
from yourapplication import app
The application itself then has to initialize itself like this to look for the cong at that
environment variable:
117
app = Flask(__name__)
app.config.from_object(yourapplication.default_config)
app.config.from_envvar(YOURAPPLICATION_CONFIG)
This approach is explained in detail in the Conguration Handling section of the docu-
mentation.
18.7.4 The Conguration File
Now as mentioned above, the application will nd the correct conguration le by
looking up the YOURAPPLICATION_CONFIG environment variable. So we have to
put the conguration in a place where the application will able to nd it. Congura-
tion les have the unfriendly quality of being different on all computers, so you do not
version them usually.
A popular approach is to store conguration les for different servers in a sep-
arate version control repository and check them out on all servers. Then sym-
link the le that is active for the server into the location where its expected (eg:
/var/www/yourapplication).
Either way, in our case here we only expect one or two servers and we can upload
them ahead of time by hand.
18.7.5 First Deployment
Now we can do our rst deployment. We have set up the servers so that they have
their virtual environments and activated apache congs. Now we can pack up the
application and deploy it:
$ fab pack deploy
Fabric will now connect to all servers and run the commands as written down in the
fable. First it will execute pack so that we have our tarball ready and then it will
execute deploy and upload the source code to all servers and install it there. Thanks
to the setup.py le we will automatically pull in the required libraries into our virtual
environment.
18.7.6 Next Steps
From that point onwards there is so much that can be done to make deployment actu-
ally fun:
Create a bootstrap command that initializes new servers. It could initialize a new
virtual environment, setup apache appropriately etc.
Put conguration les into a separate version control repository and symlink the
active congs into place.
118
You could also put your application code into a repository and check out the
latest version on the server and then install. That way you can also easily go
back to older versions.
hook in testing functionality so that you can deploy to an external server and run
the testsuite.
Working with Fabric is fun and you will notice that its quite magical to type fab
deploy and see your application being deployed automatically to one or more remote
servers.
18.8 Using SQLite 3 with Flask
In Flask you can implement the opening of database connections on demand and clos-
ing it when the context dies (usually at the end of the request) easily.
Here is a simple example of how you can use SQLite 3 with Flask:
import sqlite3
from flask import g
DATABASE = /path/to/database.db
def get_db():
db = getattr(g, _database, None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)
return db
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, _database, None)
if db is not None:
db.close()
All the application needs to do in order to now use the database is having an active
application context (which is always true if there is an request in ight) or to create an
application context itself. At that point the get_db function can be used to get the cur-
rent database connection. Whenever the context is destroyed the database connection
will be terminated.
Note: if you use Flask 0.9 or older you need to use flask._app_ctx_stack.top instead
of g as the flask.g object was bound to the request and not application context.
Example:
@app.route(/)
def index():
cur = get_db().cursor()
...
119
Note: Please keep in mind that the teardown request and appcontext functions are al-
ways executed, even if a before-request handler failed or was never executed. Because
of this we have to make sure here that the database is there before we close it.
18.8.1 Connect on Demand
The upside of this approach (connecting on rst use) is that this will only opening the
connection if truly necessary. If you want to use this code outside a request context
you can use it in a Python shell by opening the application context by hand:
with app.app_context():
# now you can use get_db()
18.8.2 Easy Querying
Now in each request handling function you can access g.db to get the current open
database connection. To simplify working with SQLite, a row factory function is use-
ful. It is executed for every result returned from the database to convert the result.
For instance in order to get dictionaries instead of tuples this could be inserted into
get_db:
def make_dicts(cursor, row):
return dict((cursor.description[idx][0], value)
for idx, value in enumerate(row))
db.row_factory = make_dicts
Or even simpler:
db.row_factory = sqlite3.Row
Additionally it is a good idea to provide a query function that combines getting the
cursor, executing and fetching the results:
def query_db(query, args=(), one=False):
cur = get_db().execute(query, args)
rv = cur.fetchall()
cur.close()
return (rv[0] if rv else None) if one else rv
This handy little function in combination with a row factory makes working with the
database much more pleasant than it is by just using the raw cursor and connection
objects.
Here is how you can use it:
for user in query_db(select * from users):
print user[username], has the id, user[user_id]
120
Or if you just want a single result:
user = query_db(select * from users where username = ?,
[the_username], one=True)
if user is None:
print No such user
else:
print the_username, has the id, user[user_id]
To pass variable parts to the SQL statement, use a question mark in the statement and
pass in the arguments as a list. Never directly add them to the SQL statement with
string formatting because this makes it possible to attack the application using SQL
Injections.
18.8.3 Initial Schemas
Relational databases need schemas, so applications often ship a schema.sql le that
creates the database. Its a good idea to provide a function that creates the database
based on that schema. This function can do that for you:
def init_db():
with app.app_context():
db = get_db()
with app.open_resource(schema.sql, mode=r) as f:
db.cursor().executescript(f.read())
db.commit()
You can then create such a database from the python shell:
>>> from yourapplication import init_db
>>> init_db()
18.9 SQLAlchemy in Flask
Many people prefer SQLAlchemy for database access. In this case its encouraged to
use a package instead of a module for your ask application and drop the models into
a separate module (Larger Applications). While that is not necessary, it makes a lot of
sense.
There are four very common ways to use SQLAlchemy. I will outline each of them
here:
18.9.1 Flask-SQLAlchemy Extension
Because SQLAlchemy is a common database abstraction layer and object relational
mapper that requires a little bit of conguration effort, there is a Flask extension that
handles that for you. This is recommended if you want to get started quickly.
121
You can download Flask-SQLAlchemy from PyPI.
18.9.2 Declarative
The declarative extension in SQLAlchemy is the most recent method of using
SQLAlchemy. It allows you to dene tables and models in one go, similar to how
Django works. In addition to the following text I recommend the ofcial documenta-
tion on the declarative extension.
Here the example database.py module for your application:
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine(sqlite:////tmp/test.db, convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
def init_db():
# import all modules here that might define models so that
# they will be registered properly on the metadata. Otherwise
# you will have to import them first before calling init_db()
import yourapplication.models
Base.metadata.create_all(bind=engine)
To dene your models, just subclass the Base class that was created by the code above.
If you are wondering why we dont have to care about threads here (like we did in the
SQLite3 example above with the g object): thats because SQLAlchemy does that for
us already with the scoped_session.
To use SQLAlchemy in a declarative way with your application, you just have to put
the following code into your application module. Flask will automatically remove
database sessions at the end of the request or when the application shuts down:
from yourapplication.database import db_session
@app.teardown_appcontext
def shutdown_session(exception=None):
db_session.remove()
Here is an example model (put this into models.py, e.g.):
from sqlalchemy import Column, Integer, String
from yourapplication.database import Base
class User(Base):
__tablename__ = users
122
id = Column(Integer, primary_key=True)
name = Column(String(50), unique=True)
email = Column(String(120), unique=True)
def __init__(self, name=None, email=None):
self.name = name
self.email = email
def __repr__(self):
return <User %r> % (self.name)
To create the database you can use the init_db function:
>>> from yourapplication.database import init_db
>>> init_db()
You can insert entries into the database like this:
>>> from yourapplication.database import db_session
>>> from yourapplication.models import User
>>> u = User(admin, admin@localhost)
>>> db_session.add(u)
>>> db_session.commit()
Querying is simple as well:
>>> User.query.all()
[<User uadmin>]
>>> User.query.filter(User.name == admin).first()
<User uadmin>
18.9.3 Manual Object Relational Mapping
Manual object relational mapping has a few upsides and a few downsides versus the
declarative approach from above. The main difference is that you dene tables and
classes separately and map them together. Its more exible but a little more to type.
In general it works like the declarative approach, so make sure to also split up your
application into multiple modules in a package.
Here is an example database.py module for your application:
from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import scoped_session, sessionmaker
engine = create_engine(sqlite:////tmp/test.db, convert_unicode=True)
metadata = MetaData()
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
def init_db():
metadata.create_all(bind=engine)
123
As for the declarative approach you need to close the session after each request or
application context shutdown. Put this into your application module:
from yourapplication.database import db_session
@app.teardown_appcontext
def shutdown_session(exception=None):
db_session.remove()
Here is an example table and model (put this into models.py):
from sqlalchemy import Table, Column, Integer, String
from sqlalchemy.orm import mapper
from yourapplication.database import metadata, db_session
class User(object):
query = db_session.query_property()
def __init__(self, name=None, email=None):
self.name = name
self.email = email
def __repr__(self):
return <User %r> % (self.name)
users = Table(users, metadata,
Column(id, Integer, primary_key=True),
Column(name, String(50), unique=True),
Column(email, String(120), unique=True)
)
mapper(User, users)
Querying and inserting works exactly the same as in the example above.
18.9.4 SQL Abstraction Layer
If you just want to use the database system (and SQL) abstraction layer you basically
only need the engine:
from sqlalchemy import create_engine, MetaData
engine = create_engine(sqlite:////tmp/test.db, convert_unicode=True)
metadata = MetaData(bind=engine)
Then you can either declare the tables in your code like in the examples above, or
automatically load them:
users = Table(users, metadata, autoload=True)
To insert data you can use the insert method. We have to get a connection rst so that
we can use a transaction:
124
>>> con = engine.connect()
>>> con.execute(users.insert(), name=admin, email=admin@localhost)
SQLAlchemy will automatically commit for us.
To query your database, you use the engine directly or use a connection:
>>> users.select(users.c.id == 1).execute().first()
(1, uadmin, uadmin@localhost)
These results are also dict-like tuples:
>>> r = users.select(users.c.id == 1).execute().first()
>>> r[name]
uadmin
You can also pass strings of SQL statements to the execute() method:
>>> engine.execute(select * from users where id = :1, [1]).first()
(1, uadmin, uadmin@localhost)
For more information about SQLAlchemy, head over to the website.
18.10 Uploading Files
Ah yes, the good old problem of le uploads. The basic idea of le uploads is actually
quite simple. It basically works like this:
1. A <form> tag is marked with enctype=multipart/form-data and an <input
type=file> is placed in that form.
2. The application accesses the le from the files dictionary on the request object.
3. use the save() method of the le to save the le permanently somewhere on the
lesystem.
18.10.1 A Gentle Introduction
Lets start with a very basic application that uploads a le to a specic upload folder
and displays a le to the user. Lets look at the bootstrapping code for our application:
import os
from flask import Flask, request, redirect, url_for
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = /path/to/the/uploads
ALLOWED_EXTENSIONS = set([txt, pdf, png, jpg, jpeg, gif])
app = Flask(__name__)
app.config[UPLOAD_FOLDER] = UPLOAD_FOLDER
125
So rst we need a couple of imports. Most should be straightforward, the
werkzeug.secure_filename() is explained a little bit later. The UPLOAD_FOLDER
is where we will store the uploaded les and the ALLOWED_EXTENSIONS is the set
of allowed le extensions. Then we add a URL rule by hand to the application. Now
usually were not doing that, so why here? The reasons is that we want the webserver
(or our development server) to serve these les for us and so we only need a rule to
generate the URL to these les.
Why do we limit the extensions that are allowed? You probably dont want your users
to be able to upload everything there if the server is directly sending out the data to the
client. That way you can make sure that users are not able to upload HTML les that
would cause XSS problems (see Cross-Site Scripting (XSS)). Also make sure to disallow
.php les if the server executes them, but who has PHP installed on his server, right? :)
Next the functions that check if an extension is valid and that uploads the le and
redirects the user to the URL for the uploaded le:
def allowed_file(filename):
return . in filename and \
filename.rsplit(., 1)[1] in ALLOWED_EXTENSIONS
@app.route(/, methods=[GET, POST])
def upload_file():
if request.method == POST:
file = request.files[file]
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config[UPLOAD_FOLDER], filename))
return redirect(url_for(uploaded_file,
filename=filename))
return
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
So what does that secure_filename() function actually do? Now the problem is that
there is that principle called never trust user input. This is also true for the lename
of an uploaded le. All submitted form data can be forged, and lenames can be dan-
gerous. For the moment just remember: always use that function to secure a lename
before storing it directly on the lesystem.
Information for the Pros
So youre interested in what that secure_filename() function does and what the prob-
lem is if youre not using it? So just imagine someone would send the following infor-
mation as lename to your application:
126
filename = "../../../../home/username/.bashrc"
Assuming the number of ../ is correct and you would join this with the UP-
LOAD_FOLDER the user might have the ability to modify a le on the servers lesys-
tem he or she should not modify. This does require some knowledge about how the
application looks like, but trust me, hackers are patient :)
Now lets look how that function works:
>>> secure_filename(../../../../home/username/.bashrc)
home_username_.bashrc
Now one last thing is missing: the serving of the uploaded les. As of Flask 0.5 we
can use a function that does that for us:
from flask import send_from_directory
@app.route(/uploads/<filename>)
def uploaded_file(filename):
return send_from_directory(app.config[UPLOAD_FOLDER],
filename)
Alternatively you can register uploaded_le as build_only rule and use the
SharedDataMiddleware. This also works with older versions of Flask:
from werkzeug import SharedDataMiddleware
app.add_url_rule(/uploads/<filename>, uploaded_file,
build_only=True)
app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
/uploads: app.config[UPLOAD_FOLDER]
})
If you now run the application everything should work as expected.
18.10.2 Improving Uploads
New in version 0.6.
So how exactly does Flask handle uploads? Well it will store them in the webservers
memory if the les are reasonable small otherwise in a temporary location (as returned
by tempfile.gettempdir()). But how do you specify the maximum le size after
which an upload is aborted? By default Flask will happily accept le uploads to an un-
limited amount of memory, but you can limit that by setting the MAX_CONTENT_LENGTH
cong key:
from flask import Flask, Request
app = Flask(__name__)
app.config[MAX_CONTENT_LENGTH] = 16 * 1024 * 1024
127
The code above will limited the maximum allowed payload to 16 megabytes. If a
larger le is transmitted, Flask will raise an RequestEntityTooLarge exception.
This feature was added in Flask 0.6 but can be achieved in older versions as well by
subclassing the request object. For more information on that consult the Werkzeug
documentation on le handling.
18.10.3 Upload Progress Bars
A while ago many developers had the idea to read the incoming le in small chunks
and store the upload progress in the database to be able to poll the progress with
JavaScript from the client. Long story short: the client asks the server every 5 seconds
how much it has transmitted already. Do you realize the irony? The client is asking
for something it should already know.
Nowthere are better solutions to that work faster and more reliable. The web changed
a lot lately and you can use HTML5, Java, Silverlight or Flash to get a nicer uploading
experience on the client side. Look at the following libraries for some nice examples
how to do that:
Plupload - HTML5, Java, Flash
SWFUpload - Flash
JumpLoader - Java
18.10.4 An Easier Solution
Because the common pattern for le uploads exists almost unchanged in all applica-
tions dealing with uploads, there is a Flask extension called Flask-Uploads that imple-
ments a full edged upload mechanism with white and blacklisting of extensions and
more.
18.11 Caching
When your application runs slow, throw some caches in. Well, at least its the easiest
way to speed up things. What does a cache do? Say you have a function that takes
some time to complete but the results would still be good enough if they were 5 min-
utes old. So then the idea is that you actually put the result of that calculation into a
cache for some time.
Flask itself does not provide caching for you, but Werkzeug, one of the libraries it is
based on, has some very basic cache support. It supports multiple cache backends,
normally you want to use a memcached server.
128
18.11.1 Setting up a Cache
You create a cache object once and keep it around, similar to how Flask objects are
created. If you are using the development server you can create a SimpleCache object,
that one is a simple cache that keeps the item stored in the memory of the Python
interpreter:
from werkzeug.contrib.cache import SimpleCache
cache = SimpleCache()
If you want to use memcached, make sure to have one of the memcache modules
supported (you get them from PyPI) and a memcached server running somewhere.
This is how you connect to such an memcached server then:
from werkzeug.contrib.cache import MemcachedCache
cache = MemcachedCache([127.0.0.1:11211])
If you are using App Engine, you can connect to the App Engine memcache server
easily:
from werkzeug.contrib.cache import GAEMemcachedCache
cache = GAEMemcachedCache()
18.11.2 Using a Cache
Now how can one use such a cache? There are two very important operations: get()
and set(). This is how to use them:
To get an item from the cache call get() with a string as key name. If something is in
the cache, it is returned. Otherwise that function will return None:
rv = cache.get(my-item)
To add items to the cache, use the set() method instead. The rst argument is the
key and the second the value that should be set. Also a timeout can be provided after
which the cache will automatically remove item.
Here a full example how this looks like normally:
def get_my_item():
rv = cache.get(my-item)
if rv is None:
rv = calculate_value()
cache.set(my-item, rv, timeout=5 * 60)
return rv
129
18.12 View Decorators
Python has a really interesting feature called function decorators. This allow some
really neat things for web applications. Because each view in Flask is a function dec-
orators can be used to inject additional functionality to one or more functions. The
route() decorator is the one you probably used already. But there are use cases for
implementing your own decorator. For instance, imagine you have a view that should
only be used by people that are logged in to. If a user goes to the site and is not logged
in, they should be redirected to the login page. This is a good example of a use case
where a decorator is an excellent solution.
18.12.1 Login Required Decorator
So lets implement such a decorator. A decorator is a function that returns a function.
Pretty simple actually. The only thing you have to keep in mind when implementing
something like this is to update the __name__, __module__ and some other attributes
of a function. This is often forgotten, but you dont have to do that by hand, there is a
function for that that is used like a decorator (functools.wraps()).
This example assumes that the login page is called login and that the current user
is stored as g.user and None if there is no-one logged in:
from functools import wraps
from flask import g, request, redirect, url_for
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if g.user is None:
return redirect(url_for(login, next=request.url))
return f(*args, **kwargs)
return decorated_function
So how would you use that decorator now? Apply it as innermost decorator to a
view function. When applying further decorators, always remember that the route()
decorator is the outermost:
@app.route(/secret_page)
@login_required
def secret_page():
pass
18.12.2 Caching Decorator
Imagine you have a view function that does an expensive calculation and because
of that you would like to cache the generated results for a certain amount of time.
A decorator would be nice for that. Were assuming you have set up a cache like
mentioned in Caching.
130
Here an example cache function. It generates the cache key from a specic prex (ac-
tually a format string) and the current path of the request. Notice that we are using a
function that rst creates the decorator that then decorates the function. Sounds aw-
ful? Unfortunately it is a little bit more complex, but the code should still be straight-
forward to read.
The decorated function will then work as follows
1. get the unique cache key for the current request base on the current path.
2. get the value for that key from the cache. If the cache returned something we
will return that value.
3. otherwise the original function is called and the return value is stored in the
cache for the timeout provided (by default 5 minutes).
Here the code:
from functools import wraps
from flask import request
def cached(timeout=5 * 60, key=view/%s):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
cache_key = key % request.path
rv = cache.get(cache_key)
if rv is not None:
return rv
rv = f(*args, **kwargs)
cache.set(cache_key, rv, timeout=timeout)
return rv
return decorated_function
return decorator
Notice that this assumes an instantiated cache object is available, see Caching for more
information.
18.12.3 Templating Decorator
A common pattern invented by the TurboGears guys a while back is a templating
decorator. The idea of that decorator is that you return a dictionary with the values
passed to the template from the view function and the template is automatically ren-
dered. With that, the following three examples do exactly the same:
@app.route(/)
def index():
return render_template(index.html, value=42)
@app.route(/)
@templated(index.html)
def index():
131
return dict(value=42)
@app.route(/)
@templated()
def index():
return dict(value=42)
As you can see, if no template name is provided it will use the endpoint of the URL
map with dots converted to slashes + .html. Otherwise the provided template name
is used. When the decorated function returns, the dictionary returned is passed to the
template rendering function. If None is returned, an empty dictionary is assumed, if
something else than a dictionary is returned we return it fromthe function unchanged.
That way you can still use the redirect function or return simple strings.
Here the code for that decorator:
from functools import wraps
from flask import request
def templated(template=None):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
template_name = template
if template_name is None:
template_name = request.endpoint \
.replace(., /) + .html
ctx = f(*args, **kwargs)
if ctx is None:
ctx = {}
elif not isinstance(ctx, dict):
return ctx
return render_template(template_name, **ctx)
return decorated_function
return decorator
18.12.4 Endpoint Decorator
When you want to use the werkzeug routing system for more exibility you need to
map the endpoint as dened in the Rule to a view function. This is possible with this
decorator. For example:
from flask import Flask
from werkzeug.routing import Rule
app = Flask(__name__)
app.url_map.add(Rule(/, endpoint=index))
@app.endpoint(index)
132
def my_index():
return "Hello world"
18.13 Form Validation with WTForms
When you have to work with form data submitted by a browser view code quickly
becomes very hard to read. There are libraries out there designed to make this process
easier to manage. One of them is WTForms which we will handle here. If you nd
yourself in the situation of having many forms, you might want to give it a try.
When you are working with WTForms you have to dene your forms as classes rst.
I recommend breaking up the application into multiple modules (Larger Applications)
for that and adding a separate module for the forms.
Getting most of WTForms with an Extension
The Flask-WTF extension expands on this pattern and adds a fewhandful little helpers
that make working with forms and Flask more fun. You can get it from PyPI.
18.13.1 The Forms
This is an example form for a typical registration page:
from wtforms import Form, BooleanField, TextField, PasswordField, validators
class RegistrationForm(Form):
username = TextField(Username, [validators.Length(min=4, max=25)])
email = TextField(Email Address, [validators.Length(min=6, max=35)])
password = PasswordField(New Password, [
validators.Required(),
validators.EqualTo(confirm, message=Passwords must match)
])
confirm = PasswordField(Repeat Password)
accept_tos = BooleanField(I accept the TOS, [validators.Required()])
18.13.2 In the View
In the view function, the usage of this form looks like this:
@app.route(/register, methods=[GET, POST])
def register():
form = RegistrationForm(request.form)
if request.method == POST and form.validate():
user = User(form.username.data, form.email.data,
form.password.data)
db_session.add(user)
133
flash(Thanks for registering)
return redirect(url_for(login))
return render_template(register.html, form=form)
Notice that we are implying that the view is using SQLAlchemy here (SQLAlchemy in
Flask) but this is no requirement of course. Adapt the code as necessary.
Things to remember:
1. create the form from the request form value if the data is submitted via the HTTP
POST method and args if the data is submitted as GET.
2. to validate the data, call the validate() method which will return True if the data
validates, False otherwise.
3. to access individual values from the form, access form.<NAME>.data.
18.13.3 Forms in Templates
Now to the template side. When you pass the form to the templates you can easily
render them there. Look at the following example template to see how easy this is.
WTForms does half the form generation for us already. To make it even nicer, we can
write a macro that renders a eld with label and a list of errors if there are any.
Heres an example _formhelpers.html template with such a macro:
{% macro render_field(field) %}
<dt>{{ field.label }}
<dd>{{ field(**kwargs)|safe }}
{% if field.errors %}
<ul class=errors>
{% for error in field.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</dd>
{% endmacro %}
This macro accepts a couple of keyword arguments that are forwarded to WTForms
eld function that renders the eld for us. The keyword arguments will be in-
serted as HTML attributes. So for example you can call render_field(form.username,
class=username) to add a class to the input element. Note that WTForms returns
standard Python unicode strings, so we have to tell Jinja2 that this data is already
HTML escaped with the |safe lter.
Here the register.html template for the function we used above which takes advantage
of the _formhelpers.html template:
{% from "_formhelpers.html" import render_field %}
<form method=post action="/register">
<dl>
134
{{ render_field(form.username) }}
{{ render_field(form.email) }}
{{ render_field(form.password) }}
{{ render_field(form.confirm) }}
{{ render_field(form.accept_tos) }}
</dl>
<p><input type=submit value=Register>
</form>
For more information about WTForms, head over to the WTForms website.
18.14 Template Inheritance
The most powerful part of Jinja is template inheritance. Template inheritance allows
you to build a base skeleton template that contains all the common elements of your
site and denes blocks that child templates can override.
Sounds complicated but is very basic. Its easiest to understand it by starting with an
example.
18.14.1 Base Template
This template, which well call layout.html, denes a simple HTML skeleton docu-
ment that you might use for a simple two-column page. Its the job of child tem-
plates to ll the empty blocks with content:
<!doctype html>
<html>
<head>
{% block head %}
<link rel="stylesheet" href="{{ url_for(static, filename=style.css) }}">
<title>{% block title %}{% endblock %} - My Webpage</title>
{% endblock %}
</head>
<body>
<div id="content">{% block content %}{% endblock %}</div>
<div id="footer">
{% block footer %}
© Copyright 2010 by <a href="http://domain.invalid/">you</a>.
{% endblock %}
</div>
</body>
</html>
In this example, the {% block %} tags dene four blocks that child templates can ll
in. All the block tag does is tell the template engine that a child template may override
those portions of the template.
135
18.14.2 Child Template
A child template might look like this:
{% extends "layout.html" %}
{% block title %}Index{% endblock %}
{% block head %}
{{ super() }}
<style type="text/css">
.important { color: #336699; }
</style>
{% endblock %}
{% block content %}
<h1>Index</h1>
<p class="important">
Welcome on my awesome homepage.
{% endblock %}
The {% extends %} tag is the key here. It tells the template engine that this template
extends another template. When the template system evaluates this template, rst
it locates the parent. The extends tag must be the rst tag in the template. To render
the contents of a block dened in the parent template, use {{ super() }}.
18.15 Message Flashing
Good applications and user interfaces are all about feedback. If the user does not get
enough feedback they will probably end up hating the application. Flask provides a
really simple way to give feedback to a user with the ashing system. The ashing
system basically makes it possible to record a message at the end of a request and
access it next request and only next request. This is usually combined with a layout
template that does this.
18.15.1 Simple Flashing
So here is a full example:
from flask import Flask, flash, redirect, render_template, \
request, url_for
app = Flask(__name__)
app.secret_key = some_secret
@app.route(/)
def index():
return render_template(index.html)
@app.route(/login, methods=[GET, POST])
def login():
136
error = None
if request.method == POST:
if request.form[username] != admin or \
request.form[password] != secret:
error = Invalid credentials
else:
flash(You were successfully logged in)
return redirect(url_for(index))
return render_template(login.html, error=error)
if __name__ == "__main__":
app.run()
And here the layout.html template which does the magic:
<!doctype html>
<title>My Application</title>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
{% block body %}{% endblock %}
And here the index.html template:
{% extends "layout.html" %}
{% block body %}
<h1>Overview</h1>
<p>Do you want to <a href="{{ url_for(login) }}">log in?</a>
{% endblock %}
And of course the login template:
{% extends "layout.html" %}
{% block body %}
<h1>Login</h1>
{% if error %}
<p class=error><strong>Error:</strong> {{ error }}
{% endif %}
<form action="" method=post>
<dl>
<dt>Username:
<dd><input type=text name=username value="{{
request.form.username }}">
<dt>Password:
<dd><input type=password name=password>
</dl>
137
<p><input type=submit value=Login>
</form>
{% endblock %}
18.15.2 Flashing With Categories
New in version 0.3.
It is also possible to provide categories when ashing a message. The default cate-
gory if nothing is provided is message. Alternative categories can be used to give
the user better feedback. For example error messages could be displayed with a red
background.
To ash a message with a different category, just use the second argument to the
flash() function:
flash(uInvalid password provided, error)
Inside the template you then have to tell the get_flashed_messages() function to also
return the categories. The loop looks slightly different in that situation then:
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<ul class=flashes>
{% for category, message in messages %}
<li class="{{ category }}">{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
This is just one example of how to render these ashed messages. One might also use
the category to add a prex such as <strong>Error:</strong> to the message.
18.15.3 Filtering Flash Messages
New in version 0.9.
Optionally you can pass a list of categories which lters the results of
get_flashed_messages(). This is useful if you wish to render each category in a sepa-
rate block.
{% with errors = get_flashed_messages(category_filter=["error"]) %}
{% if errors %}
<div class="alert-message block-message error">
<a class="close" href="#"></a>
<ul>
{%- for msg in errors %}
<li>{{ msg }}</li>
{% endfor -%}
138
</ul>
</div>
{% endif %}
{% endwith %}
18.16 AJAX with jQuery
jQuery is a small JavaScript library commonly used to simplify working with the DOM
and JavaScript in general. It is the perfect tool to make web applications more dynamic
by exchanging JSON between server and client.
JSON itself is a very lightweight transport format, very similar to how Python primi-
tives (numbers, strings, dicts and lists) look like which is widely supported and very
easy to parse. It became popular a few years ago and quickly replaced XML as trans-
port format in web applications.
18.16.1 Loading jQuery
In order to use jQuery, you have to download it rst and place it in the static folder of
your application and then ensure its loaded. Ideally you have a layout template that
is used for all pages where you just have to add a script statement to the bottom of
your <body> to load jQuery:
<script type=text/javascript src="{{
url_for(static, filename=jquery.js) }}"></script>
Another method is using Googles AJAX Libraries API to load jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write(<script src="{{
url_for(static, filename=jquery.js) }}">\x3C/script>)</script>
In this case you have to put jQuery into your static folder as a fallback, but it will
rst try to load it directly from Google. This has the advantage that your website will
probably load faster for users if they went to at least one other website before using
the same jQuery version from Google because it will already be in the browser cache.
18.16.2 Where is My Site?
Do you know where your application is? If you are developing the answer is quite
simple: its on localhost port something and directly on the root of that server. But
what if you later decide to move your application to a different location? For example
to http://example.com/myapp? On the server side this never was a problem because
we were using the handy url_for() function that could answer that question for us,
but if we are using jQuery we should not hardcode the path to the application but
make that dynamic, so how can we do that?
139
A simple method would be to add a script tag to our page that sets a global variable
to the prex to the root of the application. Something like this:
<script type=text/javascript>
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
</script>
The |safe is necessary in Flask before 0.10 so that Jinja does not escape the JSON
encoded string with HTML rules. Usually this would be necessary, but we are inside
a script block here where different rules apply.
Information for Pros
In HTML the script tag is declared CDATA which means that entities will not be
parsed. Everything until </script> is handled as script. This also means that there
must never be any </ between the script tags. |tojson is kind enough to do the right
thing here and escape slashes for you ({{ "</script>"|tojson|safe }} is rendered as
"<\/script>").
In Flask 0.10 it goes a step further and escapes all HTML tags with unicode escapes.
This makes it possible for Flask to automatically mark the result as HTML safe.
18.16.3 JSON View Functions
Now lets create a server side function that accepts two URL arguments of numbers
which should be added together and then sent back to the application in a JSONobject.
This is a really ridiculous example and is something you usually would do on the
client side alone, but a simple example that shows how you would use jQuery and
Flask nonetheless:
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
@app.route(/_add_numbers)
def add_numbers():
a = request.args.get(a, 0, type=int)
b = request.args.get(b, 0, type=int)
return jsonify(result=a + b)
@app.route(/)
def index():
return render_template(index.html)
As you can see I also added an index method here that renders a template. This tem-
plate will load jQuery as above and have a little form we can add two numbers and a
link to trigger the function on the server side.
Note that we are using the get() method here which will never fail. If the key is
missing a default value (here 0) is returned. Furthermore it can convert values to a
specic type (like in our case int). This is especially handy for code that is triggered by
140
a script (APIs, JavaScript etc.) because you dont need special error reporting in that
case.
18.16.4 The HTML
Your index.html template either has to extend a layout.html template with jQuery
loaded and the $SCRIPT_ROOT variable set, or do that on the top. Heres the HTML
code needed for our little application (index.html). Notice that we also drop the script
directly into the HTML here. It is usually a better idea to have that in a separate script
le:
<script type=text/javascript>
$(function() {
$(a#calculate).bind(click, function() {
$.getJSON($SCRIPT_ROOT + /_add_numbers, {
a: $(input[name="a"]).val(),
b: $(input[name="b"]).val()
}, function(data) {
$("#result").text(data.result);
});
return false;
});
});
</script>
<h1>jQuery Example</h1>
<p><input type=text size=5 name=a> +
<input type=text size=5 name=b> =
<span id=result>?</span>
<p><a href=# id=calculate>calculate server side</a>
I wont go into detail here about how jQuery works, just a very quick explanation of
the little bit of code above:
1. $(function() { ... }) species code that should run once the browser is done
loading the basic parts of the page.
2. $(selector) selects an element and lets you operate on it.
3. element.bind(event, func) species a function that should run when the user
clicked on the element. If that function returns false, the default behavior will not
kick in (in this case, navigate to the # URL).
4. $.getJSON(url, data, func) sends a GET request to url and will send the con-
tents of the data object as query parameters. Once the data arrived, it will call
the given function with the return value as argument. Note that we can use the
$SCRIPT_ROOT variable here that we set earlier.
If you dont get the whole picture, download the sourcecode for this example from
github.
141
18.17 Custom Error Pages
Flask comes with a handy abort() function that aborts a request with an HTTP error
code early. It will also provide a plain black and white error page for you with a basic
description, but nothing fancy.
Depending on the error code it is less or more likely for the user to actually see such
an error.
18.17.1 Common Error Codes
The following error codes are some that are often displayed to the user, even if the
application behaves correctly:
404 Not Found The good old chap, you made a mistake typing that URL message.
So common that even novices to the internet know that 404 means: damn, the
thing I was looking for is not there. Its a very good idea to make sure there is
actually something useful on a 404 page, at least a link back to the index.
403 Forbidden If you have some kind of access control on your website, you will have
to send a 403 code for disallowed resources. So make sure the user is not lost
when they try to access a forbidden resource.
410 Gone Did you know that there the 404 Not Found has a brother named 410
Gone? Few people actually implement that, but the idea is that resources that
previously existed and got deleted answer with 410 instead of 404. If you are
not deleting documents permanently from the database but just mark them as
deleted, do the user a favour and use the 410 code instead and display a message
that what they were looking for was deleted for all eternity.
500 Internal Server Error Usually happens on programming errors or if the server is
overloaded. A terrible good idea to have a nice page there, because your appli-
cation will fail sooner or later (see also: Logging Application Errors).
18.17.2 Error Handlers
An error handler is a function, just like a view function, but it is called when an error
happens and is passed that error. The error is most likely a HTTPException, but in one
case it can be a different error: a handler for internal server errors will be passed other
exception instances as well if they are uncaught.
An error handler is registered with the errorhandler() decorator and the error code
of the exception. Keep in mind that Flask will not set the error code for you, so make
sure to also provide the HTTP status code when returning a response.
Here an example implementation for a 404 Page Not Found exception:
from flask import render_template
142
@app.errorhandler(404)
def page_not_found(e):
return render_template(404.html), 404
An example template might be this:
{% extends "layout.html" %}
{% block title %}Page Not Found{% endblock %}
{% block body %}
<h1>Page Not Found</h1>
<p>What you were looking for is just not there.
<p><a href="{{ url_for(index) }}">go somewhere nice</a>
{% endblock %}
18.18 Lazily Loading Views
Flask is usually used with the decorators. Decorators are simple and you have the
URL right next to the function that is called for that specic URL. However there is
a downside to this approach: it means all your code that uses decorators has to be
imported upfront or Flask will never actually nd your function.
This can be a problem if your application has to import quick. It might have to do
that on systems like Googles App Engine or other systems. So if you suddenly notice
that your application outgrows this approach you can fall back to a centralized URL
mapping.
The system that enables having a central URL map is the add_url_rule() function.
Instead of using decorators, you have a le that sets up the application with all URLs.
18.18.1 Converting to Centralized URL Map
Imagine the current application looks somewhat like this:
from flask import Flask
app = Flask(__name__)
@app.route(/)
def index():
pass
@app.route(/user/<username>)
def user(username):
pass
Then the centralized approach you would have one le with the views (views.py) but
without any decorator:
143
def index():
pass
def user(username):
pass
And then a le that sets up an application which maps the functions to URLs:
from flask import Flask
from yourapplication import views
app = Flask(__name__)
app.add_url_rule(/, view_func=views.index)
app.add_url_rule(/user/<username>, view_func=views.user)
18.18.2 Loading Late
So far we only split up the views and the routing, but the module is still loaded up-
front. The trick to actually load the viewfunction as needed. This can be accomplished
with a helper class that behaves just like a function but internally imports the real func-
tion on rst use:
from werkzeug import import_string, cached_property
class LazyView(object):
def __init__(self, import_name):
self.__module__, self.__name__ = import_name.rsplit(., 1)
self.import_name = import_name
@cached_property
def view(self):
return import_string(self.import_name)
def __call__(self, *args, **kwargs):
return self.view(*args, **kwargs)
Whats important here is is that __module__ and __name__ are properly set. This is
used by Flask internally to gure out how to name the URL rules in case you dont
provide a name for the rule yourself.
Then you can dene your central place to combine the views like this:
from flask import Flask
from yourapplication.helpers import LazyView
app = Flask(__name__)
app.add_url_rule(/,
view_func=LazyView(yourapplication.views.index))
app.add_url_rule(/user/<username>,
view_func=LazyView(yourapplication.views.user))
144
You can further optimize this in terms of amount of keystrokes needed to write this by
having a function that calls into add_url_rule() by prexing a string with the project
name and a dot, and by wrapping view_func in a LazyView as needed:
def url(url_rule, import_name, **options):
view = LazyView(yourapplication. + import_name)
app.add_url_rule(url_rule, view_func=view, **options)
url(/, views.index)
url(/user/<username>, views.user)
One thing to keep in mind is that before and after request handlers have to be in a le
that is imported upfront to work properly on the rst request. The same goes for any
kind of remaining decorator.
18.19 MongoKit in Flask
Using a document database rather than a full DBMS gets more common these days.
This pattern shows how to use MongoKit, a document mapper library, to integrate
with MongoDB.
This pattern requires a running MongoDB server and the MongoKit library installed.
There are two very common ways to use MongoKit. I will outline each of them here:
18.19.1 Declarative
The default behavior of MongoKit is the declarative one that is based on common
ideas from Django or the SQLAlchemy declarative extension.
Here an example app.py module for your application:
from flask import Flask
from mongokit import Connection, Document
# configuration
MONGODB_HOST = localhost
MONGODB_PORT = 27017
# create the little application object
app = Flask(__name__)
app.config.from_object(__name__)
# connect to the database
connection = Connection(app.config[MONGODB_HOST],
app.config[MONGODB_PORT])
To dene your models, just subclass the Document class that is imported from Mon-
goKit. If youve seen the SQLAlchemy pattern you may wonder why we do not have
145
a session and even do not dene a init_db function here. On the one hand, MongoKit
does not have something like a session. This sometimes makes it more to type but
also makes it blazingly fast. On the other hand, MongoDB is schemaless. This means
you can modify the data structure from one insert query to the next without any prob-
lem. MongoKit is just schemaless too, but implements some validation to ensure data
integrity.
Here is an example document (put this also into app.py, e.g.):
def max_length(length):
def validate(value):
if len(value) <= length:
return True
raise Exception(%s must be at most %s characters long % length)
return validate
class User(Document):
structure = {
name: unicode,
email: unicode,
}
validators = {
name: max_length(50),
email: max_length(120)
}
use_dot_notation = True
def __repr__(self):
return <User %r> % (self.name)
# register the User document with our current connection
connection.register([User])
This example shows you how to dene your schema (named structure), a valida-
tor for the maximum character length and uses a special MongoKit feature called
use_dot_notation. Per default MongoKit behaves like a python dictionary but with
use_dot_notation set to True you can use your documents like you use models in nearly
any other ORM by using dots to separate between attributes.
You can insert entries into the database like this:
>>> from yourapplication.database import connection
>>> from yourapplication.models import User
>>> collection = connection[test].users
>>> user = collection.User()
>>> user[name] = uadmin
>>> user[email] = uadmin@localhost
>>> user.save()
Note that MongoKit is kinda strict with used column types, you must not use a com-
mon str type for either name or email but unicode.
Querying is simple as well:
146
>>> list(collection.User.find())
[<User uadmin>]
>>> collection.User.find_one({name: uadmin})
<User uadmin>
18.19.2 PyMongo Compatibility Layer
If you just want to use PyMongo, you can do that with MongoKit as well. You may
use this process if you need the best performance to get. Note that this example does
not show how to couple it with Flask, see the above MongoKit code for examples:
from MongoKit import Connection
connection = Connection()
To insert data you can use the insert method. We have to get a collection rst, this is
somewhat the same as a table in the SQL world.
>>> collection = connection[test].users
>>> user = {name: uadmin, email: uadmin@localhost}
>>> collection.insert(user)
MongoKit will automatically commit for us.
To query your database, you use the collection directly:
>>> list(collection.find())
[{u_id: ObjectId(4c271729e13823182f000000), uname: uadmin, uemail: uadmin@localhost}]
>>> collection.find_one({name: uadmin})
{u_id: ObjectId(4c271729e13823182f000000), uname: uadmin, uemail: uadmin@localhost}
These results are also dict-like objects:
>>> r = collection.find_one({name: uadmin})
>>> r[email]
uadmin@localhost
For more information about MongoKit, head over to the website.
18.20 Adding a favicon
A favicon is an icon used by browsers for tabs and bookmarks. This helps to distin-
guish your website and to give it a unique brand.
A common question is how to add a favicon to a ask application. First, of course,
you need an icon. It should be 16 16 pixels and in the ICO le format. This is not a
requirement but a de-facto standard supported by all relevant browsers. Put the icon
in your static directory as favicon.ico.
147
Now, to get browsers to nd your icon, the correct way is to add a link tag in your
HTML. So, for example:
<link rel="shortcut icon" href="{{ url_for(static, filename=favicon.ico) }}">
Thats all you need for most browsers, however some really old ones do not support
this standard. The old de-facto standard is to serve this le, with this name, at the
website root. If your application is not mounted at the root path of the domain you
either need to congure the webserver to serve the icon at the root or if you cant do
that youre out of luck. If however your application is the root you can simply route a
redirect:
app.add_url_rule(/favicon.ico,
redirect_to=url_for(static, filename=favicon.ico))
If you want to save the extra redirect request you can also write a view using
send_from_directory():
import os
from flask import send_from_directory
@app.route(/favicon.ico)
def favicon():
return send_from_directory(os.path.join(app.root_path, static),
favicon.ico, mimetype=image/vnd.microsoft.icon)
We can leave out the explicit mimetype and it will be guessed, but we may as well
specify it to avoid the extra guessing, as it will always be the same.
The above will serve the icon via your application and if possible its better to cong-
ure your dedicated web server to serve it; refer to the webservers documentation.
18.20.1 See also
The Favicon article on Wikipedia
18.21 Streaming Contents
Sometimes you want to send an enormous amount of data to the client, much more
than you want to keep in memory. When you are generating the data on the y though,
how do you send that back to the client without the roundtrip to the lesystem?
The answer is by using generators and direct responses.
18.21.1 Basic Usage
This is a basic view function that generates a lot of CSV data on the y. The trick is to
have an inner function that uses a generator to generate data and to then invoke that
148
function and pass it to a response object:
from flask import Response
@app.route(/large.csv)
def generate_large_csv():
def generate():
for row in iter_all_rows():
yield ,.join(row) + \n
return Response(generate(), mimetype=text/csv)
Each yield expression is directly sent to the browser. Note though that some WSGI
middlewares might break streaming, so be careful there in debug environments with
prolers and other things you might have enabled.
18.21.2 Streaming from Templates
The Jinja2 template engine also supports rendering templates piece by piece. This
functionality is not directly exposed by Flask because it is quite uncommon, but you
can easily do it yourself:
from flask import Response
def stream_template(template_name, **context):
app.update_template_context(context)
t = app.jinja_env.get_template(template_name)
rv = t.stream(context)
rv.enable_buffering(5)
return rv
@app.route(/my-large-page.html)
def render_large_template():
rows = iter_all_rows()
return Response(stream_template(the_template.html, rows=rows))
The trick here is to get the template object from the Jinja2 environment on the appli-
cation and to call stream() instead of render() which returns a stream object instead
of a string. Since were bypassing the Flask template render functions and using the
template object itself we have to make sure to update the render context ourselves by
calling update_template_context(). The template is then evaluated as the stream is
iterated over. Since each time you do a yield the server will ush the content to the
client you might want to buffer up a few items in the template which you can do with
rv.enable_buffering(size). 5 is a sane default.
18.21.3 Streaming with Context
New in version 0.9.
149
Note that when you stream data, the request context is already gone the moment the
function executes. Flask 0.9 provides you with a helper that can keep the request
context around during the execution of the generator:
from flask import stream_with_context, request, Response
@app.route(/stream)
def streamed_response():
def generate():
yield Hello
yield request.args[name]
yield !
return Response(stream_with_context(generate()))
Without the stream_with_context() function you would get a RuntimeError at that
point.
18.22 Deferred Request Callbacks
One of the design principles of Flask is that response objects are created and passed
down a chain of potential callbacks that can modify them or replace them. When the
request handling starts, there is no response object yet. It is created as necessary either
by a view function or by some other component in the system.
But what happens if you want to modify the response at a point where the response
does not exist yet? A common example for that would be a before-request function
that wants to set a cookie on the response object.
One way is to avoid the situation. Very often that is possible. For instance you can try
to move that logic into an after-request callback instead. Sometimes however moving
that code there is just not a very pleasant experience or makes code look very awk-
ward.
As an alternative possibility you can attach a bunch of callback functions to the g object
and call them at the end of the request. This way you can defer code execution from
anywhere in the application.
18.22.1 The Decorator
The following decorator is the key. It registers a function on a list on the g object:
from flask import g
def after_this_request(f):
if not hasattr(g, after_request_callbacks):
g.after_request_callbacks = []
g.after_request_callbacks.append(f)
return f
150
18.22.2 Calling the Deferred
Now you can use the after_this_request decorator to mark a function to be called at the
end of the request. But we still need to call them. For this the following function needs
to be registered as after_request() callback:
@app.after_request
def call_after_request_callbacks(response):
for callback in getattr(g, after_request_callbacks, ()):
callback(response)
return response
18.22.3 A Practical Example
Nowwe can easily at any point in time register a function to be called at the end of this
particular request. For example you can remember the current language of the user in
a cookie in the before-request function:
from flask import request
@app.before_request
def detect_user_language():
language = request.cookies.get(user_lang)
if language is None:
language = guess_language_from_request()
@after_this_request
def remember_language(response):
response.set_cookie(user_lang, language)
g.language = language
18.23 Adding HTTP Method Overrides
Some HTTP proxies do not support arbitrary HTTP methods or newer HTTP methods
(such as PATCH). In that case its possible to proxy HTTP methods through another
HTTP method in total violation of the protocol.
The way this works is by letting the client do an HTTP POST request and set the
X-HTTP-Method-Override header and set the value to the intended HTTP method (such
as PATCH).
This can easily be accomplished with an HTTP middleware:
class HTTPMethodOverrideMiddleware(object):
allowed_methods = frozenset([
GET,
HEAD,
POST,
DELETE,
151
PUT,
PATCH,
OPTIONS
])
bodyless_methods = frozenset([GET, HEAD, OPTIONS, DELETE])
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
method = environ.get(HTTP_X_HTTP_METHOD_OVERRIDE, ).upper()
if method in self.allowed_methods:
method = method.encode(ascii, replace)
environ[REQUEST_METHOD] = method
if method in self.bodyless_methods:
environ[CONTENT_LENGTH] = 0
return self.app(environ, start_response)
To use this with Flask this is all that is necessary:
from flask import Flask
app = Flask(__name__)
app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)
18.24 Request Content Checksums
Various pieces of code can consume the request data and preprocess it. For instance
JSON data ends up on the request object already read and processed, form data ends
up there as well but goes through a different code path. This seems inconvenient when
you want to calculate the checksum of the incoming request data. This is necessary
sometimes for some APIs.
Fortunately this is however very simple to change by wrapping the input stream.
The following example calculates the SHA1 checksum of the incoming data as it gets
read and stores it in the WSGI environment:
import hashlib
class ChecksumCalcStream(object):
def __init__(self, stream):
self._stream = stream
self._hash = hashlib.sha1()
def read(self, bytes):
rv = self._stream.read(bytes)
self._hash.update(rv)
152
return rv
def readline(self, size_hint):
rv = self._stream.readline(size_hint)
self._hash.update(rv)
return rv
def generate_checksum(request):
env = request.environ
stream = ChecksumCalcStream(env[wsgi.input])
env[wsgi.input] = stream
return stream._hash
To use this, all you need to do is to hook the calculating stream in before the request
starts consuming data. (Eg: be careful accessing request.form or anything of that
nature. before_request_handlers for instance should be careful not to access it).
Example usage:
@app.route(/special-api, methods=[POST])
def special_api():
hash = generate_checksum(request)
# Accessing this parses the input stream
files = request.files
# At this point the hash is fully constructed.
checksum = hash.hexdigest()
return Hash was: %s % checksum
18.25 Celery Based Background Tasks
Celery is a task queue for Python with batteries included. It used to have a Flask inte-
gration but it became unnecessary after some restructuring of the internals of Celery
with Version 3. This guide lls in the blanks in how to properly use Celery with Flask
but assumes that you generally already read the First Steps with Celery guide in the
ofcial Celery documentation.
18.25.1 Installing Celery
Celery is on the Python Package Index (PyPI), so it can be installed with standard
Python tools like pip or easy_install:
$ pip install celery
18.25.2 Conguring Celery
The rst thing you need is a Celery instance, this is called the celery application. It
serves the same purpose as the Flask object in Flask, just for Celery. Since this instance
153
is used as the entry-point for everything you want to do in Celery, like creating tasks
and managing workers, it must be possible for other modules to import it.
For instance you can place this in a tasks module. While you can use Celery without
any reconguration with Flask, it becomes a bit nicer by subclassing tasks and adding
support for Flasks application contexts and hooking it up with the Flask congura-
tion.
This is all that is necessary to properly integrate Celery with Flask:
from celery import Celery
def make_celery(app):
celery = Celery(app.import_name, broker=app.config[CELERY_BROKER_URL])
celery.conf.update(app.config)
TaskBase = celery.Task
class ContextTask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask
return celery
The function creates a new Celery object, congures it with the broker from the ap-
plication cong, updates the rest of the Celery cong from the Flask cong and then
creates a subclass of the task that wraps the task execution in an application context.
18.25.3 Minimal Example
With what we have above this is the minimal example of using Celery with Flask:
from flask import Flask
flask_app = Flask(__name__)
flask_app.config.update(
CELERY_BROKER_URL=redis://localhost:6379,
CELERY_RESULT_BACKEND=redis://localhost:6379
)
celery = make_celery(flask_app)
@celery.task()
def add_together(a, b):
return a + b
This task can now be called in the background:
>>> result = add_together.delay(23, 42)
>>> result.wait()
65
154
18.25.4 Running the Celery Worker
Now if you jumped in and already executed the above code you will be disappointed
to learn that your .wait() will never actually return. Thats because you also need to
run celery. You can do that by running celery as a worker:
$ celery -A your_application.celery worker
The your_application string has to point to your applications package or module that
creates the celery object.
155
156
CHAPTER
NINETEEN
DEPLOYMENT OPTIONS
Depending on what you have available there are multiple ways to run Flask applica-
tions. You can use the builtin server during development, but you should use a full
deployment option for production applications. (Do not use the builtin development
server in production.) Several options are available and documented here.
If you have a different WSGI server look up the server documentation about how to
use a WSGI app with it. Just remember that your Flask application object is the actual
WSGI application.
For hosted options to get up and running quickly, see Deploying to a Web Server in the
Quickstart.
19.1 mod_wsgi (Apache)
If you are using the Apache webserver, consider using mod_wsgi.
Watch Out
Please make sure in advance that any app.run() calls you might have in your applica-
tion le are inside an if __name__ == __main__: block or moved to a separate le.
Just make sure its not called because this will always start a local WSGI server which
we do not want if we deploy that application to mod_wsgi.
19.1.1 Installing mod_wsgi
If you dont have mod_wsgi installed yet you have to either install it using a package
manager or compile it yourself. The mod_wsgi installation instructions cover source
installations on UNIX systems.
If you are using Ubuntu/Debian you can apt-get it and activate it as follows:
# apt-get install libapache2-mod-wsgi
On FreeBSD install mod_wsgi by compiling the www/mod_wsgi port or by using
pkg_add:
157
# pkg_add -r mod_wsgi
If you are using pkgsrc you can install mod_wsgi by compiling the www/ap2-wsgi pack-
age.
If you encounter segfaulting child processes after the rst apache reload you can safely
ignore them. Just restart the server.
19.1.2 Creating a .wsgi le
To run your application you need a yourapplication.wsgi le. This le contains the code
mod_wsgi is executing on startup to get the application object. The object called appli-
cation in that le is then used as application.
For most applications the following le should be sufcient:
from yourapplication import app as application
If you dont have a factory function for application creation but a singleton instance
you can directly import that one as application.
Store that le somewhere that you will nd it again (e.g.: /var/www/yourapplication)
and make sure that yourapplication and all the libraries that are in use are on the python
load path. If you dont want to install it system wide consider using a virtual python
instance. Keep in mind that you will have to actually install your application into the
virtualenv as well. Alternatively there is the option to just patch the path in the .wsgi
le before the import:
import sys
sys.path.insert(0, /path/to/the/application)
19.1.3 Conguring Apache
The last thing you have to do is to create an Apache conguration le for your ap-
plication. In this example we are telling mod_wsgi to execute the application under a
different user for security reasons:
<VirtualHost *>
ServerName example.com
WSGIDaemonProcess yourapplication user=user1 group=group1 threads=5
WSGIScriptAlias / /var/www/yourapplication/yourapplication.wsgi
<Directory /var/www/yourapplication>
WSGIProcessGroup yourapplication
WSGIApplicationGroup %{GLOBAL}
Order deny,allow
Allow from all
158
</Directory>
</VirtualHost>
Note: WSGIDaemonProcess isnt implemented in Windows and Apache will refuse to
run with the above conguration. On a Windows system, eliminate those lines:
<VirtualHost *>
ServerName example.com
WSGIScriptAlias / C:\yourdir\yourapp.wsgi
<Directory C:\yourdir>
Order deny,allow
Allow from all
</Directory>
</VirtualHost>
For more information consult the mod_wsgi wiki.
19.1.4 Troubleshooting
If your application does not run, follow this guide to troubleshoot:
Problem: application does not run, errorlog shows SystemExit ignored You have a
app.run() call in your application le that is not guarded by an if __name__
== __main__: condition. Either remove that run() call from the le and move
it into a separate run.py le or put it into such an if block.
Problem: application gives permission errors Probably caused by your application
running as the wrong user. Make sure the folders the application needs access to
have the proper privileges set and the application runs as the correct user (user
and group parameter to the WSGIDaemonProcess directive)
Problem: application dies with an error on print Keep in mind that mod_wsgi dis-
allows doing anything with sys.stdout and sys.stderr. You can disable this
protection from the cong by setting the WSGIRestrictStdout to off:
WSGIRestrictStdout Off
Alternatively you can also replace the standard out in the .wsgi le with a differ-
ent stream:
import sys
sys.stdout = sys.stderr
Problem: accessing resources gives IO errors Your application probably is a single
.py le you symlinked into the site-packages folder. Please be aware that this
does not work, instead you either have to put the folder into the pythonpath the
le is stored in, or convert your application into a package.
The reason for this is that for non-installed packages, the module lename is
used to locate the resources and for symlinks the wrong lename is picked up.
159
19.1.5 Support for Automatic Reloading
To help deployment tools you can activate support for automatic reloading. Whenever
something changes the .wsgi le, mod_wsgi will reload all the daemon processes for us.
For that, just add the following directive to your Directory section:
WSGIScriptReloading On
19.1.6 Working with Virtual Environments
Virtual environments have the advantage that they never install the required depen-
dencies system wide so you have a better control over what is used where. If you
want to use a virtual environment with mod_wsgi you have to modify your .wsgi le
slightly.
Add the following lines to the top of your .wsgi le:
activate_this = /path/to/env/bin/activate_this.py
execfile(activate_this, dict(__file__=activate_this))
This sets up the load paths according to the settings of the virtual environment. Keep
in mind that the path has to be absolute.
19.2 Standalone WSGI Containers
There are popular servers written in Python that contain WSGI applications and serve
HTTP. These servers stand alone when they run; you can proxy to them from your
web server. Note the section on Proxy Setups if you run into issues.
19.2.1 Gunicorn
Gunicorn Green Unicorn is a WSGI HTTP Server for UNIX. Its a pre-fork worker
model ported from Rubys Unicorn project. It supports both eventlet and greenlet.
Running a Flask application on this server is quite simple:
gunicorn myproject:app
Gunicorn provides many command-line options see gunicorn -h. For example, to
run a Flask application with 4 worker processes (-w 4) binding to localhost port 4000
(-b 127.0.0.1:4000):
gunicorn -w 4 -b 127.0.0.1:4000 myproject:app
160
19.2.2 Tornado
Tornado is an open source version of the scalable, non-blocking web server and tools
that power FriendFeed. Because it is non-blocking and uses epoll, it can handle thou-
sands of simultaneous standing connections, which means it is ideal for real-time web
services. Integrating this service with Flask is straightforward:
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from yourapplication import app
http_server = HTTPServer(WSGIContainer(app))
http_server.listen(5000)
IOLoop.instance().start()
19.2.3 Gevent
Gevent is a coroutine-based Python networking library that uses greenlet to provide a
high-level synchronous API on top of libevent event loop:
from gevent.wsgi import WSGIServer
from yourapplication import app
http_server = WSGIServer((, 5000), app)
http_server.serve_forever()
19.2.4 Twisted Web
Twisted Web is the web server shipped with Twisted, a mature, non-blocking event-
driven networking library. Twisted Web comes with a standard WSGI container which
can be controlled from the command line using the twistd utility:
twistd web --wsgi myproject.app
This example will run a Flask application called app from a module named myproject.
Twisted Web supports many ags and options, and the twistd utility does as well; see
twistd -h and twistd web -h for more information. For example, to run a Twisted
Web server in the foreground, on port 8080, with an application from myproject:
twistd -n web --port 8080 --wsgi myproject.app
19.2.5 Proxy Setups
If you deploy your application using one of these servers behind an HTTP proxy
you will need to rewrite a few headers in order for the application to work. The
161
two problematic values in the WSGI environment usually are REMOTE_ADDR and
HTTP_HOST. You can congure your httpd to pass these headers, or you can x them
in middleware. Werkzeug ships a xer that will solve some common setups, but you
might want to write your own WSGI middleware for specic setups.
Heres a simple nginx conguration which proxies to an application served on local-
host at port 8000, setting appropriate headers:
server {
listen 80;
server_name _;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
location / {
proxy_pass http://127.0.0.1:8000/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
If your httpd is not providing these headers, the most common setup invokes the host
being set from X-Forwarded-Host and the remote address from X-Forwarded-For:
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
Trusting Headers
Please keep in mind that it is a security issue to use such a middleware in a non-proxy
setup because it will blindly trust the incoming headers which might be forged by
malicious clients.
If you want to rewrite the headers from another header, you might want to use a xer
like this:
class CustomProxyFix(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
host = environ.get(HTTP_X_FHOST, )
if host:
environ[HTTP_HOST] = host
return self.app(environ, start_response)
162
app.wsgi_app = CustomProxyFix(app.wsgi_app)
19.3 uWSGI
uWSGI is a deployment option on servers like nginx, lighttpd, and cherokee; see
FastCGI and Standalone WSGI Containers for other options. To use your WSGI appli-
cation with uWSGI protocol you will need a uWSGI server rst. uWSGI is both a
protocol and an application server; the application server can serve uWSGI, FastCGI,
and HTTP protocols.
The most popular uWSGI server is uwsgi, which we will use for this guide. Make sure
to have it installed to follow along.
Watch Out
Please make sure in advance that any app.run() calls you might have in your applica-
tion le are inside an if __name__ == __main__: block or moved to a separate le.
Just make sure its not called because this will always start a local WSGI server which
we do not want if we deploy that application to uWSGI.
19.3.1 Starting your app with uwsgi
uwsgi is designed to operate on WSGI callables found in python modules.
Given a ask application in myapp.py, use the following command:
$ uwsgi -s /tmp/uwsgi.sock --module myapp --callable app
Or, if you prefer:
$ uwsgi -s /tmp/uwsgi.sock -w myapp:app
19.3.2 Conguring nginx
A basic ask uWSGI conguration for nginx looks like this:
location = /yourapplication { rewrite ^ /yourapplication/; }
location /yourapplication { try_files $uri @yourapplication; }
location @yourapplication {
include uwsgi_params;
uwsgi_param SCRIPT_NAME /yourapplication;
uwsgi_modifier1 30;
uwsgi_pass unix:/tmp/uwsgi.sock;
}
163
This conguration binds the application to /yourapplication. If you want to have it in the
URL root its a bit simpler because you dont have to tell it the WSGI SCRIPT_NAME
or set the uwsgi modier to make use of it:
location / { try_files $uri @yourapplication; }
location @yourapplication {
include uwsgi_params;
uwsgi_pass unix:/tmp/uwsgi.sock;
}
19.4 FastCGI
FastCGI is a deployment option on servers like nginx, lighttpd, and cherokee; see
uWSGI and Standalone WSGI Containers for other options. To use your WSGI applica-
tion with any of them you will need a FastCGI server rst. The most popular one is
up which we will use for this guide. Make sure to have it installed to follow along.
Watch Out
Please make sure in advance that any app.run() calls you might have in your applica-
tion le are inside an if __name__ == __main__: block or moved to a separate le.
Just make sure its not called because this will always start a local WSGI server which
we do not want if we deploy that application to FastCGI.
19.4.1 Creating a .fcgi le
First you need to create the FastCGI server le. Lets call it yourapplication.fcgi:
#!/usr/bin/python
from flup.server.fcgi import WSGIServer
from yourapplication import app
if __name__ == __main__:
WSGIServer(app).run()
This is enough for Apache to work, however nginx and older versions of lighttpd need
a socket to be explicitly passed to communicate with the FastCGI server. For that to
work you need to pass the path to the socket to the WSGIServer:
WSGIServer(application, bindAddress=/path/to/fcgi.sock).run()
The path has to be the exact same path you dene in the server cong.
Save the yourapplication.fcgi le somewhere you will nd it again. It makes sense to
have that in /var/www/yourapplication or something similar.
Make sure to set the executable bit on that le so that the servers can execute it:
164
# chmod +x /var/www/yourapplication/yourapplication.fcgi
19.4.2 Conguring Apache
The example above is good enough for a basic Apache deployment but your .fcgi le
will appear in your application URL e.g. example.com/yourapplication.fcgi/news/.
There are fewways to congure your application so that yourapplication.fcgi does not
appear in the URL. A preferable way is to use the ScriptAlias and SetHandler cong-
uration directives to route requests to the FastCGI server. The following example uses
FastCgiServer to start 5 instances of the application which will handle all incoming
requests:
LoadModule fastcgi_module /usr/lib64/httpd/modules/mod_fastcgi.so
FastCgiServer /var/www/html/yourapplication/app.fcgi -idle-timeout 300 -processes 5
<VirtualHost *>
ServerName webapp1.mydomain.com
DocumentRoot /var/www/html/yourapplication
AddHandler fastcgi-script fcgi
ScriptAlias / /var/www/html/yourapplication/app.fcgi/
<Location />
SetHandler fastcgi-script
</Location>
</VirtualHost>
These processes will be managed by Apache. If youre using an standalone FastCGI
server, you can use the FastCgiExternalServer directive instead. Note that in the fol-
lowing the path is not real, its simply used as an identier to other directives such as
AliasMatch:
FastCgiServer /var/www/html/yourapplication -host 127.0.0.1:3000
If you cannot set ScriptAlias, for example on an shared web host, you can use WSGI
middleware to remove yourapplication.fcgi from the URLs. Set .htaccess:
<IfModule mod_fcgid.c>
AddHandler fcgid-script .fcgi
<Files ~ (\.fcgi)>
SetHandler fcgid-script
Options +FollowSymLinks +ExecCGI
</Files>
</IfModule>
<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
RewriteBase /
165
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ yourapplication.fcgi/$1 [QSA,L]
</IfModule>
Set yourapplication.fcgi:
#!/usr/bin/python
#: optional path to your local python site-packages folder
import sys
sys.path.insert(0, <your_local_path>/lib/python2.6/site-packages)
from flup.server.fcgi import WSGIServer
from yourapplication import app
class ScriptNameStripper(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
environ[SCRIPT_NAME] =
return self.app(environ, start_response)
app = ScriptNameStripper(app)
if __name__ == __main__:
WSGIServer(app).run()
19.4.3 Conguring lighttpd
A basic FastCGI conguration for lighttpd looks like that:
fastcgi.server = ("/yourapplication.fcgi" =>
((
"socket" => "/tmp/yourapplication-fcgi.sock",
"bin-path" => "/var/www/yourapplication/yourapplication.fcgi",
"check-local" => "disable",
"max-procs" => 1
))
)
alias.url = (
"/static/" => "/path/to/your/static"
)
url.rewrite-once = (
"^(/static($|/.*))$" => "$1",
"^(/.*)$" => "/yourapplication.fcgi$1"
)
Remember to enable the FastCGI, alias and rewrite modules. This conguration binds
166
the application to /yourapplication. If you want the application to work in the URL root
you have to work around a lighttpd bug with the LighttpdCGIRootFix middleware.
Make sure to apply it only if you are mounting the application the URL root. Also,
see the Lighty docs for more information on FastCGI and Python (note that explicitly
passing a socket to run() is no longer necessary).
19.4.4 Conguring nginx
Installing FastCGI applications on nginx is a bit different because by default no
FastCGI parameters are forwarded.
A basic ask FastCGI conguration for nginx looks like this:
location = /yourapplication { rewrite ^ /yourapplication/ last; }
location /yourapplication { try_files $uri @yourapplication; }
location @yourapplication {
include fastcgi_params;
fastcgi_split_path_info ^(/yourapplication)(.*)$;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_pass unix:/tmp/yourapplication-fcgi.sock;
}
This conguration binds the application to /yourapplication. If you want to have it in
the URL root its a bit simpler because you dont have to gure out how to calculate
PATH_INFO and SCRIPT_NAME:
location / { try_files $uri @yourapplication; }
location @yourapplication {
include fastcgi_params;
fastcgi_param PATH_INFO $fastcgi_script_name;
fastcgi_param SCRIPT_NAME "";
fastcgi_pass unix:/tmp/yourapplication-fcgi.sock;
}
19.4.5 Running FastCGI Processes
Since Nginx and others do not load FastCGI apps, you have to do it by yourself. Super-
visor can manage FastCGI processes. You can look around for other FastCGI process
managers or write a script to run your .fcgi le at boot, e.g. using a SysV init.d script.
For a temporary solution, you can always run the .fcgi script inside GNU screen. See
man screen for details, and note that this is a manual solution which does not persist
across system restart:
$ screen
$ /var/www/yourapplication/yourapplication.fcgi
167
19.4.6 Debugging
FastCGI deployments tend to be hard to debug on most webservers. Very often the
only thing the server log tells you is something along the lines of premature end of
headers. In order to debug the application the only thing that can really give you
ideas why it breaks is switching to the correct user and executing the application by
hand.
This example assumes your application is called application.fcgi and that your web-
server user is www-data:
$ su www-data
$ cd /var/www/yourapplication
$ python application.fcgi
Traceback (most recent call last):
File "yourapplication.fcgi", line 4, in <module>
ImportError: No module named yourapplication
In this case the error seems to be yourapplication not being on the python path.
Common problems are:
Relative paths being used. Dont rely on the current working directory
The code depending on environment variables that are not set by the web server.
Different python interpreters being used.
19.5 CGI
If all other deployment methods do not work, CGI will work for sure. CGI is sup-
ported by all major servers but usually has a sub-optimal performance.
This is also the way you can use a Flask application on Googles App Engine, where
execution happens in a CGI-like environment.
Watch Out
Please make sure in advance that any app.run() calls you might have in your applica-
tion le are inside an if __name__ == __main__: block or moved to a separate le.
Just make sure its not called because this will always start a local WSGI server which
we do not want if we deploy that application to CGI / app engine.
With CGI, you will also have to make sure that your code does not contain any print
statements, or that sys.stdout is overridden by something that doesnt write into the
HTTP response.
19.5.1 Creating a .cgi le
First you need to create the CGI application le. Lets call it yourapplication.cgi:
168
#!/usr/bin/python
from wsgiref.handlers import CGIHandler
from yourapplication import app
CGIHandler().run(app)
19.5.2 Server Setup
Usually there are two ways to congure the server. Either just copy the .cgi into a
cgi-bin (and use mod_rewrite or something similar to rewrite the URL) or let the server
point to the le directly.
In Apache for example you can put something like this into the cong:
ScriptAlias /app /path/to/the/application.cgi
On shared webhosting, though, you might not have access to your Apache cong. In
this case, a le called .htaccess, sitting in the public directory you want your app to be
available, works too but the ScriptAlias directive wont work in that case:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f # Dont interfere with static files
RewriteRule ^(.*)$ /path/to/the/application.cgi/$1 [L]
For more information consult the documentation of your webserver.
169
170
CHAPTER
TWENTY
BECOMING BIG
Here are your options when growing your codebase or scaling your application.
20.1 Read the Source.
Flask started in part to demonstrate how to build your own framework on top of ex-
isting well-used tools Werkzeug (WSGI) and Jinja (templating), and as it developed, it
became useful to a wide audience. As you grow your codebase, dont just use Flask
understand it. Read the source. Flasks code is written to be read; its documenta-
tion published so you can use its internal APIs. Flask sticks to documented APIs in
upstream libraries, and documents its internal utilities so that you can nd the hook
points needed for your project.
20.2 Hook. Extend.
The API docs are full of available overrides, hook points, and Signals. You can provide
custom classes for things like the request and response objects. Dig deeper on the
APIs you use, and look for the customizations which are available out of the box in a
Flask release. Look for ways in which your project can be refactored into a collection
of utilities and Flask extensions. Explore the many extensions in the community, and
look for patterns to build your own extensions if you do not nd the tools you need.
20.3 Subclass.
The Flask class has many methods designed for subclassing. You can quickly add or
customize behavior by subclassing Flask (see the linked method docs) and using that
subclass wherever you instantiate an application class. This works well with Applica-
tion Factories.
171
20.4 Wrap with middleware.
The Application Dispatching chapter shows in detail how to apply middleware. You
can introduce WSGI middleware to wrap your Flask instances and introduce xes and
changes at the layer between your Flask application and your HTTP server. Werkzeug
includes several middlewares.
20.5 Fork.
If none of the above options work, fork Flask. The majority of code of Flask is within
Werkzeug and Jinja2. These libraries do the majority of the work. Flask is just the paste
that glues those together. For every project there is the point where the underlying
framework gets in the way (due to assumptions the original developers had). This is
natural because if this would not be the case, the framework would be a very complex
system to begin with which causes a steep learning curve and a lot of user frustration.
This is not unique to Flask. Many people use patched and modied versions of their
framework to counter shortcomings. This idea is also reected in the license of Flask.
You dont have to contribute any changes back if you decide to modify the framework.
The downside of forking is of course that Flask extensions will most likely break be-
cause the new framework has a different import name. Furthermore integrating up-
stream changes can be a complex process, depending on the number of changes. Be-
cause of that, forking should be the very last resort.
20.6 Scale like a pro.
For many web applications the complexity of the code is less an issue than the scaling
for the number of users or data entries expected. Flask by itself is only limited in terms
of scaling by your application code, the data store you want to use and the Python
implementation and webserver you are running on.
Scaling well means for example that if you double the amount of servers you get about
twice the performance. Scaling bad means that if you add a newserver the application
wont perform any better or would not even support a second server.
There is only one limiting factor regarding scaling in Flask which are the context local
proxies. They depend on context which in Flask is dened as being either a thread,
process or greenlet. If your server uses some kind of concurrency that is not based
on threads or greenlets, Flask will no longer be able to support these global proxies.
However the majority of servers are using either threads, greenlets or separate pro-
cesses to achieve concurrency which are all methods well supported by the underlying
Werkzeug library.
172
20.7 Discuss with the community.
The Flask developers keep the framework accessible to users with codebases big and
small. If you nd an obstacle in your way, caused by Flask, dont hesitate to contact
the developers on the mailinglist or IRC channel. The best way for the Flask and Flask
extension developers to improve the tools for larger applications is getting feedback
from users.
173
174
Part II
API REFERENCE
If you are looking for information on a specic function, class or method, this part of
the documentation is for you.
175
176
CHAPTER
TWENTYONE
API
This part of the documentation covers all the interfaces of Flask. For parts where Flask
depends on external libraries, we document the most important right here and provide
links to the canonical documentation.
21.1 Application Object
class flask.Flask(import_name, static_path=None, static_url_path=None,
static_folder=static, template_folder=templates, in-
stance_path=None, instance_relative_cong=False)
The ask object implements a WSGI application and acts as the central object.
It is passed the name of the module or package of the application. Once it is
created it will act as a central registry for the view functions, the URL rules,
template conguration and much more.
The name of the package is used to resolve resources from inside the package
or the folder the module is contained in depending on if the package parameter
resolves to an actual python package (a folder with an __init__.py le inside) or
a standard module (just a .py le).
For more information about resource loading, see open_resource().
Usually you create a Flask instance in your main module or in the __init__.py
le of your package like this:
from flask import Flask
app = Flask(__name__)
About the First Parameter
The idea of the rst parameter is to give Flask an idea what belongs to your
application. This name is used to nd resources on the le system, can be used
by extensions to improve debugging information and a lot more.
So its important what you provide there. If you are using a single module,
__name__ is always the correct value. If you however are using a package, its
usually recommended to hardcode the name of your package there.
177
For example if your application is dened in yourapplication/app.py you should
create it with one of the two versions below:
app = Flask(yourapplication)
app = Flask(__name__.split(.)[0])
Why is that? The application will work even with __name__, thanks to how re-
sources are looked up. However it will make debugging more painful. Certain
extensions can make assumptions based on the import name of your application.
For example the Flask-SQLAlchemy extension will look for the code in your ap-
plication that triggered an SQL query in debug mode. If the import name is not
properly set up, that debugging information is lost. (For example it would only
pick up SQL queries in yourapplication.app and not yourapplication.views.frontend)
New in version 0.7: The static_url_path, static_folder, and template_folder parame-
ters were added.
New in version 0.8: The instance_path and instance_relative_cong parameters
were added.
Parameters
import_name the name of the application package
static_url_path can be used to specify a different path for the
static les on the web. Defaults to the name of the static_folder
folder.
static_folder the folder with static les that should be served
at static_url_path. Defaults to the static folder in the root
path of the application.
template_folder the folder that contains the templates that
should be used by the application. Defaults to templates
folder in the root path of the application.
instance_path An alternative instance path for the applica-
tion. By default the folder instance next to the package or
module is assumed to be the instance path.
instance_relative_cong if set to True relative lenames for
loading the cong are assumed to be relative to the instance
path instead of the application root.
add_template_filter(*args, **kwargs)
Register a custom template lter. Works exactly like the template_filter()
decorator.
Parameters name the optional name of the lter, otherwise the
function name will be used.
add_template_global(*args, **kwargs)
Register a custom template global function. Works exactly like the
template_global() decorator.
178
New in version 0.10.
Parameters name the optional name of the global function, oth-
erwise the function name will be used.
add_template_test(*args, **kwargs)
Register a custom template test. Works exactly like the template_test()
decorator.
New in version 0.10.
Parameters name the optional name of the test, otherwise the
function name will be used.
add_url_rule(*args, **kwargs)
Connects a URL rule. Works exactly like the route() decorator. If a
view_func is provided it will be registered with the endpoint.
Basically this example:
@app.route(/)
def index():
pass
Is equivalent to the following:
def index():
pass
app.add_url_rule(/, index, index)
If the view_func is not provided you will need to connect the endpoint to a
view function like so:
app.view_functions[index] = index
Internally route() invokes add_url_rule() so if you want to customize the
behavior via subclassing you only need to change this method.
For more information refer to URL Route Registrations.
Changed in version 0.2: view_func parameter added.
Changed in version 0.6: OPTIONS is added automatically as method.
Parameters
rule the URL rule as string
endpoint the endpoint for the registered URL rule. Flask
itself assumes the name of the view function as endpoint
view_func the function to call when serving a request to the
provided endpoint
options the options to be forwarded to the underlying Rule
object. A change to Werkzeug is handling of method options.
methods is a list of methods this rule should be limited to
179
(GET, POST etc.). By default a rule just listens for GET (and
implicitly HEAD). Starting with Flask 0.6, OPTIONS is im-
plicitly added and handled by the standard request handling.
after_request(*args, **kwargs)
Register a function to be run after each request.
Your function must take one parameter, an instance of response_class and
return a new response object or the same (see process_response()).
As of Flask 0.7 this function might not be executed at the end of the request
in case an unhandled exception occurred.
after_request_funcs = None
A dictionary with lists of functions that should be called after each request.
The key of the dictionary is the name of the blueprint this function is active
for, None for all requests. This can for example be used to open database
connections or getting hold of the currently logged in user. To register a
function here, use the after_request() decorator.
app_context()
Binds the application only. For as long as the application is bound to the
current context the flask.current_app points to that application. An appli-
cation context is automatically created when a request context is pushed if
necessary.
Example usage:
with app.app_context():
...
New in version 0.9.
app_ctx_globals_class
The class that is used for the g instance.
Example use cases for a custom class:
1.Store arbitrary attributes on ask.g.
2.Add a property for lazy per-request database connectors.
3.Return None instead of AttributeError on expected attributes.
4.Raise exception if an unexpected attr is set, a controlled ask.g.
In Flask 0.9 this property was called request_globals_class but it was changed
in 0.10 to app_ctx_globals_class because the ask.g object is not applica-
tion context scoped.
New in version 0.10.
alias of _AppCtxGlobals
auto_find_instance_path()
Tries to locate the instance path if it was not provided to the constructor of
180
the application class. It will basically calculate the path to a folder named
instance next to your main le or the package.
New in version 0.8.
before_first_request(*args, **kwargs)
Registers a function to be run before the rst request to this instance of the
application.
New in version 0.8.
before_first_request_funcs = None
A lists of functions that should be called at the beginning of the rst request
to this instance. To register a function here, use the before_first_request()
decorator.
New in version 0.8.
before_request(*args, **kwargs)
Registers a function to run before each request.
before_request_funcs = None
A dictionary with lists of functions that should be called at the beginning
of the request. The key of the dictionary is the name of the blueprint this
function is active for, None for all requests. This can for example be used to
open database connections or getting hold of the currently logged in user.
To register a function here, use the before_request() decorator.
blueprints = None
all the attached blueprints in a dictionary by name. Blueprints can be at-
tached multiple times so this dictionary does not tell you how often they
got attached.
New in version 0.7.
config = None
The conguration dictionary as Config. This behaves exactly like a regular
dictionary but supports additional methods to load a cong from les.
config_class
The class that is used for the config attribute of this app. Defaults to Config.
Example use cases for a custom class:
1.Default values for certain cong options.
2.Access to cong values through attributes in addition to keys.
New in version 1.0.
alias of Config
context_processor(*args, **kwargs)
Registers a template context processor function.
create_global_jinja_loader()
Creates the loader for the Jinja2 environment. Can be used to override just
181
the loader and keeping the rest unchanged. Its discouraged to override this
function. Instead one should override the jinja_loader() function instead.
The global loader dispatches between the loaders of the application and the
individual blueprints.
New in version 0.7.
create_jinja_environment()
Creates the Jinja2 environment based on jinja_options and
select_jinja_autoescape(). Since 0.7 this also adds the Jinja2 globals
and lters after initialization. Override this function to customize the
behavior.
New in version 0.5.
create_url_adapter(request)
Creates a URL adapter for the given request. The URL adapter is created at
a point where the request context is not yet set up so the request is passed
explicitly.
New in version 0.6.
Changed in version 0.9: This can nowalso be called without a request object
when the URL adapter is created for the application context.
debug
The debug ag. Set this to True to enable debugging of the application.
In debug mode the debugger will kick in when an unhandled exception
occurs and the integrated server will automatically reload the application if
changes in the code are detected.
This attribute can also be congured from the cong with the DEBUG con-
guration key. Defaults to False.
debug_log_format = \n%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n%(message)s\n
The logging format used for the debug logger. This is only used when the
application is in debug mode, otherwise the attached logging handler does
the formatting.
New in version 0.3.
default_config = ImmutableDict({JSON_AS_ASCII: True, USE_X_SENDFILE: False, SESSION_COOKIE_PATH: None, SESSION_COOKIE_DOMAIN: None, SESSION_COOKIE_NAME: session, DEBUG: False, LOGGER_NAME: None, SESSION_COOKIE_SECURE: False, SECRET_KEY: None, MAX_CONTENT_LENGTH: None, APPLICATION_ROOT: None, SERVER_NAME: None, PREFERRED_URL_SCHEME: http, JSONIFY_PRETTYPRINT_REGULAR: True, TESTING: False, PERMANENT_SESSION_LIFETIME: datetime.timedelta(31), PROPAGATE_EXCEPTIONS: None, TRAP_BAD_REQUEST_ERRORS: False, JSON_SORT_KEYS: True, SESSION_COOKIE_HTTPONLY: True, SEND_FILE_MAX_AGE_DEFAULT: 43200, PRESERVE_CONTEXT_ON_EXCEPTION: None, SESSION_REFRESH_EACH_REQUEST: True, TRAP_HTTP_EXCEPTIONS: False})
Default conguration parameters.
dispatch_request()
Does the request dispatching. Matches the URL and returns the return
value of the view or error handler. This does not have to be a response
object. In order to convert the return value to a proper response object, call
make_response().
Changed in version 0.7: This no longer does the exception handling, this
code was moved to the new full_dispatch_request().
182
do_teardown_appcontext(exc=None)
Called when an application context is popped. This works pretty much the
same as do_teardown_request() but for the application context.
New in version 0.9.
do_teardown_request(exc=None)
Called after the actual request dispatching and will call every as
teardown_request() decorated function. This is not actually called by
the Flask object itself but is always triggered when the request context is
popped. That way we have a tighter control over certain resources under
testing environments.
Changed in version 0.9: Added the exc argument. Previously this was al-
ways using the current exception information.
enable_modules = True
Enable the deprecated module support? This is active by default in 0.7 but
will be changed to False in 0.8. With Flask 1.0 modules will be removed in
favor of Blueprints
endpoint(*args, **kwargs)
A decorator to register a function as an endpoint. Example:
@app.endpoint(example.endpoint)
def example():
return "example"
Parameters endpoint the name of the endpoint
error_handler_spec = None
A dictionary of all registered error handlers. The key is None for error
handlers active on the application, otherwise the key is the name of the
blueprint. Each key points to another dictionary where the key is the status
code of the http exception. The special key None points to a list of tuples
where the rst item is the class for the instance check and the second the
error handler function.
To register a error handler, use the errorhandler() decorator.
errorhandler(*args, **kwargs)
A decorator that is used to register a function give a given error code. Ex-
ample:
@app.errorhandler(404)
def page_not_found(error):
return This page does not exist, 404
You can also register handlers for arbitrary exceptions:
@app.errorhandler(DatabaseError)
def special_exception_handler(error):
return Database connection failed, 500
183
You can also register a function as error handler without using the
errorhandler() decorator. The following example is equivalent to the one
above:
def page_not_found(error):
return This page does not exist, 404
app.error_handler_spec[None][404] = page_not_found
Setting error handlers via assignments to error_handler_spec however is
discouraged as it requires ddling with nested dictionaries and the special
case for arbitrary exception types.
The rst None refers to the active blueprint. If the error handler should be
application wide None shall be used.
New in version 0.7: One can now additionally also register custom excep-
tion types that do not necessarily have to be a subclass of the HTTPException
class.
Parameters code the code as integer for the handler
extensions = None
a place where extensions can store application specic state. For exam-
ple this is where an extension could store database engines and similar
things. For backwards compatibility extensions should register themselves
like this:
if not hasattr(app, extensions):
app.extensions = {}
app.extensions[extensionname] = SomeObject()
The key must match the name of the extension module. For example in case
of a Flask-Foo extension in ask_foo, the key would be foo.
New in version 0.7.
full_dispatch_request()
Dispatches the request and on top of that performs request pre and post-
processing as well as HTTP exception catching and error handling.
New in version 0.7.
get_send_file_max_age(lename)
Provides default cache_timeout for the send_file() functions.
By default, this function returns SEND_FILE_MAX_AGE_DEFAULT from the con-
guration of current_app.
Static le functions such as send_from_directory() use this function,
and send_file() calls this function on current_app when the given
cache_timeout is None. If a cache_timeout is given in send_file(), that
timeout is used; otherwise, this method is called.
This allows subclasses to change the behavior when sending les based on
the lename. For example, to set the cache timeout for .js les to 60 seconds:
184
class MyFlask(flask.Flask):
def get_send_file_max_age(self, name):
if name.lower().endswith(.js):
return 60
return flask.Flask.get_send_file_max_age(self, name)
New in version 0.9.
got_first_request
This attribute is set to True if the application started handling the rst re-
quest.
New in version 0.8.
handle_exception(e)
Default exception handling that kicks in when an exception occurs that is
not caught. In debug mode the exception will be re-raised immediately, oth-
erwise it is logged and the handler for a 500 internal server error is used. If
no such handler exists, a default 500 internal server error message is dis-
played.
New in version 0.3.
handle_http_exception(e)
Handles an HTTP exception. By default this will invoke the registered error
handlers and fall back to returning the exception as response.
New in version 0.3.
handle_url_build_error(error, endpoint, values)
Handle BuildError on url_for().
handle_user_exception(e)
This method is called whenever an exception occurs that should be handled.
A special case are HTTPExceptions which are forwarded by this function to
the handle_http_exception() method. This function will either return a
response value or reraise the exception with the same traceback.
New in version 0.7.
has_static_folder
This is True if the package bound objects container has a folder named
static.
New in version 0.5.
init_jinja_globals()
Deprecated. Used to initialize the Jinja2 globals.
New in version 0.5.
Changed in version 0.7: This method is deprecated with 0.7. Override
create_jinja_environment() instead.
inject_url_defaults(endpoint, values)
Injects the URL defaults for the given endpoint directly into the values dic-
185
tionary passed. This is used internally and automatically called on URL
building.
New in version 0.7.
instance_path = None
Holds the path to the instance folder.
New in version 0.8.
jinja_env
The Jinja2 environment used to load templates.
jinja_loader
The Jinja loader for this package bound object.
New in version 0.5.
jinja_options = ImmutableDict({extensions: [jinja2.ext.autoescape, jinja2.ext.with_]})
Options that are passed directly to the Jinja2 environment.
json_decoder
The JSON decoder class to use. Defaults to JSONDecoder.
New in version 0.10.
alias of JSONDecoder
json_encoder
The JSON encoder class to use. Defaults to JSONEncoder.
New in version 0.10.
alias of JSONEncoder
log_exception(exc_info)
Logs an exception. This is called by handle_exception() if debugging is
disabled and right before the handler is called. The default implementation
logs the exception as error on the logger.
New in version 0.8.
logger
Alogging.Logger object for this application. The default conguration is to
log to stderr if the application is in debug mode. This logger can be used to
(surprise) log messages. Here some examples:
app.logger.debug(A value for debugging)
app.logger.warning(A warning occurred (%d apples), 42)
app.logger.error(An error occurred)
New in version 0.3.
logger_name
The name of the logger to use. By default the logger name is the package
name passed to the constructor.
New in version 0.4.
186
make_config(instance_relative=False)
Used to create the cong attribute by the Flask constructor. The in-
stance_relative parameter is passed in from the constructor of Flask (there
named instance_relative_cong) and indicates if the cong should be relative
to the instance path or the root path of the application.
New in version 0.8.
make_default_options_response()
This method is called to create the default OPTIONS response. This can be
changed through subclassing to change the default behavior of OPTIONS
responses.
New in version 0.7.
make_null_session()
Creates a new instance of a missing session. Instead of overriding this
method we recommend replacing the session_interface.
New in version 0.7.
make_response(rv)
Converts the return value froma viewfunction to a real response object that
is an instance of response_class.
The following types are allowed for rv:
response_class the object is returned unchanged
str a response object is created with the string as body
unicode a response object is created with the string encoded
to utf-8 as body
a WSGI function the function is called as WSGI application and
buffered as response object
tuple A tuple in the form (response, status, headers)
or (response, headers) where response is any of
the types dened here, status is a string or an inte-
ger and headers is a list or a dictionary with header
values.
Parameters rv the return value from the view function
Changed in version 0.9: Previously a tuple was interpreted as the arguments
for the response object.
name
The name of the application. This is usually the import name with the dif-
ference that its guessed from the run le if the import name is main. This
name is used as a display name when Flask needs the name of the applica-
tion. It can be set and overridden to change the value.
New in version 0.8.
187
open_instance_resource(resource, mode=rb)
Opens a resource from the applications instance folder (instance_path).
Otherwise works like open_resource(). Instance resources can also be
opened for writing.
Parameters
resource the name of the resource. To access resources
within subfolders use forward slashes as separator.
mode resource le opening mode, default is rb.
open_resource(resource, mode=rb)
Opens a resource from the applications resource folder. To see how this
works, consider the following folder structure:
/myapplication.py
/schema.sql
/static
/style.css
/templates
/layout.html
/index.html
If you want to open the schema.sql le you would do the following:
with app.open_resource(schema.sql) as f:
contents = f.read()
do_something_with(contents)
Parameters
resource the name of the resource. To access resources
within subfolders use forward slashes as separator.
mode resource le opening mode, default is rb.
open_session(request)
Creates or opens a new session. Default implementation stores all session
data in a signed cookie. This requires that the secret_key is set. Instead of
overriding this method we recommend replacing the session_interface.
Parameters request an instance of request_class.
permanent_session_lifetime
Atimedelta which is used to set the expiration date of a permanent session.
The default is 31 days which makes a permanent session survive for roughly
one month.
This attribute can also be congured from the cong with the
PERMANENT_SESSION_LIFETIME conguration key. Defaults to
timedelta(days=31)
188
preprocess_request()
Called before the actual request dispatching and will call every as
before_request() decorated function. If any of these function returns a
value its handled as if it was the return value from the view and further
request handling is stopped.
This also triggers the url_value_processor() functions before the actual
before_request() functions are called.
preserve_context_on_exception
Returns the value of the PRESERVE_CONTEXT_ON_EXCEPTION congu-
ration value in case its set, otherwise a sensible default is returned.
New in version 0.7.
process_response(response)
Can be overridden in order to modify the response object before its sent to
the WSGI server. By default this will call all the after_request() decorated
functions.
Changed in version 0.5: As of Flask 0.5 the functions registered for after
request execution are called in reverse order of registration.
Parameters response a response_class object.
Returns a new response object or the same, has to be an instance of
response_class.
propagate_exceptions
Returns the value of the PROPAGATE_EXCEPTIONS conguration value
in case its set, otherwise a sensible default is returned.
New in version 0.7.
register_blueprint(*args, **kwargs)
Registers a blueprint on the application.
New in version 0.7.
register_error_handler(code_or_exception, f )
Alternative error attach function to the errorhandler() decorator that is
more straightforward to use for non decorator usage.
New in version 0.7.
register_module(module, **options)
Registers a module with this application. The keyword argument of this
function are the same as the ones for the constructor of the Module class and
will override the values of the module if provided.
Changed in version 0.7: The module system was deprecated in favor for the
blueprint system.
request_class
The class that is used for request objects. See Request for more information.
189
alias of Request
request_context(environ)
Creates a RequestContext from the given environment and binds it to the
current context. This must be used in combination with the with statement
because the request is only bound to the current context for the duration of
the with block.
Example usage:
with app.request_context(environ):
do_something_with(request)
The object returned can also be used without the with statement which is
useful for working in the shell. The example above is doing exactly the
same as this code:
ctx = app.request_context(environ)
ctx.push()
try:
do_something_with(request)
finally:
ctx.pop()
Changed in version 0.3: Added support for non-with statement usage and
with statement is now passed the ctx object.
Parameters environ a WSGI environment
response_class
The class that is used for response objects. See Response for more informa-
tion.
alias of Response
route(rule, **options)
A decorator that is used to register a view function for a given URL rule.
This does the same thing as add_url_rule() but is intended for decorator
usage:
@app.route(/)
def index():
return Hello World
For more information refer to URL Route Registrations.
Parameters
rule the URL rule as string
endpoint the endpoint for the registered URL rule. Flask
itself assumes the name of the view function as endpoint
options the options to be forwarded to the underlying Rule
object. A change to Werkzeug is handling of method options.
methods is a list of methods this rule should be limited to
190
(GET, POST etc.). By default a rule just listens for GET (and
implicitly HEAD). Starting with Flask 0.6, OPTIONS is im-
plicitly added and handled by the standard request handling.
run(host=None, port=None, debug=None, **options)
Runs the application on a local development server. If the debug ag is set
the server will automatically reload for code changes and show a debugger
in case an exception happened.
If you want to run the application in debug mode, but disable the code ex-
ecution on the interactive debugger, you can pass use_evalex=False as pa-
rameter. This will keep the debuggers traceback screen active, but disable
code execution.
Keep in Mind
Flask will suppress any server error with a generic error page unless it
is in debug mode. As such to enable just the interactive debugger with-
out the code reloading, you have to invoke run() with debug=True and
use_reloader=False. Setting use_debugger to True without being in debug
mode wont catch any exceptions because there wont be any to catch.
Changed in version 0.10: The default port is now picked from the
SERVER_NAME variable.
Parameters
host the hostname to listen on. Set this to 0.0.0.0 to
have the server available externally as well. Defaults to
127.0.0.1.
port the port of the webserver. Defaults to 5000 or the port
dened in the SERVER_NAME cong variable if present.
debug if given, enable or disable debug mode. See debug.
options the options to be forwarded to the underlying
Werkzeug server. See werkzeug.serving.run_simple() for
more information.
save_session(session, response)
Saves the session if it needs updates. For the default implementation, check
open_session(). Instead of overriding this method we recommend replac-
ing the session_interface.
Parameters
session the session to be saved (a SecureCookie object)
response an instance of response_class
secret_key
If a secret key is set, cryptographic components can use this to sign cookies
191
and other things. Set this to a complex random value when you want to use
the secure cookie for instance.
This attribute can also be congured from the cong with the SECRET_KEY
conguration key. Defaults to None.
select_jinja_autoescape(lename)
Returns True if autoescaping should be active for the given template name.
New in version 0.5.
send_static_file(lename)
Function used internally to send static les from the static folder to the
browser.
New in version 0.5.
session_cookie_name
The secure cookie uses this for the name of the session cookie.
This attribute can also be congured from the cong with the SES-
SION_COOKIE_NAME conguration key. Defaults to session
session_interface = <ask.sessions.SecureCookieSessionInterface object at 0x10daed0d0>
the session interface to use. By default an instance of
SecureCookieSessionInterface is used here.
New in version 0.8.
should_ignore_error(error)
This is called to gure out if an error should be ignored or not as far as
the teardown system is concerned. If this function returns True then the
teardown handlers will not be passed the error.
New in version 0.10.
teardown_appcontext(*args, **kwargs)
Registers a function to be called when the application context ends. These
functions are typically also called when the request context is popped.
Example:
ctx = app.app_context()
ctx.push()
...
ctx.pop()
When ctx.pop() is executed in the above example, the teardown functions
are called just before the app context moves from the stack of active con-
texts. This becomes relevant if you are using such constructs in tests.
Since a request context typically also manages an application context it
would also be called when you pop a request context.
When a teardown function was called because of an exception it will be
passed an error object.
192
New in version 0.9.
teardown_appcontext_funcs = None
A list of functions that are called when the application context is destroyed.
Since the application context is also torn down if the request ends this is the
place to store code that disconnects from databases.
New in version 0.9.
teardown_request(*args, **kwargs)
Register a function to be run at the end of each request, regardless of
whether there was an exception or not. These functions are executed when
the request context is popped, even if not an actual request was performed.
Example:
ctx = app.test_request_context()
ctx.push()
...
ctx.pop()
When ctx.pop() is executed in the above example, the teardown functions
are called just before the request context moves from the stack of active con-
texts. This becomes relevant if you are using such constructs in tests.
Generally teardown functions must take every necessary step to avoid that
they will fail. If they do execute code that might fail they will have to sur-
round the execution of these code by try/except statements and log occur-
ring errors.
When a teardown function was called because of a exception it will be
passed an error object.
Debug Note
In debug mode Flask will not tear down a request on an exception
immediately. Instead if will keep it alive so that the interactive de-
bugger can still access it. This behavior can be controlled by the
PRESERVE_CONTEXT_ON_EXCEPTION conguration variable.
teardown_request_funcs = None
A dictionary with lists of functions that are called after each request, even
if an exception has occurred. The key of the dictionary is the name of
the blueprint this function is active for, None for all requests. These func-
tions are not allowed to modify the request, and their return values are ig-
nored. If an exception occurred while processing the request, it gets passed
to each teardown_request function. To register a function here, use the
teardown_request() decorator.
New in version 0.7.
template_context_processors = None
A dictionary with list of functions that are called without argument to pop-
193
ulate the template context. The key of the dictionary is the name of the
blueprint this function is active for, None for all requests. Each returns a
dictionary that the template context is updated with. To register a function
here, use the context_processor() decorator.
template_filter(*args, **kwargs)
A decorator that is used to register custom template lter. You can specify a
name for the lter, otherwise the function name will be used. Example:
@app.template_filter()
def reverse(s):
return s[::-1]
Parameters name the optional name of the lter, otherwise the
function name will be used.
template_global(*args, **kwargs)
A decorator that is used to register a custom template global function. You
can specify a name for the global function, otherwise the function name will
be used. Example:
@app.template_global()
def double(n):
return 2 * n
New in version 0.10.
Parameters name the optional name of the global function, oth-
erwise the function name will be used.
template_test(*args, **kwargs)
A decorator that is used to register custom template test. You can specify a
name for the test, otherwise the function name will be used. Example:
@app.template_test()
def is_prime(n):
if n == 2:
return True
for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
if n % i == 0:
return False
return True
New in version 0.10.
Parameters name the optional name of the test, otherwise the
function name will be used.
test_client(use_cookies=True)
Creates a test client for this application. For information about unit testing
head over to Testing Flask Applications.
Note that if you are testing for assertions or exceptions in your application
194
code, you must set app.testing = True in order for the exceptions to prop-
agate to the test client. Otherwise, the exception will be handled by the
application (not visible to the test client) and the only indication of an As-
sertionError or other exception will be a 500 status code response to the test
client. See the testing attribute. For example:
app.testing = True
client = app.test_client()
The test client can be used in a with block to defer the closing down of the
context until the end of the with block. This is useful if you want to access
the context locals for testing:
with app.test_client() as c:
rv = c.get(/?vodka=42)
assert request.args[vodka] == 42
See FlaskClient for more information.
Changed in version 0.4: added support for with block usage for the client.
New in version 0.7: The use_cookies parameter was added as well as the
ability to override the client to be used by setting the test_client_class
attribute.
test_client_class = None
the test client that is used with when test_client is used.
New in version 0.7.
test_request_context(*args, **kwargs)
Creates a WSGI environment from the given values (see
werkzeug.test.EnvironBuilder for more information, this function ac-
cepts the same arguments).
testing
The testing ag. Set this to True to enable the test mode of Flask extensions
(and in the future probably also Flask itself). For example this might activate
unittest helpers that have an additional runtime cost which should not be
enabled by default.
If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the
default its implicitly enabled.
This attribute can also be congured fromthe cong with the TESTINGcon-
guration key. Defaults to False.
trap_http_exception(e)
Checks if an HTTP exception should be trapped or not. By default
this will return False for all exceptions except for a bad request key er-
ror if TRAP_BAD_REQUEST_ERRORS is set to True. It also returns True if
TRAP_HTTP_EXCEPTIONS is set to True.
This is called for all HTTP exceptions raised by a view function. If it returns
True for any exception the error handler for this exception is not called and
195
it shows up as regular exception in the traceback. This is helpful for debug-
ging implicitly raised HTTP exceptions.
New in version 0.8.
update_template_context(context)
Update the template context with some commonly used variables. This in-
jects request, session, cong and g into the template context as well as every-
thing template context processors want to inject. Note that the as of Flask
0.6, the original values in the context will not be overridden if a context
processor decides to return a value with the same key.
Parameters context the context as a dictionary that is updated in
place to add extra variables.
url_build_error_handlers = None
A list of functions that are called when url_for() raises a BuildError. Each
function registered here is called with error, endpoint and values. If a function
returns None or raises a BuildError the next function is tried.
New in version 0.9.
url_default_functions = None
A dictionary with lists of functions that can be used as URL value prepro-
cessors. The key None here is used for application wide callbacks, otherwise
the key is the name of the blueprint. Each of these functions has the chance
to modify the dictionary of URL values before they are used as the key-
word arguments of the view function. For each function registered this one
should also provide a url_defaults() function that adds the parameters
automatically again that were removed that way.
New in version 0.7.
url_defaults(*args, **kwargs)
Callback function for URL defaults for all view functions of the applica-
tion. Its called with the endpoint and values and should update the values
passed in place.
url_map = None
The Map for this instance. You can use this to change the routing converters
after the class was created but before any routes are connected. Example:
from werkzeug.routing import BaseConverter
class ListConverter(BaseConverter):
def to_python(self, value):
return value.split(,)
def to_url(self, values):
return ,.join(BaseConverter.to_url(value)
for value in values)
app = Flask(__name__)
app.url_map.converters[list] = ListConverter
196
url_rule_class
The rule object to use for URL rules created. This is used by add_url_rule().
Defaults to werkzeug.routing.Rule.
New in version 0.7.
alias of Rule
url_value_preprocessor(*args, **kwargs)
Registers a function as URL value preprocessor for all view functions of the
application. Its called before the view functions are called and can modify
the url values provided.
url_value_preprocessors = None
A dictionary with lists of functions that can be used as URL value processor
functions. Whenever a URL is built these functions are called to modify
the dictionary of values in place. The key None here is used for application
wide callbacks, otherwise the key is the name of the blueprint. Each of these
functions has the chance to modify the dictionary
New in version 0.7.
use_x_sendfile
Enable this if you want to use the X-Sendle feature. Keep in mind that the
server has to support this. This only affects les sent with the send_file()
method.
New in version 0.2.
This attribute can also be congured from the cong with the
USE_X_SENDFILE conguration key. Defaults to False.
view_functions = None
A dictionary of all view functions registered. The keys will be function
names which are also used to generate URLs and the values are the function
objects themselves. To register a view function, use the route() decorator.
wsgi_app(environ, start_response)
The actual WSGI application. This is not implemented in __call__ so that
middlewares can be applied without losing a reference to the class. So in-
stead of doing this:
app = MyMiddleware(app)
Its a better idea to do this instead:
app.wsgi_app = MyMiddleware(app.wsgi_app)
Then you still have the original application object around and can continue
to call methods on it.
Changed in version 0.7: The behavior of the before and after request call-
backs was changed under error conditions and a new callback was added
that will always execute at the end of the request, independent on if an error
occurred or not. See Callbacks and Errors.
197
Parameters
environ a WSGI environment
start_response a callable accepting a status code, a list of
headers and an optional exception context to start the re-
sponse
21.2 Blueprint Objects
class flask.Blueprint(name, import_name, static_folder=None,
static_url_path=None, template_folder=None,
url_prex=None, subdomain=None, url_defaults=None)
Represents a blueprint. A blueprint is an object that records functions that will
be called with the BlueprintSetupState later to register functions or other things
on the main application. See Modular Applications with Blueprints for more infor-
mation.
New in version 0.7.
add_app_template_filter(f, name=None)
Register a custom template lter, available application wide. Like
Flask.add_template_filter() but for a blueprint. Works exactly like the
app_template_filter() decorator.
Parameters name the optional name of the lter, otherwise the
function name will be used.
add_app_template_global(f, name=None)
Register a custom template global, available application wide. Like
Flask.add_template_global() but for a blueprint. Works exactly like the
app_template_global() decorator.
New in version 0.10.
Parameters name the optional name of the global, otherwise the
function name will be used.
add_app_template_test(f, name=None)
Register a custom template test, available application wide. Like
Flask.add_template_test() but for a blueprint. Works exactly like the
app_template_test() decorator.
New in version 0.10.
Parameters name the optional name of the test, otherwise the
function name will be used.
add_url_rule(rule, endpoint=None, view_func=None, **options)
Like Flask.add_url_rule() but for a blueprint. The endpoint for the
url_for() function is prexed with the name of the blueprint.
198
after_app_request(f )
Like Flask.after_request() but for a blueprint. Such a function is executed
after each request, even if outside of the blueprint.
after_request(f )
Like Flask.after_request() but for a blueprint. This function is only exe-
cuted after each request that is handled by a function of that blueprint.
app_context_processor(f )
Like Flask.context_processor() but for a blueprint. Such a function is ex-
ecuted each request, even if outside of the blueprint.
app_errorhandler(code)
Like Flask.errorhandler() but for a blueprint. This handler is used for all
requests, even if outside of the blueprint.
app_template_filter(name=None)
Register a custom template lter, available application wide. Like
Flask.template_filter() but for a blueprint.
Parameters name the optional name of the lter, otherwise the
function name will be used.
app_template_global(name=None)
Register a custom template global, available application wide. Like
Flask.template_global() but for a blueprint.
New in version 0.10.
Parameters name the optional name of the global, otherwise the
function name will be used.
app_template_test(name=None)
Register a custom template test, available application wide. Like
Flask.template_test() but for a blueprint.
New in version 0.10.
Parameters name the optional name of the test, otherwise the
function name will be used.
app_url_defaults(f )
Same as url_defaults() but application wide.
app_url_value_preprocessor(f )
Same as url_value_preprocessor() but application wide.
before_app_first_request(f )
Like Flask.before_first_request(). Such a function is executed before the
rst request to the application.
before_app_request(f )
Like Flask.before_request(). Such a function is executed before each re-
quest, even if outside of a blueprint.
199
before_request(f )
Like Flask.before_request() but for a blueprint. This function is only exe-
cuted before each request that is handled by a function of that blueprint.
context_processor(f )
Like Flask.context_processor() but for a blueprint. This function is only
executed for requests handled by a blueprint.
endpoint(endpoint)
Like Flask.endpoint() but for a blueprint. This does not prex the end-
point with the blueprint name, this has to be done explicitly by the user of
this method. If the endpoint is prexed with a . it will be registered to the
current blueprint, otherwise its an application independent endpoint.
errorhandler(code_or_exception)
Registers an error handler that becomes active for this blueprint only. Please
be aware that routing does not happen local to a blueprint so an error han-
dler for 404 usually is not handled by a blueprint unless it is caused inside
a view function. Another special case is the 500 internal server error which
is always looked up from the application.
Otherwise works as the errorhandler() decorator of the Flask object.
get_send_file_max_age(lename)
Provides default cache_timeout for the send_file() functions.
By default, this function returns SEND_FILE_MAX_AGE_DEFAULT from the con-
guration of current_app.
Static le functions such as send_from_directory() use this function,
and send_file() calls this function on current_app when the given
cache_timeout is None. If a cache_timeout is given in send_file(), that
timeout is used; otherwise, this method is called.
This allows subclasses to change the behavior when sending les based on
the lename. For example, to set the cache timeout for .js les to 60 seconds:
class MyFlask(flask.Flask):
def get_send_file_max_age(self, name):
if name.lower().endswith(.js):
return 60
return flask.Flask.get_send_file_max_age(self, name)
New in version 0.9.
has_static_folder
This is True if the package bound objects container has a folder named
static.
New in version 0.5.
jinja_loader
The Jinja loader for this package bound object.
New in version 0.5.
200
make_setup_state(app, options, rst_registration=False)
Creates an instance of BlueprintSetupState() object that is later passed to
the register callback functions. Subclasses can override this to return a sub-
class of the setup state.
open_resource(resource, mode=rb)
Opens a resource from the applications resource folder. To see how this
works, consider the following folder structure:
/myapplication.py
/schema.sql
/static
/style.css
/templates
/layout.html
/index.html
If you want to open the schema.sql le you would do the following:
with app.open_resource(schema.sql) as f:
contents = f.read()
do_something_with(contents)
Parameters
resource the name of the resource. To access resources
within subfolders use forward slashes as separator.
mode resource le opening mode, default is rb.
record(func)
Registers a function that is called when the blueprint is registered on the
application. This function is called with the state as argument as returned
by the make_setup_state() method.
record_once(func)
Works like record() but wraps the function in another function that will
ensure the function is only called once. If the blueprint is registered a second
time on the application, the function passed is not called.
register(app, options, rst_registration=False)
Called by Flask.register_blueprint() to register a blueprint on the ap-
plication. This can be overridden to customize the register behavior. Key-
word arguments from register_blueprint() are directly forwarded to this
method in the options dictionary.
route(rule, **options)
Like Flask.route() but for a blueprint. The endpoint for the url_for()
function is prexed with the name of the blueprint.
send_static_file(lename)
Function used internally to send static les from the static folder to the
browser.
201
New in version 0.5.
teardown_app_request(f )
Like Flask.teardown_request() but for a blueprint. Such a function is exe-
cuted when tearing down each request, even if outside of the blueprint.
teardown_request(f )
Like Flask.teardown_request() but for a blueprint. This function is
only executed when tearing down requests handled by a function of that
blueprint. Teardown request functions are executed when the request con-
text is popped, even when no actual request was performed.
url_defaults(f )
Callback function for URL defaults for this blueprint. Its called with the
endpoint and values and should update the values passed in place.
url_value_preprocessor(f )
Registers a function as URL value preprocessor for this blueprint. Its called
before the viewfunctions are called and can modify the url values provided.
21.3 Incoming Request Data
class flask.Request(environ, populate_request=True, shallow=False)
The request object used by default in Flask. Remembers the matched endpoint
and view arguments.
It is what ends up as request. If you want to replace the request object used you
can subclass this and set request_class to your subclass.
The request object is a Request subclass and provides all of the attributes
Werkzeug denes plus a few Flask specic ones.
form
A MultiDict with the parsed form data from POST or PUT requests. Please
keep in mind that le uploads will not end up here, but instead in the files
attribute.
args
A MultiDict with the parsed contents of the query string. (The part in the
URL after the question mark).
values
A CombinedMultiDict with the contents of both form and args.
cookies
A dict with the contents of all cookies transmitted with the request.
stream
If the incoming form data was not encoded with a known mimetype the
data is stored unmodied in this stream for consumption. Most of the time
it is a better idea to use data which will give you that data as a string. The
stream only returns the data once.
202
headers
The incoming request headers as a dictionary like object.
data
Contains the incoming request data as string in case it came with a mime-
type Flask does not handle.
files
A MultiDict with les uploaded as part of a POST or PUT request. Each
le is stored as FileStorage object. It basically behaves like a standard le
object you know from Python, with the difference that it also has a save()
function that can store the le on the lesystem.
environ
The underlying WSGI environment.
method
The current request method (POST, GET etc.)
path
script_root
url
base_url
url_root
Provides different ways to look at the current URL. Imagine your applica-
tion is listening on the following URL:
http://www.example.com/myapplication
And a user requests the following URL:
http://www.example.com/myapplication/page.html?x=y
In this case the values of the above mentioned attributes would be the fol-
lowing:
path /page.html
script_root /myapplication
base_url http://www.example.com/myapplication/page.html
url http://www.example.com/myapplication/page.html?x=y
url_root http://www.example.com/myapplication/
is_xhr
True if the request was triggered via a JavaScript XMLHttpRequest. This only
works with libraries that support the X-Requested-With header and set it to
XMLHttpRequest. Libraries that do that are prototype, jQuery and Mochikit
and probably some more.
blueprint
The name of the current blueprint
203
endpoint
The endpoint that matched the request. This in combination with view_args
can be used to reconstruct the same or a modied URL. If an exception
happened when matching, this will be None.
get_json(force=False, silent=False, cache=True)
Parses the incoming JSON request data and returns it. If parsing fails the
on_json_loading_failed() method on the request object will be invoked.
By default this function will only load the json data if the mimetype is
application/json but this can be overriden by the force parameter.
Parameters
force if set to True the mimetype is ignored.
silent if set to True this method will fail silently and return
None.
cache if set to True the parsed JSON data is remembered on
the request.
is_json
Indicates if this request is JSON or not. By default a request is con-
sidered to include JSON data if the mimetype is application/json or
application/*+json.
New in version 0.11.
json
If the mimetype is application/json this will contain the parsed JSON data.
Otherwise this will be None.
The get_json() method should be used instead.
max_content_length
Read-only view of the MAX_CONTENT_LENGTH cong key.
module
The name of the current module if the request was dispatched to an actual
module. This is deprecated functionality, use blueprints instead.
on_json_loading_failed(e)
Called if decoding of the JSON data failed. The return value of this method
is used by get_json() when an error occurred. The default implementation
just raises a BadRequest exception.
Changed in version 0.10: Removed buggy previous behavior of generating
a random JSON response. If you want that behavior back you can trivially
add it by subclassing.
New in version 0.8.
routing_exception = None
if matching the URL failed, this is the exception that will be raised / was
204
raised as part of the request handling. This is usually a NotFound exception
or something similar.
url_rule = None
the internal URL rule that matched the request. This can be useful to in-
spect which methods are allowed for the URL from a before/after handler
(request.url_rule.methods) etc.
New in version 0.6.
view_args = None
a dict of view arguments that matched the request. If an exception hap-
pened when matching, this will be None.
class flask.request
To access incoming request data, you can use the global request object. Flask
parses incoming request data for you and gives you access to it through that
global object. Internally Flask makes sure that you always get the correct data
for the active thread if you are in a multithreaded environment.
This is a proxy. See Notes On Proxies for more information.
The request object is an instance of a Request subclass and provides all of the
attributes Werkzeug denes. This just shows a quick overview of the most im-
portant ones.
21.4 Response Objects
class flask.Response(response=None, status=None, headers=None, mime-
type=None, content_type=None, direct_passthrough=False)
The response object that is used by default in Flask. Works like the response
object from Werkzeug but is set to have an HTML mimetype by default. Quite
often you dont have to create this object yourself because make_response() will
take care of that for you.
If you want to replace the response object used you can subclass this and set
response_class to your subclass.
headers
A Headers object representing the response headers.
status
A string with a response status.
status_code
The response status as integer.
data
A descriptor that calls get_data() and set_data(). This should not be used
and will eventually get deprecated.
205
mimetype
The mimetype (content type without charset etc.)
set_cookie(key, value=, max_age=None, expires=None, path=/, do-
main=None, secure=None, httponly=False)
Sets a cookie. The parameters are the same as in the cookie Morsel object in
the Python standard library but it accepts unicode data, too.
Parameters
key the key (name) of the cookie to be set.
value the value of the cookie.
max_age should be a number of seconds, or None (default)
if the cookie should last only as long as the clients browser
session.
expires should be a datetime object or UNIX timestamp.
domain if you want to set a cross-domain cookie. For exam-
ple, domain=".example.com" will set a cookie that is readable
by the domain www.example.com, foo.example.com etc. Oth-
erwise, a cookie will only be readable by the domain that set
it.
path limits the cookie to a given path, per default it will
span the whole domain.
21.5 Sessions
If you have the Flask.secret_key set you can use sessions in Flask applications. A
session basically makes it possible to remember information from one request to an-
other. The way Flask does this is by using a signed cookie. So the user can look at the
session contents, but not modify it unless they know the secret key, so make sure to
set that to something complex and unguessable.
To access the current session you can use the session object:
class flask.session
The session object works pretty much like an ordinary dict, with the difference
that it keeps track on modications.
This is a proxy. See Notes On Proxies for more information.
The following attributes are interesting:
new
True if the session is new, False otherwise.
modified
True if the session object detected a modication. Be advised that modica-
206
tions on mutable structures are not picked up automatically, in that situation
you have to explicitly set the attribute to True yourself. Here an example:
# this change is not picked up because a mutable object (here
# a list) is changed.
session[objects].append(42)
# so mark it as modified yourself
session.modified = True
permanent
If set to True the session lives for permanent_session_lifetime seconds. The
default is 31 days. If set to False (which is the default) the session will be
deleted when the user closes the browser.
21.6 Session Interface
New in version 0.8.
The session interface provides a simple way to replace the session implementation that
Flask is using.
class flask.sessions.SessionInterface
The basic interface you have to implement in order to replace the default session
interface which uses werkzeugs securecookie implementation. The only meth-
ods you have to implement are open_session() and save_session(), the others
have useful defaults which you dont need to change.
The session object returned by the open_session() method has to provide a dic-
tionary like interface plus the properties and methods from the SessionMixin.
We recommend just subclassing a dict and adding that mixin:
class Session(dict, SessionMixin):
pass
If open_session() returns None Flask will call into make_null_session() to create
a session that acts as replacement if the session support cannot work because
some requirement is not fullled. The default NullSession class that is created
will complain that the secret key was not set.
To replace the session interface on an application all you have to do is to assign
flask.Flask.session_interface:
app = Flask(__name__)
app.session_interface = MySessionInterface()
New in version 0.8.
get_cookie_domain(app)
Helpful helper method that returns the cookie domain that should be used
for the session cookie if session cookies are used.
207
get_cookie_httponly(app)
Returns True if the session cookie should be httponly. This currently just
returns the value of the SESSION_COOKIE_HTTPONLY cong var.
get_cookie_path(app)
Returns the path for which the cookie should be valid. The default imple-
mentation uses the value from the SESSION_COOKIE_PATH cong var if
its set, and falls back to APPLICATION_ROOT or uses / if its None.
get_cookie_secure(app)
Returns True if the cookie should be secure. This currently just returns the
value of the SESSION_COOKIE_SECURE setting.
get_expiration_time(app, session)
A helper method that returns an expiration date for the session or None
if the session is linked to the browser session. The default implementation
returns now+ the permanent session lifetime congured on the application.
is_null_session(obj)
Checks if a given object is a null session. Null sessions are not asked to be
saved.
This checks if the object is an instance of null_session_class by default.
make_null_session(app)
Creates a null session which acts as a replacement object if the real session
support could not be loaded due to a conguration error. This mainly aids
the user experience because the job of the null session is to still support
lookup without complaining but modications are answered with a helpful
error message of what failed.
This creates an instance of null_session_class by default.
null_session_class
make_null_session() will look here for the class that should be created
when a null session is requested. Likewise the is_null_session() method
will perform a typecheck against this type.
alias of NullSession
open_session(app, request)
This method has to be implemented and must either return None in case
the loading failed because of a conguration error or an instance of a ses-
sion object which implements a dictionary like interface + the methods and
attributes on SessionMixin.
pickle_based = False
A ag that indicates if the session interface is pickle based. This can be used
by ask extensions to make a decision in regards to how to deal with the
session object.
New in version 0.10.
save_session(app, session, response)
208
This is called for actual sessions returned by open_session() at the end of
the request. This is still called during a request context so if you absolutely
need access to the request you can do that.
should_set_cookie(app, session)
Indicates weather a cookie should be set now or not. This is used by session
backends to gure out if they should emit a set-cookie header or not. The
default behavior is controlled by the SESSION_REFRESH_EACH_REQUEST cong
variable. If its set to False then a cookie is only set if the session is modied,
if set to True its always set if the session is permanent.
This check is usually skipped if sessions get deleted.
New in version 1.0.
class flask.sessions.SecureCookieSessionInterface
The default session interface that stores sessions in signed cookies through the
itsdangerous module.
digest_method()
the hash function to use for the signature. The default is sha1
key_derivation = hmac
the name of the itsdangerous supported key derivation. The default is
hmac.
salt = cookie-session
the salt that should be applied on top of the secret key for the signing of
cookie based sessions.
serializer = <ask.sessions.TaggedJSONSerializer object at 0x10daf0710>
A python serializer for the payload. The default is a compact JSON derived
serializer with support for some extra Python types such as datetime objects
or tuples.
session_class
alias of SecureCookieSession
class flask.sessions.SecureCookieSession(initial=None)
Baseclass for sessions based on signed cookies.
class flask.sessions.NullSession(initial=None)
Class used to generate nicer error messages if sessions are not available. Will still
allow read-only access to the empty session but fail on setting.
class flask.sessions.SessionMixin
Expands a basic dictionary with an accessors that are expected by Flask exten-
sions and users for the session.
modified = True
for some backends this will always be True, but some backends will default
this to false and detect changes in the dictionary for as long as changes do
not happen on mutable structures in the session. The default mixin imple-
mentation just hardcodes True in.
209
new = False
some session backends can tell you if a session is new, but that is not nec-
essarily guaranteed. Use with caution. The default mixin implementation
just hardcodes False in.
permanent
this reects the _permanent key in the dict.
flask.sessions.session_json_serializer = <ask.sessions.TaggedJSONSerializer object at 0x10daf0710>
A customized JSON serializer that supports a few extra types that we take for
granted when serializing (tuples, markup objects, datetime).
This object provides dumping and loading methods similar to simplejson but it
also tags certain builtin Python objects that commonly appear in sessions. Cur-
rently the following extended values are supported in the JSON it dumps:
Markup objects
UUID objects
datetime objects
tuples
Notice
The PERMANENT_SESSION_LIFETIME cong key can also be an integer starting with Flask
0.8. Either catch this down yourself or use the permanent_session_lifetime attribute
on the app which converts the result to an integer automatically.
21.7 Test Client
class flask.testing.FlaskClient(application, response_wrapper=None,
use_cookies=True, al-
low_subdomain_redirects=False)
Works like a regular Werkzeug test client but has some knowledge about how
Flask works to defer the cleanup of the request context stack to the end of a with
body when used in a with statement. For general information about how to use
this class refer to werkzeug.test.Client.
Basic usage is outlined in the Testing Flask Applications chapter.
session_transaction(*args, **kwds)
When used in combination with a with statement this opens a session trans-
action. This can be used to modify the session that the test client uses. Once
the with block is left the session is stored back.
with client.session_transaction() as session: session[value] = 42
Internally this is implemented by going through a temporary test request
context and since session handling could depend on request variables this
210
function accepts the same arguments as test_request_context() which are
directly passed through.
21.8 Application Globals
To share data that is valid for one request only from one function to another, a global
variable is not good enough because it would break in threaded environments. Flask
provides you with a special object that ensures it is only valid for the active request
and that will return different values for each request. In a nutshell: it does the right
thing, like it does for request and session.
flask.g
Just store on this whatever you want. For example a database connection or the
user that is currently logged in.
Starting with Flask 0.10 this is stored on the application context and no longer
on the request context which means it becomes available if only the application
context is bound and not yet a request. This is especially useful when combined
with the Faking Resources and Context pattern for testing.
Additionally as of 0.10 you can use the get() method to get an attribute or None
(or the second argument) if its not set. These two usages are now equivalent:
user = getattr(flask.g, user, None)
user = flask.g.get(user, None)
Its now also possible to use the in operator on it to see if an attribute is dened
and it yields all keys on iteration.
This is a proxy. See Notes On Proxies for more information.
21.9 Useful Functions and Classes
flask.current_app
Points to the application handling the request. This is useful for extensions that
want to support multiple applications running side by side. This is powered by
the application context and not by the request context, so you can change the
value of this proxy by using the app_context() method.
This is a proxy. See Notes On Proxies for more information.
flask.has_request_context()
If you have code that wants to test if a request context is there or not this function
can be used. For instance, you may want to take advantage of request informa-
tion if the request object is available, but fail silently if it is unavailable.
class User(db.Model):
def __init__(self, username, remote_addr=None):
211
self.username = username
if remote_addr is None and has_request_context():
remote_addr = request.remote_addr
self.remote_addr = remote_addr
Alternatively you can also just test any of the context bound objects (such as
request or g for truthness):
class User(db.Model):
def __init__(self, username, remote_addr=None):
self.username = username
if remote_addr is None and request:
remote_addr = request.remote_addr
self.remote_addr = remote_addr
New in version 0.7.
flask.copy_current_request_context(f )
A helper function that decorates a function to retain the current request context.
This is useful when working with greenlets. The moment the function is deco-
rated a copy of the request context is created and then pushed when the function
is called.
Example:
import gevent
from flask import copy_current_request_context
@app.route(/)
def index():
@copy_current_request_context
def do_some_work():
# do some work here, it can access flask.request like you
# would otherwise in the view function.
...
gevent.spawn(do_some_work)
return Regular response
New in version 0.10.
flask.has_app_context()
Works like has_request_context() but for the application context. You can also
just do a boolean check on the current_app object instead.
New in version 0.9.
flask.url_for(endpoint, **values)
Generates a URL to the given endpoint with the method provided.
Variable arguments that are unknown to the target endpoint are appended to the
generated URL as query arguments. If the value of a query argument is None, the
whole pair is skipped. In case blueprints are active you can shortcut references
to the same blueprint by prexing the local endpoint with a dot (.).
212
This will reference the index function local to the current blueprint:
url_for(.index)
For more information, head over to the Quickstart.
To integrate applications, Flask has a hook to intercept URL build errors through
Flask.build_error_handler. The url_for function results in a BuildError when
the current app does not have a URL for the given endpoint and values. When it
does, the current_app calls its build_error_handler if it is not None, which can
return a string to use as the result of url_for (instead of url_fors default to raise
the BuildError exception) or re-raise the exception. An example:
def external_url_handler(error, endpoint, **values):
"Looks up an external URL when url_for cannot build a URL."
# This is an example of hooking the build_error_handler.
# Here, lookup_url is some utility function youve built
# which looks up the endpoint in some external URL registry.
url = lookup_url(endpoint, **values)
if url is None:
# External lookup did not have a URL.
# Re-raise the BuildError, in context of original traceback.
exc_type, exc_value, tb = sys.exc_info()
if exc_value is error:
raise exc_type, exc_value, tb
else:
raise error
# url_for will use this result, instead of raising BuildError.
return url
app.build_error_handler = external_url_handler
Here, error is the instance of BuildError, and endpoint and **values are the argu-
ments passed into url_for. Note that this is for building URLs outside the current
application, and not for handling 404 NotFound errors.
New in version 0.10: The _scheme parameter was added.
New in version 0.9: The _anchor and _method parameters were added.
New in version 0.9: Calls Flask.handle_build_error() on BuildError.
Parameters
endpoint the endpoint of the URL (name of the function)
values the variable arguments of the URL rule
_external if set to True, an absolute URL is generated. Server
address can be changed via SERVER_NAME conguration
variable which defaults to localhost.
_scheme a string specifying the desired URL scheme. The
_external parameter must be set to True or a ValueError is raised.
213
_anchor if provided this is added as anchor to the URL.
_method if provided this explicitly species an HTTP
method.
flask.abort(code)
Raises an HTTPException for the given status code. For example to abort request
handling with a page not found exception, you would call abort(404).
Parameters code the HTTP error code.
flask.redirect(location, code=302)
Return a response object (a WSGI application) that, if called, redirects the client
to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not
supported because its not a real redirect and 304 because its the answer for a
request with a request with dened If-Modied-Since headers.
New in version 0.6: The location can now be a unicode string that is encoded
using the iri_to_uri() function.
Parameters
location the location the response should redirect to.
code the redirect status code. defaults to 302.
flask.make_response(*args)
Sometimes it is necessary to set additional headers in a view. Because views
do not have to return response objects but can return a value that is converted
into a response object by Flask itself, it becomes tricky to add headers to it. This
function can be called instead of using a return and you will get a response object
which you can use to attach headers.
If view looked like this and you want to add a new header:
def index():
return render_template(index.html, foo=42)
You can now do something like this:
def index():
response = make_response(render_template(index.html, foo=42))
response.headers[X-Parachutes] = parachutes are cool
return response
This function accepts the very same arguments you can return from a view func-
tion. This for example creates a response with a 404 error code:
response = make_response(render_template(not_found.html), 404)
The other use case of this function is to force the return value of a view function
into a response which is helpful with view decorators:
response = make_response(view_function())
response.headers[X-Parachutes] = parachutes are cool
214
Internally this function does the following things:
if no arguments are passed, it creates a new response argument
if one argument is passed, flask.Flask.make_response() is invoked with
it.
if more than one argument is passed, the arguments are passed to the
flask.Flask.make_response() function as tuple.
New in version 0.6.
flask.after_this_request(f )
Executes a function after this request. This is useful to modify response objects.
The function is passed the response object and has to return the same or a new
one.
Example:
@app.route(/)
def index():
@after_this_request
def add_header(response):
response.headers[X-Foo] = Parachute
return response
return Hello World!
This is more useful if a function other than the view function wants to modify
a response. For instance think of a decorator that wants to add some headers
without converting the return value into a response object.
New in version 0.9.
flask.send_file(lename_or_fp, mimetype=None, as_attachment=False, attach-
ment_lename=None, add_etags=True, cache_timeout=None, con-
ditional=False)
Sends the contents of a le to the client. This will use the most efcient
method available and congured. By default it will try to use the WSGI
servers le_wrapper support. Alternatively you can set the applications
use_x_sendfile attribute to True to directly emit an X-Sendle header. This how-
ever requires support of the underlying webserver for X-Sendle.
By default it will try to guess the mimetype for you, but you can also explicitly
provide one. For extra security you probably want to send certain les as at-
tachment (HTML for instance). The mimetype guessing requires a lename or an
attachment_lename to be provided.
Please never pass lenames to this function from user sources without checking
them rst. Something like this is usually sufcient to avoid security problems:
if .. in filename or filename.startswith(/):
abort(404)
New in version 0.2.
215
New in version 0.5: The add_etags, cache_timeout and conditional parameters were
added. The default behavior is now to attach etags.
Changed in version 0.7: mimetype guessing and etag support for le objects was
deprecated because it was unreliable. Pass a lename if you are able to, otherwise
attach an etag yourself. This functionality will be removed in Flask 1.0
Changed in version 0.9: cache_timeout pulls its default from application cong,
when None.
Parameters
lename_or_fp the lename of the le to send. This is rel-
ative to the root_path if a relative path is specied. Alterna-
tively a le object might be provided in which case X-Sendle
might not work and fall back to the traditional method. Make
sure that the le pointer is positioned at the start of data to
send before calling send_file().
mimetype the mimetype of the le if provided, otherwise
auto detection happens.
as_attachment set to True if you want to send this le with a
Content-Disposition: attachment header.
attachment_lename the lename for the attachment if it dif-
fers from the les lename.
add_etags set to False to disable attaching of etags.
conditional set to True to enable conditional responses.
cache_timeout the timeout in seconds for the headers. When
None (default), this value is set by get_send_file_max_age() of
current_app.
flask.send_from_directory(directory, lename, **options)
Send a le from a given directory with send_file(). This is a secure way to
quickly expose static les from an upload folder or something similar.
Example usage:
@app.route(/uploads/<path:filename>)
def download_file(filename):
return send_from_directory(app.config[UPLOAD_FOLDER],
filename, as_attachment=True)
Sending les and Performance
It is strongly recommended to activate either X-Sendle support in your web-
server or (if no authentication happens) to tell the webserver to serve les for
the given path on its own without calling into the web application for improved
performance.
New in version 0.5.
216
Parameters
directory the directory where all the les are stored.
lename the lename relative to that directory to download.
options optional keyword arguments that are directly for-
warded to send_file().
flask.safe_join(directory, lename)
Safely join directory and lename.
Example usage:
@app.route(/wiki/<path:filename>)
def wiki_page(filename):
filename = safe_join(app.config[WIKI_FOLDER], filename)
with open(filename, rb) as fd:
content = fd.read() # Read and process the file content...
Parameters
directory the base directory.
lename the untrusted lename relative to that directory.
Raises NotFound if the resulting path would fall out of directory.
flask.escape(s)
Convert the characters &, <, >, and in string s to HTML-safe sequences. Use
this if you need to display text that might contain such characters in HTML.
Marks return value as markup string.
class flask.Markup
Marks a string as being safe for inclusion in HTML/XML output without need-
ing to be escaped. This implements the __html__ interface a couple of frame-
works and web applications use. Markup is a direct subclass of unicode and pro-
vides all the methods of unicode just that it escapes arguments passed and always
returns Markup.
The escape function returns markup objects so that double escaping cant happen.
The constructor of the Markup class can be used for three different things: When
passed an unicode object its assumed to be safe, when passed an object with
an HTML representation (has an __html__ method) that representation is used,
otherwise the object passed is converted into a unicode string and then assumed
to be safe:
>>> Markup("Hello <em>World</em>!")
Markup(uHello <em>World</em>!)
>>> class Foo(object):
... def __html__(self):
... return <a href="#">foo</a>
...
217
>>> Markup(Foo())
Markup(u<a href="#">foo</a>)
If you want object passed being always treated as unsafe you can use the
escape() classmethod to create a Markup object:
>>> Markup.escape("Hello <em>World</em>!")
Markup(uHello <em>World</em>!)
Operations on a markup string are markup aware which means that all argu-
ments are passed through the escape() function:
>>> em = Markup("<em>%s</em>")
>>> em % "foo & bar"
Markup(u<em>foo & bar</em>)
>>> strong = Markup("<strong>%(text)s</strong>")
>>> strong % {text: <blink>hacker here</blink>}
Markup(u<strong><blink>hacker here</blink></strong>)
>>> Markup("<em>Hello</em> ") + "<foo>"
Markup(u<em>Hello</em> <foo>)
classmethod escape(s)
Escape the string. Works like escape() with the difference that for sub-
classes of Markup this function would return the correct subclass.
striptags()
Unescape markup into an unicode string and strip all tags. This also re-
solves known HTML4 and XHTML entities. Whitespace is normalized to
one:
>>> Markup("Main » <em>About</em>").striptags()
uMain \xbb About
unescape()
Unescape markup again into an unicode string. This also resolves known
HTML4 and XHTML entities:
>>> Markup("Main » <em>About</em>").unescape()
uMain \xbb <em>About</em>
21.10 Message Flashing
flask.flash(message, category=message)
Flashes a message to the next request. In order to remove the ashed mes-
sage from the session and to display it to the user, the template has to call
get_flashed_messages().
Changed in version 0.3: category parameter added.
Parameters
218
message the message to be ashed.
category the category for the message. The following values
are recommended: message for any kind of message, error
for errors, info for information messages and warning for
warnings. However any kind of string can be used as category.
flask.get_flashed_messages(with_categories=False, category_lter=[])
Pulls all ashed messages from the session and returns them. Further calls in the
same request to the function will return the same messages. By default just the
messages are returned, but when with_categories is set to True, the return value
will be a list of tuples in the form (category, message) instead.
Filter the ashed messages to one or more categories by providing those cate-
gories in category_lter. This allows rendering categories in separate html blocks.
The with_categories and category_lter arguments are distinct:
with_categories controls whether categories are returned with message text
(True gives a tuple, where False gives just the message text).
category_lter lters the messages down to only those matching the pro-
vided categories.
See Message Flashing for examples.
Changed in version 0.3: with_categories parameter added.
Changed in version 0.9: category_lter parameter added.
Parameters
with_categories set to True to also receive categories.
category_lter whitelist of categories to limit return values
21.11 JSON Support
Flask uses simplejson for the JSON implementation. Since simplejson is provided
both by the standard library as well as extension Flask will try simplejson rst and
then fall back to the stdlib json module. On top of that it will delegate access to the
current applications JSON encoders and decoders for easier customization.
So for starters instead of doing:
try:
import simplejson as json
except ImportError:
import json
You can instead just do this:
from flask import json
219
For usage examples, read the json documentation in the standard library. The follow-
ing extensions are by default applied to the stdlibs JSON module:
1. datetime objects are serialized as RFC 822 strings.
2. Any object with an __html__ method (like Markup) will have that method called
and then the return value is serialized as string.
The htmlsafe_dumps() function of this json module is also available as lter called
|tojson in Jinja2. Note that inside script tags no escaping must take place, so make
sure to disable escaping with |safe if you intend to use it inside script tags unless you
are using Flask 0.10 which implies that:
<script type=text/javascript>
doSomethingWith({{ user.username|tojson|safe }});
</script>
Auto-Sort JSON Keys
The conguration variable JSON_SORT_KEYS (Conguration Handling) can be set to false
to stop Flask from auto-sorting keys. By default sorting is enabled and outside of the
app context sorting is turned on.
Notice that disabling key sorting can cause issues when using content based HTTP
caches and Pythons hash randomization feature.
flask.json.jsonify(*args, **kwargs)
Creates a Response with the JSONrepresentation of the given arguments with an
application/json mimetype. The arguments to this function are the same as to the
dict constructor.
Example usage:
from flask import jsonify
@app.route(/_get_current_user)
def get_current_user():
return jsonify(username=g.user.username,
email=g.user.email,
id=g.user.id)
This will send a JSON response like this to the browser:
{
"username": "admin",
"email": "admin@localhost",
"id": 42
}
For security reasons only objects are supported toplevel. For more information
about this, have a look at JSON Security.
This functions response will be pretty printed if it was not requested
with X-Requested-With: XMLHttpRequest to simplify debugging unless the
220
JSONIFY_PRETTYPRINT_REGULAR cong parameter is set to false.
New in version 0.2.
flask.json.dumps(obj, **kwargs)
Serialize obj to a JSON formatted str by using the applications congured en-
coder (json_encoder) if there is an application on the stack.
This function can return unicode strings or ascii-only bytestrings by default
which coerce into unicode strings automatically. That behavior by default is con-
trolled by the JSON_AS_ASCII conguration variable and can be overriden by the
simplejson ensure_ascii parameter.
flask.json.dump(obj, fp, **kwargs)
Like dumps() but writes into a le object.
flask.json.loads(s, **kwargs)
Unserialize a JSON object from a string s by using the applications congured
decoder (json_decoder) if there is an application on the stack.
flask.json.load(fp, **kwargs)
Like loads() but reads from a le object.
class flask.json.JSONEncoder(skipkeys=False, ensure_ascii=True,
check_circular=True, allow_nan=True,
sort_keys=False, indent=None, separators=None,
encoding=utf-8, default=None)
The default Flask JSONencoder. This one extends the default simplejson encoder
by also supporting datetime objects, UUID as well as Markup objects which are
serialized as RFC 822 datetime strings (same as the HTTP date format). In order
to support more data types override the default() method.
default(o)
Implement this method in a subclass such that it returns a serializable object
for o, or calls the base implementation (to raise a TypeError).
For example, to support arbitrary iterators, you could implement default
like this:
def default(self, o):
try:
iterable = iter(o)
except TypeError:
pass
else:
return list(iterable)
return JSONEncoder.default(self, o)
class flask.json.JSONDecoder(encoding=None, object_hook=None,
parse_oat=None, parse_int=None,
parse_constant=None, strict=True, ob-
ject_pairs_hook=None)
The default JSON decoder. This one does not change the behavior from the de-
fault simplejson encoder. Consult the json documentation for more informa-
221
tion. This decoder is not only used for the load functions of this module but also
Request.
21.12 Template Rendering
flask.render_template(template_name_or_list, **context)
Renders a template from the template folder with the given context.
Parameters
template_name_or_list the name of the template to be ren-
dered, or an iterable with template names the rst one existing
will be rendered
context the variables that should be available in the context
of the template.
flask.render_template_string(source, **context)
Renders a template fromthe given template source string with the given context.
Parameters
source the sourcecode of the template to be rendered
context the variables that should be available in the context
of the template.
flask.get_template_attribute(template_name, attribute)
Loads a macro (or variable) a template exports. This can be used to invoke a
macro from within Python code. If you for example have a template named
_cider.html with the following contents:
{% macro hello(name) %}Hello {{ name }}!{% endmacro %}
You can access this from Python code like this:
hello = get_template_attribute(_cider.html, hello)
return hello(World)
New in version 0.2.
Parameters
template_name the name of the template
attribute the name of the variable of macro to access
21.13 Conguration
class flask.Config(root_path, defaults=None)
Works exactly like a dict but provides ways to ll it from les or special dictio-
naries. There are two common patterns to populate the cong.
222
Either you can ll the cong from a cong le:
app.config.from_pyfile(yourconfig.cfg)
Or alternatively you can dene the conguration options in the module that calls
from_object() or provide an import path to a module that should be loaded.
It is also possible to tell it to use the same module and with that provide the
conguration values just before the call:
DEBUG = True
SECRET_KEY = development key
app.config.from_object(__name__)
In both cases (loading from any Python le or loading from modules), only up-
percase keys are added to the cong. This makes it possible to use lowercase
values in the cong le for temporary values that are not added to the cong or
to dene the cong keys in the same le that implements the application.
Probably the most interesting way to load congurations is froman environment
variable pointing to a le:
app.config.from_envvar(YOURAPPLICATION_SETTINGS)
In this case before launching the application you have to set this environment
variable to the le you want to use. On Linux and OS X use the export statement:
export YOURAPPLICATION_SETTINGS=/path/to/config/file
On windows use set instead.
Parameters
root_path path to which les are read relative from. When
the cong object is created by the application, this is the appli-
cations root_path.
defaults an optional dictionary of default values
from_envvar(variable_name, silent=False)
Loads a conguration from an environment variable pointing to a congu-
ration le. This is basically just a shortcut with nicer error messages for this
line of code:
app.config.from_pyfile(os.environ[YOURAPPLICATION_SETTINGS])
Parameters
variable_name name of the environment variable
silent set to True if you want silent failure for missing les.
Returns bool. True if able to load cong, False otherwise.
from_json(lename, silent=False)
Updates the values in the cong from a JSON le. This function behaves as
223
if the JSON object was a dictionary and passed ot the from_object() func-
tion.
Parameters
lename the lename of the JSONle. This can either be an
absolute lename or a lename relative to the root path.
silent set to True if you want silent failure for missing les.
New in version 1.0.
from_object(obj)
Updates the values from the given object. An object can be of one of the
following two types:
a string: in this case the object with that name will be imported
an actual object reference: that object is used directly
Objects are usually either modules or classes.
Just the uppercase variables in that object are stored in the cong. Example
usage:
app.config.from_object(yourapplication.default_config)
from yourapplication import default_config
app.config.from_object(default_config)
You should not use this function to load the actual conguration but
rather conguration defaults. The actual cong should be loaded with
from_pyfile() and ideally from a location not within the package because
the package might be installed system wide.
Parameters obj an import name or object
from_pyfile(lename, silent=False)
Updates the values in the cong from a Python le. This function behaves
as if the le was imported as module with the from_object() function.
Parameters
lename the lename of the cong. This can either be an
absolute lename or a lename relative to the root path.
silent set to True if you want silent failure for missing les.
New in version 0.7: silent parameter.
get_namespace(namespace, lowercase=True)
Returns a dictionary containing a subset of conguration options that match
the specied namespace/prex. Example usage:
app.config[IMAGE_STORE_TYPE] = fs
app.config[IMAGE_STORE_PATH] = /var/app/images
app.config[IMAGE_STORE_BASE_URL] = http://img.website.com
image_store_config = app.config.get_namespace(IMAGE_STORE_)
224
The resulting dictionary image_store would look like:
{
type: fs,
path: /var/app/images,
base_url: http://img.website.com
}
This is often useful when conguration options map directly to keyword
arguments in functions or class constructors.
Parameters
namespace a conguration namespace
lowercase a ag indicating if the keys of the resulting dic-
tionary should be lowercase
New in version 1.0.
21.14 Extensions
flask.ext
This module acts as redirect import module to Flask extensions. It was added in
0.8 as the canonical way to import Flask extensions and makes it possible for us
to have more exibility in how we distribute extensions.
If you want to use an extension named Flask-Foo you would import it from
ext as follows:
from flask.ext import foo
New in version 0.8.
21.15 Stream Helpers
flask.stream_with_context(generator_or_function)
Request contexts disappear when the response is started on the server. This is
done for efciency reasons and to make it less likely to encounter memory leaks
with badly written WSGI middlewares. The downside is that if you are using
streamed responses, the generator cannot access request bound information any
more.
This function however can help you keep the context around for longer:
from flask import stream_with_context, request, Response
@app.route(/stream)
def streamed_response():
@stream_with_context
225
def generate():
yield Hello
yield request.args[name]
yield !
return Response(generate())
Alternatively it can also be used around a specic generator:
from flask import stream_with_context, request, Response
@app.route(/stream)
def streamed_response():
def generate():
yield Hello
yield request.args[name]
yield !
return Response(stream_with_context(generate()))
New in version 0.9.
21.16 Useful Internals
class flask.ctx.RequestContext(app, environ, request=None)
The request context contains all request relevant information. It is created at the
beginning of the request and pushed to the _request_ctx_stack and removed at
the end of it. It will create the URL adapter and request object for the WSGI
environment provided.
Do not attempt to use this class directly, instead use test_request_context()
and request_context() to create this object.
When the request context is popped, it will evaluate all the functions registered
on the application for teardown execution (teardown_request()).
The request context is automatically popped at the end of the request for you.
In debug mode the request context is kept around if exceptions happen so that
interactive debuggers have a chance to introspect the data. With 0.4 this can also
be forced for requests that did not fail and outside of DEBUG mode. By setting
flask._preserve_context to True on the WSGI environment the context will
not pop itself at the end of the request. This is used by the test_client() for
example to implement the deferred cleanup functionality.
You might nd this helpful for unittests where you need the information from
the context local around for a little longer. Make sure to properly pop() the stack
yourself in that situation, otherwise your unittests will leak memory.
copy()
Creates a copy of this request context with the same request object. This can
be used to move a request context to a different greenlet. Because the actual
226
request object is the same this cannot be used to move a request context to
a different thread unless access to the request object is locked.
New in version 0.10.
match_request()
Can be overridden by a subclass to hook into the matching of the request.
pop(exc=None)
Pops the request context and unbinds it by doing that. This will also trigger
the execution of functions registered by the teardown_request() decorator.
Changed in version 0.9: Added the exc argument.
push()
Binds the request context to the current context.
flask._request_ctx_stack
The internal LocalStack that is used to implement all the context local objects
used in Flask. This is a documented instance and can be used by extensions and
application code but the use is discouraged in general.
The following attributes are always present on each layer of the stack:
app the active Flask application.
url_adapter the URL adapter that was used to match the request.
request the current request object.
session the active session object.
g an object with all the attributes of the flask.g object.
ashes an internal cache for the ashed messages.
Example usage:
from flask import _request_ctx_stack
def get_session():
ctx = _request_ctx_stack.top
if ctx is not None:
return ctx.session
class flask.ctx.AppContext(app)
The application context binds an application object implicitly to the current
thread or greenlet, similar to how the RequestContext binds request informa-
tion. The application context is also implicitly created if a request context is
created but the application is not on top of the individual application context.
pop(exc=None)
Pops the app context.
push()
Binds the app context to the current context.
227
flask._app_ctx_stack
Works similar to the request context but only binds the application. This is
mainly there for extensions to store data.
New in version 0.9.
class flask.blueprints.BlueprintSetupState(blueprint, app, options,
rst_registration)
Temporary holder object for registering a blueprint with the application. An in-
stance of this class is created by the make_setup_state() method and later passed
to all register callback functions.
add_url_rule(rule, endpoint=None, view_func=None, **options)
A helper method to register a rule (and optionally a view function) to the
application. The endpoint is automatically prexed with the blueprints
name.
app = None
a reference to the current application
blueprint = None
a reference to the blueprint that created this setup state.
first_registration = None
as blueprints can be registered multiple times with the application and not
everything wants to be registered multiple times on it, this attribute can be
used to gure out if the blueprint was registered in the past already.
options = None
a dictionary with all options that were passed to the register_blueprint()
method.
subdomain = None
The subdomain that the blueprint should be active for, None otherwise.
url_defaults = None
A dictionary with URL defaults that is added to each and every URL that
was dened with the blueprint.
url_prefix = None
The prex that should be used for all URLs dened on the blueprint.
21.17 Signals
New in version 0.6.
flask.signals_available
True if the signaling systemis available. This is the case when blinker is installed.
flask.template_rendered
This signal is sent when a template was successfully rendered. The signal is in-
228
voked with the instance of the template as template and the context as dictionary
(named context).
flask.request_started
This signal is sent before any request processing started but when the request
context was set up. Because the request context is already bound, the subscriber
can access the request with the standard global proxies such as request.
flask.request_finished
This signal is sent right before the response is sent to the client. It is passed the
response to be sent named response.
flask.got_request_exception
This signal is sent when an exception happens during request processing. It is
sent before the standard exception handling kicks in and even in debug mode,
where no exception handling happens. The exception itself is passed to the sub-
scriber as exception.
flask.request_tearing_down
This signal is sent when the application is tearing down the request. This is
always called, even if an error happened. An exc keyword argument is passed
with the exception that caused the teardown.
Changed in version 0.9: The exc parameter was added.
flask.appcontext_tearing_down
This signal is sent when the application is tearing down the application context.
This is always called, even if an error happened. An exc keyword argument is
passed with the exception that caused the teardown. The sender is the applica-
tion.
flask.appcontext_pushed
This signal is sent when an application context is pushed. The sender is the
application.
New in version 0.10.
flask.appcontext_popped
This signal is sent when an application context is popped. The sender is the
application. This usually falls in line with the appcontext_tearing_down signal.
New in version 0.10.
flask.message_flashed
This signal is sent when the application is ashing a message. The messages is
sent as message keyword argument and the category as category.
New in version 0.10.
class flask.signals.Namespace
An alias for blinker.base.Namespace if blinker is available, otherwise a dummy
class that creates fake signals. This class is available for Flask extensions that
want to provide the same fallback system as Flask itself.
229
signal(name, doc=None)
Creates a new signal for this namespace if blinker is available, otherwise
returns a fake signal that has a send method that will do nothing but will
fail with a RuntimeError for all other operations, including connecting.
21.18 Class-Based Views
New in version 0.7.
class flask.views.View
Alternative way to use view functions. A subclass has to implement
dispatch_request() which is called with the viewarguments fromthe URL rout-
ing system. If methods is provided the methods do not have to be passed to the
add_url_rule() method explicitly:
class MyView(View):
methods = [GET]
def dispatch_request(self, name):
return Hello %s! % name
app.add_url_rule(/hello/<name>, view_func=MyView.as_view(myview))
When you want to decorate a pluggable view you will have to either do that
when the view function is created (by wrapping the return value of as_view())
or you can use the decorators attribute:
class SecretView(View):
methods = [GET]
decorators = [superuser_required]
def dispatch_request(self):
...
The decorators stored in the decorators list are applied one after another when
the viewfunction is created. Note that you can not use the class based decorators
since those would decorate the view class and not the generated view function!
classmethod as_view(name, *class_args, **class_kwargs)
Converts the class into an actual view function that can be used with the
routing system. Internally this generates a function on the y which will in-
stantiate the View on each request and call the dispatch_request() method
on it.
The arguments passed to as_view() are forwarded to the constructor of the
class.
decorators = []
The canonical way to decorate class-based views is to decorate the return
value of as_view(). However since this moves parts of the logic from the
class declaration to the place where its hooked into the routing system.
230
You can place one or more decorators in this list and whenever the view
function is created the result is automatically decorated.
New in version 0.8.
dispatch_request()
Subclasses have to override this method to implement the actual view func-
tion code. This method is called with all the arguments from the URL rule.
methods = None
A for which methods this pluggable view can handle.
class flask.views.MethodView
Like a regular class-based view but that dispatches requests to particular meth-
ods. For instance if you implement a method called get() it means you will
response to GET requests and the dispatch_request() implementation will au-
tomatically forward your request to that. Also options is set for you automati-
cally:
class CounterAPI(MethodView):
def get(self):
return session.get(counter, 0)
def post(self):
session[counter] = session.get(counter, 0) + 1
return OK
app.add_url_rule(/counter, view_func=CounterAPI.as_view(counter))
21.19 URL Route Registrations
Generally there are three ways to dene rules for the routing system:
1. You can use the flask.Flask.route() decorator.
2. You can use the flask.Flask.add_url_rule() function.
3. You can directly access the underlying Werkzeug routing system which is ex-
posed as flask.Flask.url_map.
Variable parts in the route can be specied with angular brackets (/user/<username>).
By default a variable part in the URL accepts any string without a slash however a
different converter can be specied as well by using <converter:name>.
Variable parts are passed to the view function as keyword arguments.
The following converters are available:
string accepts any text without a slash (the default)
int accepts integers
oat like int but for oating point values
path like the default but also accepts slashes
231
Here are some examples:
@app.route(/)
def index():
pass
@app.route(/<username>)
def show_user(username):
pass
@app.route(/post/<int:post_id>)
def show_post(post_id):
pass
An important detail to keep in mind is how Flask deals with trailing slashes. The idea
is to keep each URL unique so the following rules apply:
1. If a rule ends with a slash and is requested without a slash by the user, the user
is automatically redirected to the same page with a trailing slash attached.
2. If a rule does not end with a trailing slash and the user requests the page with a
trailing slash, a 404 not found is raised.
This is consistent with how web servers deal with static les. This also makes it possi-
ble to use relative link targets safely.
You can also dene multiple rules for the same function. They have to be unique
however. Defaults can also be specied. Here for example is a denition for a URL
that accepts an optional page:
@app.route(/users/, defaults={page: 1})
@app.route(/users/page/<int:page>)
def show_users(page):
pass
This species that /users/ will be the URL for page one and /users/page/N will be the
URL for page N.
Here are the parameters that route() and add_url_rule() accept. The only difference
is that with the route parameter the viewfunction is dened with the decorator instead
of the view_func parameter.
232
rule the URL rule as string
end-
point
the endpoint for the registered URL rule. Flask itself assumes that the name
of the view function is the name of the endpoint if not explicitly stated.
view_func the function to call when serving a request to the provided endpoint. If this
is not provided one can specify the function later by storing it in the
view_functions dictionary with the endpoint as key.
de-
faults
A dictionary with defaults for this rule. See the example above for how
defaults work.
sub-
do-
main
species the rule for the subdomain in case subdomain matching is in use.
If not specied the default subdomain is assumed.
**op-
tions
the options to be forwarded to the underlying Rule object. A change to
Werkzeug is handling of method options. methods is a list of methods this
rule should be limited to (GET, POST etc.). By default a rule just listens for
GET (and implicitly HEAD). Starting with Flask 0.6, OPTIONS is implicitly
added and handled by the standard request handling. They have to be
specied as keyword arguments.
21.20 View Function Options
For internal usage the view functions can have some attributes attached to customize
behavior the view function would normally not have control over. The following at-
tributes can be provided optionally to either override some defaults to add_url_rule()
or general behavior:
__name__: The name of a function is by default used as endpoint. If endpoint is
provided explicitly this value is used. Additionally this will be prexed with the
name of the blueprint by default which cannot be customized from the function
itself.
methods: If methods are not provided when the URL rule is added, Flask will
look on the view function object itself is an methods attribute exists. If it does, it
will pull the information for the methods from there.
provide_automatic_options: if this attribute is set Flask will either force enable or
disable the automatic implementation of the HTTP OPTIONS response. This can
be useful when working with decorators that want to customize the OPTIONS
response on a per-view basis.
required_methods: if this attribute is set, Flask will always add these methods
when registering a URL rule even if the methods were explicitly overridden in
the route() call.
Full example:
def index():
if request.method == OPTIONS:
# custom options handling here
...
233
return Hello World!
index.provide_automatic_options = False
index.methods = [GET, OPTIONS]
app.add_url_rule(/, index)
New in version 0.8: The provide_automatic_options functionality was added.
234
Part III
ADDITIONAL NOTES
Design notes, legal information and changelog are here for the interested.
235
236
CHAPTER
TWENTYTWO
DESIGN DECISIONS IN FLASK
If you are curious why Flask does certain things the way it does and not differently,
this section is for you. This should give you an idea about some of the design decisions
that may appear arbitrary and surprising at rst, especially in direct comparison with
other frameworks.
22.1 The Explicit Application Object
A Python web application based on WSGI has to have one central callable object that
implements the actual application. In Flask this is an instance of the Flask class. Each
Flask application has to create an instance of this class itself and pass it the name of
the module, but why cant Flask do that itself?
Without such an explicit application object the following code:
from flask import Flask
app = Flask(__name__)
@app.route(/)
def index():
return Hello World!
Would look like this instead:
from hypothetical_flask import route
@route(/)
def index():
return Hello World!
There are three major reasons for this. The most important one is that implicit appli-
cation objects require that there may only be one instance at the time. There are ways
to fake multiple applications with a single application object, like maintaining a stack
of applications, but this causes some problems I wont outline here in detail. Now
the question is: when does a microframework need more than one application at the
same time? A good example for this is unittesting. When you want to test something
237
it can be very helpful to create a minimal application to test specic behavior. When
the application object is deleted everything it allocated will be freed again.
Another thing that becomes possible when you have an explicit object lying around in
your code is that you can subclass the base class (Flask) to alter specic behavior. This
would not be possible without hacks if the object were created ahead of time for you
based on a class that is not exposed to you.
But there is another very important reason why Flask depends on an explicit instantia-
tion of that class: the package name. Whenever you create a Flask instance you usually
pass it __name__ as package name. Flask depends on that information to properly load
resources relative to your module. With Pythons outstanding support for reection it
can then access the package to gure out where the templates and static les are stored
(see open_resource()). Now obviously there are frameworks around that do not need
any conguration and will still be able to load templates relative to your application
module. But they have to use the current working directory for that, which is a very
unreliable way to determine where the application is. The current working directory is
process-wide and if you are running multiple applications in one process (which could
happen in a webserver without you knowing) the paths will be off. Worse: many web-
servers do not set the working directory to the directory of your application but to the
document root which does not have to be the same folder.
The third reason is explicit is better than implicit. That object is your WSGI ap-
plication, you dont have to remember anything else. If you want to apply a WSGI
middleware, just wrap it and youre done (though there are better ways to do that so
that you do not lose the reference to the application object wsgi_app()).
Furthermore this design makes it possible to use a factory function to create the appli-
cation which is very helpful for unittesting and similar things (Application Factories).
22.2 The Routing System
Flask uses the Werkzeug routing system which was designed to automatically order
routes by complexity. This means that you can declare routes in arbitrary order and
they will still work as expected. This is a requirement if you want to properly imple-
ment decorator based routing since decorators could be red in undened order when
the application is split into multiple modules.
Another design decision with the Werkzeug routing systemis that routes in Werkzeug
try to ensure that URLs are unique. Werkzeug will go quite far with that in that it will
automatically redirect to a canonical URL if a route is ambiguous.
22.3 One Template Engine
Flask decides on one template engine: Jinja2. Why doesnt Flask have a pluggable tem-
plate engine interface? You can obviously use a different template engine, but Flask
will still congure Jinja2 for you. While that limitation that Jinja2 is always congured
238
will probably go away, the decision to bundle one template engine and use that will
not.
Template engines are like programming languages and each of those engines has a
certain understanding about how things work. On the surface they all work the same:
you tell the engine to evaluate a template with a set of variables and take the return
value as string.
But thats about where similarities end. Jinja2 for example has an extensive lter sys-
tem, a certain way to do template inheritance, support for reusable blocks (macros)
that can be used from inside templates and also from Python code, uses Unicode for
all operations, supports iterative template rendering, congurable syntax and more.
On the other hand an engine like Genshi is based on XML stream evaluation, template
inheritance by taking the availability of XPath into account and more. Mako on the
other hand treats templates similar to Python modules.
When it comes to connecting a template engine with an application or framework
there is more than just rendering templates. For instance, Flask uses Jinja2s extensive
autoescaping support. Also it provides ways to access macros from Jinja2 templates.
A template abstraction layer that would not take the unique features of the template
engines away is a science on its own and a too large undertaking for a microframework
like Flask.
Furthermore extensions can then easily depend on one template language being
present. You can easily use your own templating language, but an extension could
still depend on Jinja itself.
22.4 Micro with Dependencies
Why does Flask call itself a microframework and yet it depends on two libraries
(namely Werkzeug and Jinja2). Why shouldnt it? If we look over to the Ruby side of
web development there we have a protocol very similar to WSGI. Just that its called
Rack there, but besides that it looks very much like a WSGI rendition for Ruby. But
nearly all applications in Ruby land do not work with Rack directly, but on top of a
library with the same name. This Rack library has two equivalents in Python: WebOb
(formerly Paste) and Werkzeug. Paste is still around but from my understanding its
sort of deprecated in favour of WebOb. The development of WebOb and Werkzeug
started side by side with similar ideas in mind: be a good implementation of WSGI for
other applications to take advantage.
Flask is a framework that takes advantage of the work already done by Werkzeug to
properly interface WSGI (which can be a complex task at times). Thanks to recent
developments in the Python package infrastructure, packages with dependencies are
no longer an issue and there are very few reasons against having libraries that depend
on others.
239
22.5 Thread Locals
Flask uses thread local objects (context local objects in fact, they support greenlet con-
texts as well) for request, session and an extra object you can put your own things on
(g). Why is that and isnt that a bad idea?
Yes it is usually not such a bright idea to use thread locals. They cause troubles for
servers that are not based on the concept of threads and make large applications harder
to maintain. However Flask is just not designed for large applications or asynchronous
servers. Flask wants to make it quick and easy to write a traditional web application.
Also see the Becoming Big section of the documentation for some inspiration for larger
applications based on Flask.
22.6 What Flask is, What Flask is Not
Flask will never have a database layer. It will not have a form library or anything else
in that direction. Flask itself just bridges to Werkzeug to implement a proper WSGI
application and to Jinja2 to handle templating. It also binds to a fewcommon standard
library packages such as logging. Everything else is up for extensions.
Why is this the case? Because people have different preferences and requirements and
Flask could not meet those if it would force any of this into the core. The majority
of web applications will need a template engine in some sort. However not every
application needs a SQL database.
The idea of Flask is to build a good foundation for all applications. Everything else is
up to you or extensions.
240
CHAPTER
TWENTYTHREE
HTML/XHTML FAQ
The Flask documentation and example applications are using HTML5. You may no-
tice that in many situations, when end tags are optional they are not used, so that
the HTML is cleaner and faster to load. Because there is much confusion about HTML
and XHTML among developers, this document tries to answer some of the major ques-
tions.
23.1 History of XHTML
For a while, it appeared that HTML was about to be replaced by XHTML. However,
barely any websites on the Internet are actual XHTML (which is HTML processed us-
ing XML rules). There are a couple of major reasons why this is the case. One of
them is Internet Explorers lack of proper XHTML support. The XHTML spec states
that XHTML must be served with the MIME type application/xhtml+xml, but Internet
Explorer refuses to read les with that MIME type. While it is relatively easy to con-
gure Web servers to serve XHTML properly, few people do. This is likely because
properly using XHTML can be quite painful.
One of the most important causes of pain is XMLs draconian (strict and ruthless) er-
ror handling. When an XML parsing error is encountered, the browser is supposed to
show the user an ugly error message, instead of attempting to recover from the error
and display what it can. Most of the (X)HTML generation on the web is based on
non-XML template engines (such as Jinja, the one used in Flask) which do not protect
you from accidentally creating invalid XHTML. There are XML based template en-
gines, such as Kid and the popular Genshi, but they often come with a larger runtime
overhead and, are not as straightforward to use because they have to obey XML rules.
The majority of users, however, assumed they were properly using XHTML. They
wrote an XHTML doctype at the top of the document and self-closed all the necessary
tags (<br> becomes <br/> or <br></br> in XHTML). However, even if the document
properly validates as XHTML, what really determines XHTML/HTML processing in
browsers is the MIME type, which as said before is often not set properly. So the valid
XHTML was being treated as invalid HTML.
XHTML also changed the way JavaScript is used. To properly work with XHTML, pro-
grammers have to use the namespaced DOM interface with the XHTML namespace
241
to query for HTML elements.
23.2 History of HTML5
Development of the HTML5 specication was started in 2004 under the name Web
Applications 1.0 by the Web Hypertext Application Technology Working Group, or
WHATWG (which was formed by the major browser vendors Apple, Mozilla, and
Opera) with the goal of writing a new and improved HTML specication, based on
existing browser behavior instead of unrealistic and backwards-incompatible speci-
cations.
For example, in HTML4 <title/Hello/ theoretically parses exactly the same as
<title>Hello</title>. However, since people were using XHTML-like tags along the
lines of <link />, browser vendors implemented the XHTML syntax over the syntax
dened by the specication.
In 2007, the specication was adopted as the basis of a new HTML specication under
the umbrella of the W3C, known as HTML5. Currently, it appears that XHTML is
losing traction, as the XHTML 2 working group has been disbanded and HTML5 is
being implemented by all major browser vendors.
23.3 HTML versus XHTML
The following table gives you a quick overview of features available in HTML 4.01,
XHTML 1.1 and HTML5. (XHTML 1.0 is not included, as it was superseded by
XHTML 1.1 and the barely-used XHTML5.)
HTML4.01 XHTML1.1 HTML5
<tag/value/ == <tag>value</tag>
1
<br/> supported
2
<script/> supported
should be served as text/html
3
should be served as application/xhtml+xml
strict error handling
inline SVG
inline MathML
<video> tag
<audio> tag
New semantic tags like <article>
1
This is an obscure feature inherited fromSGML. It is usually not supported by browsers, for reasons
detailed above.
242
23.4 What does strict mean?
HTML5 has strictly dened parsing rules, but it also species exactly how a browser
should react to parsing errors - unlike XHTML, which simply states parsing should
abort. Some people are confused by apparently invalid syntax that still generates the
expected results (for example, missing end tags or unquoted attribute values).
Some of these work because of the lenient error handling most browsers use when
they encounter a markup error, others are actually specied. The following constructs
are optional in HTML5 by standard, but have to be supported by browsers:
Wrapping the document in an <html> tag
Wrapping header elements in <head> or the body elements in <body>
Closing the <p>, <li>, <dt>, <dd>, <tr>, <td>, <th>, <tbody>, <thead>, or <tfoot>
tags.
Quoting attributes, so long as they contain no whitespace or special characters
(like <, >, , or ").
Requiring boolean attributes to have a value.
This means the following page in HTML5 is perfectly valid:
<!doctype html>
<title>Hello HTML5</title>
<div class=header>
<h1>Hello HTML5</h1>
<p class=tagline>HTML5 is awesome
</div>
<ul class=nav>
<li><a href=/index>Index</a>
<li><a href=/downloads>Downloads</a>
<li><a href=/about>About</a>
</ul>
<div class=body>
<h2>HTML5 is probably the future</h2>
<p>
There might be some other things around but in terms of
browser vendor support, HTML5 is hard to beat.
<dl>
<dt>Key 1
<dd>Value 1
<dt>Key 2
<dd>Value 2
</dl>
</div>
2
This is for compatibility with server code that generates XHTML for tags such as <br>. It should
not be used in new code.
3
XHTML 1.0 is the last XHTML standard that allows to be served as text/html for backwards com-
patibility reasons.
243
23.5 New technologies in HTML5
HTML5 adds many new features that make Web applications easier to write and to
use.
The <audio> and <video> tags provide a way to embed audio and video without
complicated add-ons like QuickTime or Flash.
Semantic elements like <article>, <header>, <nav>, and <time> that make con-
tent easier to understand.
The <canvas> tag, which supports a powerful drawing API, reducing the need
for server-generated images to present data graphically.
Newformcontrol types like <input type="date"> that allowuser agents to make
entering and validating values easier.
Advanced JavaScript APIs like Web Storage, Web Workers, Web Sockets, geolo-
cation, and ofine applications.
Many other features have been added, as well. A good guide to new features in
HTML5 is Mark Pilgrims soon-to-be-published book, Dive Into HTML5. Not all of
them are supported in browsers yet, however, so use caution.
23.6 What should be used?
Currently, the answer is HTML5. There are very few reasons to use XHTML consider-
ing the latest developments in Web browsers. To summarize the reasons given above:
Internet Explorer (which, sadly, currently leads in market share) has poor sup-
port for XHTML.
Many JavaScript libraries also do not support XHTML, due to the more compli-
cated namespacing API it requires.
HTML5 adds several newfeatures, including semantic tags and the long-awaited
<audio> and <video> tags.
It has the support of most browser vendors behind it.
It is much easier to write, and more compact.
For most applications, it is undoubtedly better to use HTML5 than XHTML.
244
CHAPTER
TWENTYFOUR
SECURITY CONSIDERATIONS
Web applications usually face all kinds of security problems and its very hard to get
everything right. Flask tries to solve a few of these things for you, but there are a
couple more you have to take care of yourself.
24.1 Cross-Site Scripting (XSS)
Cross site scripting is the concept of injecting arbitrary HTML (and with it JavaScript)
into the context of a website. To remedy this, developers have to properly escape text
so that it cannot include arbitrary HTML tags. For more information on that have a
look at the Wikipedia article on Cross-Site Scripting.
Flask congures Jinja2 to automatically escape all values unless explicitly told other-
wise. This should rule out all XSS problems caused in templates, but there are still
other places where you have to be careful:
generating HTML without the help of Jinja2
calling Markup on data submitted by users
sending out HTML from uploaded les, never do that, use the Content-
Disposition: attachment header to prevent that problem.
sending out textles from uploaded les. Some browsers are using content-type
guessing based on the rst few bytes so users could trick a browser to execute
HTML.
Another thing that is very important are unquoted attributes. While Jinja2 can protect
you from XSS issues by escaping HTML, there is one thing it cannot protect you from:
XSS by attribute injection. To counter this possible attack vector, be sure to always
quote your attributes with either double or single quotes when using Jinja expressions
in them:
<a href="{{ href }}">the text</a>
Why is this necessary? Because if you would not be doing that, an attacker could easily
inject custom JavaScript handlers. For example an attacker could inject this piece of
HTML+JavaScript:
245
onmouseover=alert(document.cookie)
When the user would then move with the mouse over the link, the cookie would be
presented to the user in an alert window. But instead of showing the cookie to the
user, a good attacker might also execute any other JavaScript code. In combination
with CSS injections the attacker might even make the element ll out the entire page
so that the user would just have to have the mouse anywhere on the page to trigger
the attack.
24.2 Cross-Site Request Forgery (CSRF)
Another big problem is CSRF. This is a very complex topic and I wont outline it here
in detail just mention what it is and how to theoretically prevent it.
If your authentication information is stored in cookies, you have implicit state man-
agement. The state of being logged in is controlled by a cookie, and that cookie is
sent with each request to a page. Unfortunately that includes requests triggered by
3rd party sites. If you dont keep that in mind, some people might be able to trick your
applications users with social engineering to do stupid things without themknowing.
Say you have a specic URL that, when you sent POST requests to will delete a users
prole (say http://example.com/user/delete). If an attacker now creates a page that sends
a post request to that page with some JavaScript they just has to trick some users to
load that page and their proles will end up being deleted.
Imagine you were to run Facebook with millions of concurrent users and someone
would send out links to images of little kittens. When users would go to that page,
their proles would get deleted while they are looking at images of uffy cats.
How can you prevent that? Basically for each request that modies content on the
server you would have to either use a one-time token and store that in the cookie and
also transmit it with the form data. After receiving the data on the server again, you
would then have to compare the two tokens and ensure they are equal.
Why does Flask not do that for you? The ideal place for this to happen is the form
validation framework, which does not exist in Flask.
24.3 JSON Security
ECMAScript 5 Changes
Starting with ECMAScript 5 the behavior of literals changed. Now they are not con-
structed with the constructor of Array and others, but with the builtin constructor of
Array which closes this particular attack vector.
JSON itself is a high-level serialization format, so there is barely anything that could
cause security problems, right? You cant declare recursive structures that could cause
246
problems and the only thing that could possibly break are very large responses that
can cause some kind of denial of service at the receivers side.
However there is a catch. Due to how browsers work the CSRF issue comes up with
JSON unfortunately. Fortunately there is also a weird part of the JavaScript specica-
tion that can be used to solve that problem easily and Flask is kinda doing that for you
by preventing you from doing dangerous stuff. Unfortunately that protection is only
there for jsonify() so you are still at risk when using other ways to generate JSON.
So what is the issue and how to avoid it? The problem are arrays at top-level in JSON.
Imagine you send the following data out in a JSON request. Say thats exporting the
names and email addresses of all your friends for a part of the user interface that is
written in JavaScript. Not very uncommon:
[
{"username": "admin",
"email": "admin@localhost"}
]
And it is doing that of course only as long as you are logged in and only for you. And
it is doing that for all GET requests to a certain URL, say the URL for that request is
http://example.com/api/get_friends.json.
So now what happens if a clever hacker is embedding this to his website and social
engineers a victim to visiting his site:
<script type=text/javascript>
var captured = [];
var oldArray = Array;
function Array() {
var obj = this, id = 0, capture = function(value) {
obj.__defineSetter__(id++, capture);
if (value)
captured.push(value);
};
capture();
}
</script>
<script type=text/javascript
src=http://example.com/api/get_friends.json></script>
<script type=text/javascript>
Array = oldArray;
// now we have all the data in the captured array.
</script>
If you know a bit of JavaScript internals you might know that its possible to patch
constructors and register callbacks for setters. An attacker can use this (like above)
to get all the data you exported in your JSON le. The browser will totally ignore
the application/json mimetype if text/javascript is dened as content type in the
script tag and evaluate that as JavaScript. Because top-level array elements are allowed
(albeit useless) and we hooked in our own constructor, after that page loaded the data
from the JSON response is in the captured array.
247
Because it is a syntax error in JavaScript to have an object literal ({...}) toplevel an
attacker could not just do a request to an external URL with the script tag to load up
the data. So what Flask does is to only allow objects as toplevel elements when using
jsonify(). Make sure to do the same when using an ordinary JSONgenerate function.
248
CHAPTER
TWENTYFIVE
UNICODE IN FLASK
Flask like Jinja2 and Werkzeug is totally Unicode based when it comes to text. Not
only these libraries, also the majority of web related Python libraries that deal with
text. If you dont know Unicode so far, you should probably read The Absolute Min-
imum Every Software Developer Absolutely, Positively Must Know About Unicode
and Character Sets. This part of the documentation just tries to cover the very basics
so that you have a pleasant experience with Unicode related things.
25.1 Automatic Conversion
Flask has a few assumptions about your application (which you can change of course)
that give you basic and painless Unicode support:
the encoding for text on your website is UTF-8
internally you will always use Unicode exclusively for text except for literal
strings with only ASCII character points.
encoding and decoding happens whenever you are talking over a protocol that
requires bytes to be transmitted.
So what does this mean to you?
HTTP is based on bytes. Not only the protocol, also the system used to address doc-
uments on servers (so called URIs or URLs). However HTML which is usually trans-
mitted on top of HTTP supports a large variety of character sets and which ones are
used, are transmitted in an HTTP header. To not make this too complex Flask just
assumes that if you are sending Unicode out you want it to be UTF-8 encoded. Flask
will do the encoding and setting of the appropriate headers for you.
The same is true if you are talking to databases with the help of SQLAlchemy or a
similar ORM system. Some databases have a protocol that already transmits Unicode
and if they do not, SQLAlchemy or your other ORM should take care of that.
249
25.2 The Golden Rule
So the rule of thumb: if you are not dealing with binary data, work with Unicode.
What does working with Unicode in Python 2.x mean?
as long as you are using ASCII charpoints only (basically numbers, some special
characters of latin letters without umlauts or anything fancy) you can use regular
string literals (Hello World).
if you need anything else than ASCII in a string you have to mark this string as
Unicode string by prexing it with a lowercase u. (like uHnsel und Gretel)
if you are using non-Unicode characters in your Python les you have to tell
Python which encoding your le uses. Again, I recommend UTF-8 for this
purpose. To tell the interpreter your encoding you can put the # -*- coding:
utf-8 -*- into the rst or second line of your Python source le.
Jinja is congured to decode the template les from UTF-8. So make sure to tell
your editor to save the le as UTF-8 there as well.
25.3 Encoding and Decoding Yourself
If you are talking with a lesystem or something that is not really based on Unicode
you will have to ensure that you decode properly when working with Unicode inter-
face. So for example if you want to load a le on the lesystem and embed it into a
Jinja2 template you will have to decode it from the encoding of that le. Here the old
problem that text les do not specify their encoding comes into play. So do yourself a
favour and limit yourself to UTF-8 for text les as well.
Anyways. To load such a le with Unicode you can use the built-in str.decode()
method:
def read_file(filename, charset=utf-8):
with open(filename, r) as f:
return f.read().decode(charset)
To go from Unicode into a specic charset such as UTF-8 you can use the
unicode.encode() method:
def write_file(filename, contents, charset=utf-8):
with open(filename, w) as f:
f.write(contents.encode(charset))
25.4 Conguring Editors
Most editors save as UTF-8 by default nowadays but in case your editor is not cong-
ured to do this you have to change it. Here some common ways to set your editor to
store as UTF-8:
250
Vim: put set enc=utf-8 to your .vimrc le.
Emacs: either use an encoding cookie or put this into your .emacs le:
(prefer-coding-system utf-8)
(setq default-buffer-file-coding-system utf-8)
Notepad++:
1. Go to Settings -> Preferences ...
2. Select the New Document/Default Directory tab
3. Select UTF-8 without BOM as encoding
It is also recommended to use the Unix newline format, you can select it in the
same panel but this is not a requirement.
251
252
CHAPTER
TWENTYSIX
FLASK EXTENSION DEVELOPMENT
Flask, being a microframework, often requires some repetitive steps to get a third party
library working. Because very often these steps could be abstracted to support multi-
ple projects the Flask Extension Registry was created.
If you want to create your own Flask extension for something that does not exist yet,
this guide to extension development will help you get your extension running in no
time and to feel like users would expect your extension to behave.
26.1 Anatomy of an Extension
Extensions are all located in a package called flask_something where something is
the name of the library you want to bridge. So for example if you plan to add support
for a library named simplexml to Flask, you would name your extensions package
flask_simplexml.
The name of the actual extension (the human readable name) however would be some-
thing like Flask-SimpleXML. Make sure to include the name Flask somewhere in
that name and that you check the capitalization. This is how users can then register
dependencies to your extension in their setup.py les.
Flask sets up a redirect package called flask.ext where users should import the ex-
tensions from. If you for instance have a package called flask_something users would
import it as flask.ext.something. This is done to transition from the old namespace
packages. See Extension Import Transition for more details.
But how do extensions look like themselves? An extension has to ensure that it works
with multiple Flask application instances at once. This is a requirement because many
people will use patterns like the Application Factories pattern to create their application
as needed to aid unittests and to support multiple congurations. Because of that it is
crucial that your application supports that kind of behavior.
Most importantly the extension must be shipped with a setup.py le and registered
on PyPI. Also the development checkout link should work so that people can easily
install the development version into their virtualenv without having to download the
library by hand.
253
Flask extensions must be licensed under a BSD, MIT or more liberal license to be able
to be enlisted in the Flask Extension Registry. Keep in mind that the Flask Extension
Registry is a moderated place and libraries will be reviewed upfront if they behave as
required.
26.2 Hello Flaskext!
So lets get started with creating such a Flask extension. The extension we want to
create here will provide very basic support for SQLite3.
First we create the following folder structure:
flask-sqlite3/
flask_sqlite3.py
LICENSE
README
Heres the contents of the most important les:
26.2.1 setup.py
The next le that is absolutely required is the setup.py le which is used to install your
Flask extension. The following contents are something you can work with:
"""
Flask-SQLite3
-------------
This is the description for that library
"""
from setuptools import setup
setup(
name=Flask-SQLite3,
version=1.0,
url=http://example.com/flask-sqlite3/,
license=BSD,
author=Your Name,
[email protected],
description=Very short description,
long_description=__doc__,
py_modules=[flask_sqlite3],
# if you would be using a package instead use packages instead
# of py_modules:
# packages=[flask_sqlite3],
zip_safe=False,
include_package_data=True,
platforms=any,
254
install_requires=[
Flask
],
classifiers=[
Environment :: Web Environment,
Intended Audience :: Developers,
License :: OSI Approved :: BSD License,
Operating System :: OS Independent,
Programming Language :: Python,
Topic :: Internet :: WWW/HTTP :: Dynamic Content,
Topic :: Software Development :: Libraries :: Python Modules
]
)
Thats a lot of code but you can really just copy/paste that from existing extensions
and adapt.
26.2.2 ask_sqlite3.py
Now this is where your extension code goes. But how exactly should such an exten-
sion look like? What are the best practices? Continue reading for some insight.
26.3 Initializing Extensions
Many extensions will need some kind of initialization step. For example, consider an
application thats currently connecting to SQLite like the documentation suggests (Us-
ing SQLite 3 with Flask). So how does the extension know the name of the application
object?
Quite simple: you pass it to it.
There are two recommended ways for an extension to initialize:
initialization functions:
If your extension is called helloworld you might have a function called
init_helloworld(app[, extra_args]) that initializes the extension for that
application. It could attach before / after handlers etc.
classes:
Classes work mostly like initialization functions but can later be used to
further change the behavior. For an example look at how the OAuth exten-
sion works: there is an OAuth object that provides some helper functions
like OAuth.remote_app to create a reference to a remote application that uses
OAuth.
What to use depends on what you have in mind. For the SQLite 3 extension we will
use the class-based approach because it will provide users with an object that handles
opening and closing database connections.
255
Whats important about classes is that they encourage to be shared around on mod-
ule level. In that case, the object itself must not under any circumstances store any
application specic state and must be shareable between different application.
26.4 The Extension Code
Heres the contents of the ask_sqlite3.py for copy/paste:
import sqlite3
from flask import current_app
# Find the stack on which we want to store the database connection.
# Starting with Flask 0.9, the _app_ctx_stack is the correct one,
# before that we need to use the _request_ctx_stack.
try:
from flask import _app_ctx_stack as stack
except ImportError:
from flask import _request_ctx_stack as stack
class SQLite3(object):
def __init__(self, app=None):
self.app = app
if app is not None:
self.init_app(app)
def init_app(self, app):
app.config.setdefault(SQLITE3_DATABASE, :memory:)
# Use the newstyle teardown_appcontext if its available,
# otherwise fall back to the request context
if hasattr(app, teardown_appcontext):
app.teardown_appcontext(self.teardown)
else:
app.teardown_request(self.teardown)
def connect(self):
return sqlite3.connect(current_app.config[SQLITE3_DATABASE])
def teardown(self, exception):
ctx = stack.top
if hasattr(ctx, sqlite3_db):
ctx.sqlite3_db.close()
@property
def connection(self):
ctx = stack.top
if ctx is not None:
if not hasattr(ctx, sqlite3_db):
256
ctx.sqlite3_db = self.connect()
return ctx.sqlite3_db
So heres what these lines of code do:
1. The __init__ method takes an optional app object and, if supplied, will call
init_app.
2. The init_app method exists so that the SQLite3 object can be instantiated with-
out requiring an app object. This method supports the factory pattern for cre-
ating applications. The init_app will set the conguration for the database, de-
faulting to an in memory database if no conguration is supplied. In addition,
the init_app method attaches the teardown handler. It will try to use the new-
style app context handler and if it does not exist, falls back to the request context
one.
3. Next, we dene a connect method that opens a database connection.
4. Finally, we add a connection property that on rst access opens the database
connection and stores it on the context. This is also the recommended way to
handling resources: fetch resources lazily the rst time they are used.
Note here that were attaching our database connection to the top application
context via _app_ctx_stack.top. Extensions should use the top context for stor-
ing their own information with a sufciently complex name. Note that were
falling back to the _request_ctx_stack.top if the application is using an older
version of Flask that does not support it.
So why did we decide on a class-based approach here? Because using our extension
looks something like this:
from flask import Flask
from flask_sqlite3 import SQLite3
app = Flask(__name__)
app.config.from_pyfile(the-config.cfg)
db = SQLite3(app)
You can then use the database from views like this:
@app.route(/)
def show_all():
cur = db.connection.cursor()
cur.execute(...)
Likewise if you are outside of a request but you are using Flask 0.9 or later with the
app context support, you can use the database in the same way:
with app.app_context():
cur = db.connection.cursor()
cur.execute(...)
At the end of the with block the teardown handles will be executed automatically.
257
Additionally, the init_app method is used to support the factory pattern for creating
apps:
db = Sqlite3()
# Then later on.
app = create_app(the-config.cfg)
db.init_app(app)
Keep in mind that supporting this factory pattern for creating apps is required for
approved ask extensions (described below).
Note on init_app
As you noticed, init_app does not assign app to self. This is intentional! Class based
Flask extensions must only store the application on the object when the application
was passed to the constructor. This tells the extension: I am not interested in using
multiple applications.
When the extension needs to nd the current application and it does not have a refer-
ence to it, it must either use the current_app context local or change the API in a way
that you can pass the application explicitly.
26.5 Using _app_ctx_stack
In the example above, before every request, a sqlite3_db variable is assigned
to _app_ctx_stack.top. In a view function, this variable is accessible using the
connection property of SQLite3. During the teardown of a request, the sqlite3_db
connection is closed. By using this pattern, the same connection to the sqlite3 database
is accessible to anything that needs it for the duration of the request.
If the _app_ctx_stack does not exist because the user uses an old version of Flask, it is
recommended to fall back to _request_ctx_stack which is bound to a request.
26.6 Teardown Behavior
This is only relevant if you want to support Flask 0.6 and older
Due to the change in Flask 0.7 regarding functions that are run at the end of the request
your extension will have to be extra careful there if it wants to continue to support
older versions of Flask. The following pattern is a good way to support both:
def close_connection(response):
ctx = _request_ctx_stack.top
ctx.sqlite3_db.close()
return response
if hasattr(app, teardown_request):
258
app.teardown_request(close_connection)
else:
app.after_request(close_connection)
Strictly speaking the above code is wrong, because teardown functions are passed the
exception and typically dont return anything. However because the return value is
discarded this will just work assuming that the code in between does not touch the
passed parameter.
26.7 Learn from Others
This documentation only touches the bare minimum for extension development. If
you want to learn more, its a very good idea to check out existing extensions on the
Flask Extension Registry. If you feel lost there is still the mailinglist and the IRC chan-
nel to get some ideas for nice looking APIs. Especially if you do something nobody
before you did, it might be a very good idea to get some more input. This not only
to get an idea about what people might want to have from an extension, but also to
avoid having multiple developers working on pretty much the same side by side.
Remember: good API design is hard, so introduce your project on the mailinglist, and
let other developers give you a helping hand with designing the API.
The best Flask extensions are extensions that share common idioms for the API. And
this can only work if collaboration happens early.
26.8 Approved Extensions
Flask also has the concept of approved extensions. Approved extensions are tested as
part of Flask itself to ensure extensions do not break on new releases. These approved
extensions are listed on the Flask Extension Registry and marked appropriately. If you
want your own extension to be approved you have to follow these guidelines:
0. An approved Flask extension requires a maintainer. In the event an extension
author would like to move beyond the project, the project should nd a new
maintainer including full source hosting transition and PyPI access. If no main-
tainer is available, give access to the Flask core team.
1. An approved Flask extension must provide exactly one package or module
named flask_extensionname. They might also reside inside a flaskext names-
pace packages though this is discouraged now.
2. It must ship a testing suite that can either be invoked with make test or python
setup.py test. For test suites invoked with make test the extension has to en-
sure that all dependencies for the test are installed automatically. If tests are
invoked with python setup.py test, test dependencies can be specied in the
setup.py le. The test suite also has to be part of the distribution.
3. APIs of approved extensions will be checked for the following characteristics:
259
an approved extension has to support multiple applications running in the
same Python process.
it must be possible to use the factory pattern for creating applications.
4. The license must be BSD/MIT/WTFPL licensed.
5. The naming scheme for ofcial extensions is Flask-ExtensionName or
ExtensionName-Flask.
6. Approved extensions must dene all their dependencies in the setup.py le un-
less a dependency cannot be met because it is not available on PyPI.
7. The extension must have documentation that uses one of the two Flask themes
for Sphinx documentation.
8. The setup.py description (and thus the PyPI description) has to link to the doc-
umentation, website (if there is one) and there must be a link to automatically
install the development version (PackageName==dev).
9. The zip_safe ag in the setup script must be set to False, even if the extension
would be safe for zipping.
10. An extension currently has to support Python 2.6 as well as Python 2.7
26.9 Extension Import Transition
For a while we recommended using namespace packages for Flask extensions. This
turned out to be problematic in practice because many different competing namespace
package systems exist and pip would automatically switch between different systems
and this caused a lot of problems for users.
Instead we now recommend naming packages flask_foo instead of the now depre-
cated flaskext.foo. Flask 0.8 introduces a redirect import systemthat lets uses import
from flask.ext.foo and it will try flask_foo rst and if that fails flaskext.foo.
Flask extensions should urge users to import fromflask.ext.foo instead of flask_foo
or flaskext_foo so that extensions can transition to the new package name without
affecting users.
260
CHAPTER
TWENTYSEVEN
POCOO STYLEGUIDE
The Pocoo styleguide is the styleguide for all Pocoo Projects, including Flask. This
styleguide is a requirement for Patches to Flask and a recommendation for Flask ex-
tensions.
In general the Pocoo Styleguide closely follows PEP 8 with some small differences and
extensions.
27.1 General Layout
Indentation: 4 real spaces. No tabs, no exceptions.
Maximum line length: 79 characters with a soft limit for 84 if absolutely necessary.
Try to avoid too nested code by cleverly placing break, continue and return state-
ments.
Continuing long statements: To continue a statement you can use backslashes in
which case you should align the next line with the last dot or equal sign, or
indent four spaces:
this_is_a_very_long(function_call, with many parameters) \
.that_returns_an_object_with_an_attribute
MyModel.query.filter(MyModel.scalar > 120) \
.order_by(MyModel.name.desc()) \
.limit(10)
If you break in a statement with parentheses or braces, align to the braces:
this_is_a_very_long(function_call, with many parameters,
23, 42, and even more)
For lists or tuples with many items, break immediately after the opening brace:
items = [
this is the first, set of items, with more items,
to come in this line, like this
]
261
Blank lines: Top level functions and classes are separated by two lines, everything
else by one. Do not use too many blank lines to separate logical segments in
code. Example:
def hello(name):
print Hello %s! % name
def goodbye(name):
print See you %s. % name
class MyClass(object):
"""This is a simple docstring"""
def __init__(self, name):
self.name = name
def get_annoying_name(self):
return self.name.upper() + !!!!111
27.2 Expressions and Statements
General whitespace rules:
No whitespace for unary operators that are not words (e.g.: -, ~ etc.) as well
on the inner side of parentheses.
Whitespace is placed between binary operators.
Good:
exp = -1.05
value = (item_value / item_count) * offset / exp
value = my_list[index]
value = my_dict[key]
Bad:
exp = - 1.05
value = ( item_value / item_count ) * offset / exp
value = (item_value/item_count)*offset/exp
value=( item_value/item_count ) * offset/exp
value = my_list[ index ]
value = my_dict [key]
Yoda statements are a no-go: Never compare constant with variable, always variable
with constant:
Good:
262
if method == md5:
pass
Bad:
if md5 == method:
pass
Comparisons:
against arbitrary types: == and !=
against singletons with is and is not (eg: foo is not None)
never compare something with True or False (for example never do foo ==
False, do not foo instead)
Negated containment checks: use foo not in bar instead of not foo in bar
Instance checks: isinstance(a, C) instead of type(A) is C, but try to avoid instance
checks in general. Check for features.
27.3 Naming Conventions
Class names: CamelCase, with acronyms kept uppercase (HTTPWriter and not
HttpWriter)
Variable names: lowercase_with_underscores
Method and function names: lowercase_with_underscores
Constants: UPPERCASE_WITH_UNDERSCORES
precompiled regular expressions: name_re
Protected members are prexed with a single underscore. Double underscores are
reserved for mixin classes.
On classes with keywords, trailing underscores are appended. Clashes with builtins
are allowed and must not be resolved by appending an underline to the variable name.
If the function needs to access a shadowed builtin, rebind the builtin to a different
name instead.
Function and method arguments:
class methods: cls as rst parameter
instance methods: self as rst parameter
lambdas for properties might have the rst parameter replaced with x like
in display_name = property(lambda x: x.real_name or x.username)
263
27.4 Docstrings
Docstring conventions: All docstrings are formatted with reStructuredText as under-
stood by Sphinx. Depending on the number of lines in the docstring, they are
laid out differently. If its just one line, the closing triple quote is on the same line
as the opening, otherwise the text is on the same line as the opening quote and
the triple quote that closes the string on its own line:
def foo():
"""This is a simple docstring"""
def bar():
"""This is a longer docstring with so much information in there
that it spans three lines. In this case the closing triple quote
is on its own line.
"""
Module header: The module header consists of an utf-8 encoding declaration (if non
ASCII letters are used, but it is recommended all the time) and a standard doc-
string:
# -*- coding: utf-8 -*-
"""
package.module
~~~~~~~~~~~~~~
A brief description goes here.
:copyright: (c) YEAR by AUTHOR.
:license: LICENSE_NAME, see LICENSE_FILE for more details.
"""
Please keep in mind that proper copyrights and license les are a requirement
for approved Flask extensions.
27.5 Comments
Rules for comments are similar to docstrings. Both are formatted with reStructured-
Text. If a comment is used to document an attribute, put a colon after the opening
pound sign (#):
class User(object):
#: the name of the user as unicode string
name = Column(String)
#: the sha1 hash of the password + inline salt
pw_hash = Column(String)
264
CHAPTER
TWENTYEIGHT
PYTHON 3 SUPPORT
Flask and all of its dependencies support Python 3 so you can in theory start working
on it already. There are however a few things you should be aware of before you start
using Python 3 for your next project.
28.1 Requirements
If you want to use Flask with Python 3 you will need to use Python 3.3 or higher. 3.2
and older are not supported.
In addition to that you need to use the latest and greatest versions of itsdangerous, Jinja2
and Werkzeug.
28.2 API Stability
Some of the decisions made in regards to unicode and byte untilization on Python 3
make it hard to write lowlevel code. This mainly affects WSGI middlewares and inter-
acting with the WSGI provided information. Werkzeug wraps all that information in
high-level helpers but some of those were specically added for the Python 3 support
and are quite new.
A lot of the documentation out there on using WSGI leaves out those details as it was
written before WSGI was updated to Python 3. While the API for Werkzeug and Flask
on Python 2.x should not change much we cannot guarantee that this wont happen
on Python 3.
28.3 Few Users
Python 3 currently has less than 1% of the users of Python 2 going by PyPI download
stats. As a result many of the problems you will encounter are probably hard to search
for on the internet if they are Python 3 specic.
265
28.4 Small Ecosystem
The majority of the Flask extensions, all of the documentation and the vast majority of
the PyPI provided libraries do not support Python 3 yet. Even if you start your project
with knowing that all you will need is supported by Python 3 you dont know what
happens six months from now. If you are adventurous you can start porting libraries
on your own, but that is nothing for the faint of heart.
28.5 Recommendations
Unless you are already familiar with the differences in the versions we recommend
sticking to current versions of Python until the ecosystem caught up.
The majority of the upgrade pain is in the lower-level libararies like Flask and
Werkzeug and not in the actual high-level application code. For instance all of the
Flask examples that are in the Flask repository work out of the box on both 2.x and 3.x
and did not require a single line of code changed.
266
CHAPTER
TWENTYNINE
UPGRADING TO NEWER RELEASES
Flask itself is changing like any software is changing over time. Most of the changes
are the nice kind, the kind where you dont have to change anything in your code to
prot from a new release.
However every once in a while there are changes that do require some changes in
your code or there are changes that make it possible for you to improve your own
code quality by taking advantage of new features in Flask.
This section of the documentation enumerates all the changes in Flask from release to
release and how you can change your code to have a painless updating experience.
If you want to use the easy_install command to upgrade your Flask installation, make
sure to pass it the -U parameter:
$ easy_install -U Flask
29.1 Version 0.10
The biggest change going from 0.9 to 0.10 is that the cookie serialization format
changed frompickle to a specialized JSONformat. This change has been done in order
to avoid the damage an attacker can do if the secret key is leaked. When you upgrade
you will notice two major changes: all sessions that were issued before the upgrade
are invalidated and you can only store a limited amount of types in the session. The
new sessions are by design much more restricted to only allow JSON with a few small
extensions for tuples and strings with HTML markup.
In order to not break peoples sessions it is possible to continue using the old session
system by using the Flask-OldSessions extension.
Flask also started storing the flask.g object on the application context instead of the
request context. This change should be transparent for you but it means that you now
can store things on the g object when there is no request context yet but an applica-
tion context. The old flask.Flask.request_globals_class attribute was renamed to
flask.Flask.app_ctx_globals_class.
267
29.2 Version 0.9
The behavior of returning tuples from a function was simplied. If you return a tuple
it no longer denes the arguments for the response object youre creating, its now
always a tuple in the form (response, status, headers) where at least one item has
to be provided. If you depend on the old behavior, you can add it easily by subclassing
Flask:
class TraditionalFlask(Flask):
def make_response(self, rv):
if isinstance(rv, tuple):
return self.response_class(*rv)
return Flask.make_response(self, rv)
If you maintain an extension that was using _request_ctx_stack before, please con-
sider changing to _app_ctx_stack if it makes sense for your extension. For instance,
the app context stack makes sense for extensions which connect to databases. Using
the app context stack instead of the request stack will make extensions more readily
handle use cases outside of requests.
29.3 Version 0.8
Flask introduced a new session interface system. We also noticed that there
was a naming collision between ask.session the module that implements sessions
and flask.session which is the global session object. With that introduction we
moved the implementation details for the session system into a new module called
flask.sessions. If you used the previously undocumented session support we urge
you to upgrade.
If invalid JSON data was submitted Flask will now raise a BadRequest exception in-
stead of letting the default ValueError bubble up. This has the advantage that you no
longer have to handle that error to avoid an internal server error showing up for the
user. If you were catching this down explicitly in the past as ValueError you will need
to change this.
Due to a bug in the test client Flask 0.7 did not trigger teardown handlers when the
test client was used in a with statement. This was since xed but might require some
changes in your testsuites if you relied on this behavior.
29.4 Version 0.7
In Flask 0.7 we cleaned up the code base internally a lot and did some backwards in-
compatible changes that make it easier to implement larger applications with Flask.
Because we want to make upgrading as easy as possible we tried to counter the prob-
lems arising from these changes by providing a script that can ease the transition.
268
The script scans your whole application and generates an unied diff with changes it
assumes are safe to apply. However as this is an automated tool it wont be able to
nd all use cases and it might miss some. We internally spread a lot of deprecation
warnings all over the place to make it easy to nd pieces of code that it was unable to
upgrade.
We strongly recommend that you hand review the generated patchle and only apply
the chunks that look good.
If you are using git as version control system for your project we recommend apply-
ing the patch with path -p1 < patchfile.diff and then using the interactive commit
feature to only apply the chunks that look good.
To apply the upgrade script do the following:
1. Download the script: ask-07-upgrade.py
2. Run it in the directory of your application:
python flask-07-upgrade.py > patchfile.diff
3. Review the generated patchle.
4. Apply the patch:
patch -p1 < patchfile.diff
5. If you were using per-module template folders you need to move some templates
around. Previously if you had a folder named templates next to a blueprint
named admin the implicit template path automatically was admin/index.html for
a template le called templates/index.html. This no longer is the case. Nowyou
need to name the template templates/admin/index.html. The tool will not detect
this so you will have to do that on your own.
Please note that deprecation warnings are disabled by default starting with Python 2.7.
In order to see the deprecation warnings that might be emitted you have to enabled
them with the warnings module.
If you are working with windows and you lack the patch command line utility you can
get it as part of various Unix runtime environments for windows including cygwin,
msysgit or ming32. Also source control systems like svn, hg or git have builtin support
for applying unied diffs as generated by the tool. Check the manual of your version
control system for more information.
29.4.1 Bug in Request Locals
Due to a bug in earlier implementations the request local proxies now raise a
RuntimeError instead of an AttributeError when they are unbound. If you
caught these exceptions with AttributeError before, you should catch them with
RuntimeError now.
Additionally the send_file() function is now issuing deprecation warnings if you
depend on functionality that will be removed in Flask 1.0. Previously it was possible
269
to use etags and mimetypes when le objects were passed. This was unreliable and
caused issues for a few setups. If you get a deprecation warning, make sure to update
your application to work with either lenames there or disable etag attaching and
attach them yourself.
Old code:
return send_file(my_file_object)
return send_file(my_file_object)
New code:
return send_file(my_file_object, add_etags=False)
29.4.2 Upgrading to new Teardown Handling
We streamlined the behavior of the callbacks for request handling. For things that
modify the response the after_request() decorators continue to work as expected,
but for things that absolutely must happen at the end of request we introduced the new
teardown_request() decorator. Unfortunately that change also made after-request
work differently under error conditions. Its not consistently skipped if exceptions
happen whereas previously it might have been called twice to ensure it is executed at
the end of the request.
If you have database connection code that looks like this:
@app.after_request
def after_request(response):
g.db.close()
return response
You are now encouraged to use this instead:
@app.teardown_request
def after_request(exception):
if hasattr(g, db):
g.db.close()
On the upside this change greatly improves the internal code ow and makes it easier
to customize the dispatching and error handling. This makes it now a lot easier to
write unit tests as you can prevent closing down of database connections for a while.
You can take advantage of the fact that the teardown callbacks are called when the re-
sponse context is removed fromthe stack so a test can query the database after request
handling:
with app.test_client() as client:
resp = client.get(/)
# g.db is still bound if there is such a thing
# and here its gone
270
29.4.3 Manual Error Handler Attaching
While it is still possible to attach error handlers to Flask.error_handlers its discour-
aged to do so and in fact deprecated. In general we no longer recommend custom
error handler attaching via assignments to the underlying dictionary due to the more
complex internal handling to support arbitrary exception classes and blueprints. See
Flask.errorhandler() for more information.
The proper upgrade is to change this:
app.error_handlers[403] = handle_error
Into this:
app.register_error_handler(403, handle_error)
Alternatively you should just attach the function with a decorator:
@app.errorhandler(403)
def handle_error(e):
...
(Note that register_error_handler() is new in Flask 0.7)
29.4.4 Blueprint Support
Blueprints replace the previous concept of Modules in Flask. They provide better
semantics for various features and work better with large applications. The update
script provided should be able to upgrade your applications automatically, but there
might be some cases where it fails to upgrade. What changed?
Blueprints need explicit names. Modules had an automatic name guesssing
scheme where the shortname for the module was taken from the last part of
the import module. The upgrade script tries to guess that name but it might fail
as this information could change at runtime.
Blueprints have an inverse behavior for url_for(). Previously .foo told
url_for() that it should look for the endpoint foo on the application. Now it
means relative to current module. The script will inverse all calls to url_for()
automatically for you. It will do this in a very eager way so you might end up
with some unnecessary leading dots in your code if youre not using modules.
Blueprints do not automatically provide static folders. They will also no longer
automatically export templates from a folder called templates next to their loca-
tion however but it can be enabled from the constructor. Same with static les: if
you want to continue serving static les you need to tell the constructor explic-
itly the path to the static folder (which can be relative to the blueprints module
path).
Rendering templates was simplied. Now the blueprints can provide template
folders which are added to a general template searchpath. This means that you
271
need to add another subfolder with the blueprints name into that folder if you
want blueprintname/template.html as the template name.
If you continue to use the Module object which is deprecated, Flask will restore the
previous behavior as good as possible. However we strongly recommend upgrading
to the new blueprints as they provide a lot of useful improvement such as the ability
to attach a blueprint multiple times, blueprint specic error handlers and a lot more.
29.5 Version 0.6
Flask 0.6 comes with a backwards incompatible change which affects the order of after-
request handlers. Previously they were called in the order of the registration, now
they are called in reverse order. This change was made so that Flask behaves more like
people expected it to work and how other systems handle request pre- and postpro-
cessing. If you depend on the order of execution of post-request functions, be sure to
change the order.
Another change that breaks backwards compatibility is that context processors will no
longer override values passed directly to the template rendering function. If for exam-
ple request is as variable passed directly to the template, the default context processor
will not override it with the current request object. This makes it easier to extend con-
text processors later to inject additional variables without breaking existing template
not expecting them.
29.6 Version 0.5
Flask 0.5 is the rst release that comes as a Python package instead of a single mod-
ule. There were a couple of internal refactoring so if you depend on undocumented
internal details you probably have to adapt the imports.
The following changes may be relevant to your application:
autoescaping no longer happens for all templates. Instead it is congured to only
happen on les ending with .html, .htm, .xml and .xhtml. If you have templates
with different extensions you should override the select_jinja_autoescape()
method.
Flask no longer supports zipped applications in this release. This functionality
might come back in future releases if there is demand for this feature. Removing
support for this makes the Flask internal code easier to understand and xes a
couple of small issues that make debugging harder than necessary.
The create_jinja_loader function is gone. If you want to customize the Jinja loader
now, use the create_jinja_environment() method instead.
272
29.7 Version 0.4
For application developers there are no changes that require changes in your code.
In case you are developing on a Flask extension however, and that extension has a
unittest-mode you might want to link the activation of that mode to the new TESTING
ag.
29.8 Version 0.3
Flask 0.3 introduces conguration support and logging as well as categories for ash-
ing messages. All these are features that are 100% backwards compatible but you
might want to take advantage of them.
29.8.1 Conguration Support
The conguration support makes it easier to write any kind of application that requires
some sort of conguration. (Which most likely is the case for any application out
there).
If you previously had code like this:
app.debug = DEBUG
app.secret_key = SECRET_KEY
You no longer have to do that, instead you can just load a conguration into the cong
object. How this works is outlined in Conguration Handling.
29.8.2 Logging Integration
Flask now congures a logger for you with some basic and useful defaults. If you
run your application in production and want to prot from automatic error logging,
you might be interested in attaching a proper log handler. Also you can start logging
warnings and errors into the logger when appropriately. For more information on
that, read Logging Application Errors.
29.8.3 Categories for Flash Messages
Flash messages can now have categories attached. This makes it possible to render
errors, warnings or regular messages differently for example. This is an opt-in feature
because it requires some rethinking in the code.
Read all about that in the Message Flashing pattern.
273
274
CHAPTER
THIRTY
FLASK CHANGELOG
Here you can see the full list of changes between each Flask release.
30.1 Version 1.0
(release date to be announced, codename to be selected)
Added SESSION_REFRESH_EACH_REQUEST cong key that controls the set-cookie
behavior. If set to True a permanent session will be refreshed each request and
get their lifetime extended, if set to False it will only be modied if the session ac-
tually modies. Non permanent sessions are not affected by this and will always
expire if the browser window closes.
Made Flask support custom JSON mimetypes for incoming data.
Added support for returning tuples in the form (response, headers) from a
view function.
Added flask.Config.from_json().
Added flask.Flask.config_class.
Added flask.config.Config.get_namespace().
30.2 Version 0.10.2
(bugx release, release date to be announced)
Fixed broken test_appcontext_signals() test case.
Raise an AttributeError in flask.helpers.find_package() with a useful mes-
sage explaining why it is raised when a PEP 302 import hook is used without an
is_package() method.
Fixed an issue causing exceptions raised before entering a request or app context
to be passed to teardown handlers.
275
Fixed an issue with query parameters getting removed from requests in the test
client when absolute URLs were requested.
Made @before_rst_request into a decorator as intended.
Fixed an etags bug when sending a le streams with a name.
Fixed send_from_directory not expanding to the application root path correctly.
Changed logic of before rst request handlers to ip the ag after invoking. This
will allow some uses that are potentially dangerous but should probably be per-
mitted.
30.3 Version 0.10.1
(bugx release, released on June 14th 2013)
Fixed an issue where |tojson was not quoting single quotes which made the
lter not work properly in HTML attributes. Now its possible to use that lter
in single quoted attributes. This should make using that lter with angular.js
easier.
Added support for byte strings back to the session system. This broke compati-
bility with the common case of people putting binary data for token verication
into the session.
Fixed an issue where registering the same method twice for the same endpoint
would trigger an exception incorrectly.
30.4 Version 0.10
Released on June 13nd 2013, codename Limoncello.
Changed default cookie serialization format from pickle to JSON to limit the
impact an attacker can do if the secret key leaks. See Version 0.10 for more infor-
mation.
Added template_test methods in addition to the already existing
template_filter method family.
Added template_global methods in addition to the already existing
template_filter method family.
Set the content-length header for x-sendle.
tojson lter now does not escape script blocks in HTML5 parsers.
tojson used in templates is now safe by default due. This was allowed due to
the different escaping behavior.
Flask will now raise an error if you attempt to register a new function on an
already used endpoint.
276
Added wrapper module around simplejson and added default serialization of
datetime objects. This allows much easier customization of howJSONis handled
by Flask or any Flask extension.
Removed deprecated internal flask.session module alias. Use flask.sessions
instead to get the session module. This is not to be confused with flask.session
the session proxy.
Templates can now be rendered without request context. The behavior is
slightly different as the request, session and g objects will not be available and
blueprints context processors are not called.
The cong object is nowavailable to the template as a real global and not through
a context processor which makes it available even in imported templates by de-
fault.
Added an option to generate non-ascii encoded JSONwhich should result in less
bytes being transmitted over the network. Its disabled by default to not cause
confusion with existing libraries that might expect flask.json.dumps to return
bytestrings by default.
flask.g is now stored on the app context instead of the request context.
flask.g now gained a get() method for not erroring out on non existing items.
flask.g now can be used with the in operator to see whats dened and it now
is iterable and will yield all attributes stored.
flask.Flask.request_globals_class got renamed to
flask.Flask.app_ctx_globals_class which is a better name to what it does
since 0.10.
request, session and g are nowalso added as proxies to the template context which
makes them available in imported templates. One has to be very careful with
those though because usage outside of macros might cause caching.
Flask will no longer invoke the wrong error handlers if a proxy exception is
passed through.
Added a workaround for chromes cookies in localhost not working as intended
with domain names.
Changed logic for picking defaults for cookie values fromsessions to work better
with Google Chrome.
Added message_ashed signal that simplies ashing testing.
Added support for copying of request contexts for better working with greenlets.
Removed custom JSON HTTP exception subclasses. If you were relying on
them you can reintroduce them again yourself trivially. Using them however
is strongly discouraged as the interface was awed.
Python requirements changed: requiring Python 2.6 or 2.7 now to prepare for
Python 3.3 port.
277
Changed how the teardown system is informed about exceptions. This is now
more reliable in case something handles an exception halfway through the error
handling process.
Request context preservation in debug mode now keeps the exception informa-
tion around which means that teardown handlers are able to distinguish error
from success cases.
Added the JSONIFY_PRETTYPRINT_REGULAR conguration variable.
Flask noworders JSONkeys by default to not trash HTTP caches due to different
hash seeds between different workers.
Added appcontext_pushed and appcontext_popped signals.
The builtin run method now takes the SERVER_NAME into account when picking
the default port to run on.
Added ask.request.get_json() as a replacement for the old ask.request.json prop-
erty.
30.5 Version 0.9
Released on July 1st 2012, codename Campari.
The flask.Request.on_json_loading_failed() now returns a JSON formatted
response by default.
The flask.url_for() function now can generate anchors to the generated links.
The flask.url_for() function now can also explicitly generate URL rules spe-
cic to a given HTTP method.
Logger now only returns the debug log setting if it was not set explicitly.
Unregister a circular dependency between the WSGI environment and the
request object when shutting down the request. This means that environ
werkzeug.request will be None after the response was returned to the WSGI
server but has the advantage that the garbage collector is not needed on CPython
to tear down the request unless the user created circular dependencies them-
selves.
Session is nowstored after callbacks so that if the session payload is stored in the
session you can still modify it in an after request callback.
The flask.Flask class will avoid importing the provided import name if it can
(the required rst parameter), to benet tools which build Flask instances pro-
grammatically. The Flask class will fall back to using import on systems with
custom module hooks, e.g. Google App Engine, or when the import name is
inside a zip archive (usually a .egg) prior to Python 2.7.
Blueprints nowhave a decorator to add customtemplate lters application wide,
flask.Blueprint.app_template_filter().
278
The Flask and Blueprint classes now have a non-decorator method for adding
custom template lters application wide, flask.Flask.add_template_filter()
and flask.Blueprint.add_app_template_filter().
The flask.get_flashed_messages() function nowallows rendering ashed mes-
sage categories in separate blocks, through a category_filter argument.
The flask.Flask.run() method now accepts None for host and port arguments,
using default values when None. This allows for calling run using conguration
values, e.g. app.run(app.config.get(MYHOST), app.config.get(MYPORT)),
with proper behavior whether or not a cong le is provided.
The flask.render_template() method now accepts a either an iterable of tem-
plate names or a single template name. Previously, it only accepted a single
template name. On an iterable, the rst template found is rendered.
Added flask.Flask.app_context() which works very similar to the request con-
text but only provides access to the current application. This also adds support
for URL generation without an active request context.
View functions can now return a tuple with the rst instance being an instance
of flask.Response. This allows for returning jsonify(error="error msg"), 400
from a view function.
Flask and Blueprint now provide a get_send_file_max_age() hook for sub-
classes to override behavior of serving static les from Flask when using
flask.Flask.send_static_file() (used for the default static le handler) and
send_file(). This hook is provided a lename, which for example allows chang-
ing cache controls by le extension. The default max-age for send_le and static
les can be congured through a newSEND_FILE_MAX_AGE_DEFAULT conguration
variable, which is used in the default get_send_le_max_age implementation.
Fixed an assumption in sessions implementation which could break message
ashing on sessions implementations which use external storage.
Changed the behavior of tuple return values from functions. They are no longer
arguments to the response object, they now have a dened meaning.
Added flask.Flask.request_globals_class to allow a specic class to be used
on creation of the g instance of each request.
Added required_methods attribute to view functions to force-add methods on reg-
istration.
Added flask.after_this_request().
Added flask.stream_with_context() and the ability to push contexts multiple
times without producing unexpected behavior.
30.6 Version 0.8.1
Bugx release, released on July 1st 2012
279
Fixed an issue with the undocumented ask.session module to not work properly
on Python 2.5. It should not be used but did cause some problems for package
managers.
30.7 Version 0.8
Released on September 29th 2011, codename Rakija
Refactored session support into a session interface so that the implementation of
the sessions can be changed without having to override the Flask class.
Empty session cookies are now deleted properly automatically.
View functions can now opt out of getting the automatic OPTIONS implementa-
tion.
HTTP exceptions and Bad Request errors can now be trapped so that they show
up normally in the traceback.
Flask in debug mode is nowdetecting some common problems and tries to warn
you about them.
Flask in debug mode will now complain with an assertion error if a view was
attached after the rst request was handled. This gives earlier feedback when
users forget to import view code ahead of time.
Added the ability to register callbacks that are only triggered once at the begin-
ning of the rst request. (Flask.before_first_request())
Malformed JSON data will now trigger a bad request HTTP exception instead
of a value error which usually would result in a 500 internal server error if not
handled. This is a backwards incompatible change.
Applications nownot only have a root path where the resources and modules are
located but also an instance path which is the designated place to drop les that
are modied at runtime (uploads etc.). Also this is conceptionally only instance
depending and outside version control so its the perfect place to put congura-
tion les etc. For more information see Instance Folders.
Added the APPLICATION_ROOT conguration variable.
Implemented session_transaction() to easily modify sessions from the test en-
vironment.
Refactored test client internally. The APPLICATION_ROOT conguration variable as
well as SERVER_NAME are now properly used by the test client as defaults.
Added flask.views.View.decorators to support simpler decorating of plug-
gable (class-based) views.
Fixed an issue where the test client if used with the with statement did not
trigger the execution of the teardown handlers.
Added ner control over the session cookie parameters.
280
HEAD requests to a method view now automatically dispatch to the get method
if no handler was implemented.
Implemented the virtual flask.ext package to import extensions from.
The context preservation on exceptions is now an integral component of Flask
itself and no longer of the test client. This cleaned up some internal logic and
lowers the odds of runaway request contexts in unittests.
30.8 Version 0.7.3
Bugx release, release date to be decided
Fixed the Jinja2 environments list_templates method not returning the correct
names when blueprints or modules were involved.
30.9 Version 0.7.2
Bugx release, released on July 6th 2011
Fixed an issue with URL processors not properly working on blueprints.
30.10 Version 0.7.1
Bugx release, released on June 29th 2011
Added missing future import that broke 2.5 compatibility.
Fixed an innite redirect issue with blueprints.
30.11 Version 0.7
Released on June 28th 2011, codename Grappa
Added make_default_options_response() which can be used by subclasses to
alter the default behavior for OPTIONS responses.
Unbound locals now raise a proper RuntimeError instead of an AttributeError.
Mimetype guessing and etag support based on le objects is now deprecated for
flask.send_file() because it was unreliable. Pass lenames instead or attach
your own etags and provide a proper mimetype by hand.
Static le handling for modules now requires the name of the static folder to
be supplied explicitly. The previous autodetection was not reliable and caused
281
issues on Googles App Engine. Until 1.0 the old behavior will continue to work
but issue dependency warnings.
xed a problem for Flask to run on jython.
added a PROPAGATE_EXCEPTIONS conguration variable that can be used to
ip the setting of exception propagation which previously was linked to DEBUG
alone and is now linked to either DEBUG or TESTING.
Flask no longer internally depends on rules being added through the add_url_rule
function and can now also accept regular werkzeug rules added to the url map.
Added an endpoint method to the ask application object which allows one to
register a callback to an arbitrary endpoint with a decorator.
Use Last-Modied for static le sending instead of Date which was incorrectly
introduced in 0.6.
Added create_jinja_loader to override the loader creation process.
Implemented a silent ag for cong.from_pyle.
Added teardown_request decorator, for functions that should run at the end of
a request regardless of whether an exception occurred. Also the behavior for
after_request was changed. Its now no longer executed when an exception is
raised. See Upgrading to new Teardown Handling
Implemented flask.has_request_context()
Deprecated init_jinja_globals. Override the create_jinja_environment() method
instead to achieve the same functionality.
Added flask.safe_join()
The automatic JSON request data unpacking now looks at the charset mimetype
parameter.
Dont modify the session on flask.get_flashed_messages() if there are no mes-
sages in the session.
before_request handlers are now able to abort requests with errors.
it is not possible to dene user exception handlers. That way you can provide
customerror messages froma central hub for certain errors that might occur dur-
ing request processing (for instance database connection errors, timeouts from
remote resources etc.).
Blueprints can provide blueprint specic error handlers.
Implemented generic Pluggable Views (class-based views).
30.12 Version 0.6.1
Bugx release, released on December 31st 2010
282
Fixed an issue where the default OPTIONS response was not exposing all valid
methods in the Allow header.
Jinja2 template loading syntax now allows ./ in front of a template load path.
Previously this caused issues with module setups.
Fixed an issue where the subdomain setting for modules was ignored for the
static folder.
Fixed a security problem that allowed clients to download arbitrary les if the
host server was a windows based operating system and the client uses back-
slashes to escape the directory the les where exposed from.
30.13 Version 0.6
Released on July 27th 2010, codename Whisky
after request functions are now called in reverse order of registration.
OPTIONS is now automatically implemented by Flask unless the application
explicitly adds OPTIONS as method to the URL rule. In this case no automatic
OPTIONS handling kicks in.
static rules are now even in place if there is no static folder for the module. This
was implemented to aid GAE which will remove the static folder if its part of a
mapping in the .yml le.
the config is now available in the templates as cong.
context processors will no longer override values passed directly to the render
function.
added the ability to limit the incoming request data with the new
MAX_CONTENT_LENGTH conguration value.
the endpoint for the flask.Module.add_url_rule() method is now optional to
be consistent with the function of the same name on the application object.
added a flask.make_response() function that simplies creating response object
instances in views.
added signalling support based on blinker. This feature is currently optional and
supposed to be used by extensions and applications. If you want to use it, make
sure to have blinker installed.
refactored the way URL adapters are created. This process is nowfully customiz-
able with the create_url_adapter() method.
modules can now register for a subdomain instead of just an URL prex. This
makes it possible to bind a whole module to a congurable subdomain.
283
30.14 Version 0.5.2
Bugx Release, released on July 15th 2010
xed another issue with loading templates from directories when modules were
used.
30.15 Version 0.5.1
Bugx Release, released on July 6th 2010
xes an issue with template loading from directories when modules where used.
30.16 Version 0.5
Released on July 6th 2010, codename Calvados
xed a bug with subdomains that was caused by the inability to specify the
server name. The server name can now be set with the SERVER_NAME cong
key. This key is now also used to set the session cookie cross-subdomain wide.
autoescaping is no longer active for all templates. Instead it is only active for
.html, .htm, .xml and .xhtml. Inside templates this behavior can be changed
with the autoescape tag.
refactored Flask internally. It now consists of more than a single le.
flask.send_file() now emits etags and has the ability to do conditional re-
sponses builtin.
(temporarily) dropped support for zipped applications. This was a rarely used
feature and led to some confusing behavior.
added support for per-package template and static-le directories.
removed support for create_jinja_loader which is no longer used in 0.5 due to the
improved module support.
added a helper function to expose les from any directory.
30.17 Version 0.4
Released on June 18th 2010, codename Rakia
added the ability to register application wide error handlers from modules.
after_request() handlers are now also invoked if the request dies with an ex-
ception and an error handling page kicks in.
284
test client has not the ability to preserve the request context for a little longer.
This can also be used to trigger custom requests that do not pop the request
stack for testing.
because the Python standard library caches loggers, the name of the logger is
congurable now to better support unittests.
added TESTING switch that can activate unittesting helpers.
the logger switches to DEBUG mode now if debug is enabled.
30.18 Version 0.3.1
Bugx release, released on May 28th 2010
xed a error reporting bug with flask.Config.from_envvar()
removed some unused code from ask
release does no longer include development leftover les (.git folder for themes,
built documentation in zip and pdf le and some .pyc les)
30.19 Version 0.3
Released on May 28th 2010, codename Schnaps
added support for categories for ashed messages.
the application now congures a logging.Handler and will log request handling
exceptions to that logger when not in debug mode. This makes it possible to
receive mails on server errors for example.
added support for context binding that does not require the use of the with state-
ment for playing in the console.
the request context is nowavailable within the with statement making it possible
to further push the request context or pop it.
added support for congurations.
30.20 Version 0.2
Released on May 12th 2010, codename Jgermeister
various bugxes
integrated JSON support
added get_template_attribute() helper function.
285
add_url_rule() can now also register a view function.
refactored internal request dispatching.
server listens on 127.0.0.1 by default now to x issues with chrome.
added external URL support.
added support for send_file()
module support and internal request handling refactoring to better support
pluggable applications.
sessions can be set to be permanent now on a per-session basis.
better error reporting on missing secret keys.
added support for Google Appengine.
30.21 Version 0.1
First public preview release.
286
CHAPTER
THIRTYONE
LICENSE
Flask is licensed under a three clause BSD License. It basically means: do whatever
you want with it as long as the copyright in Flask sticks around, the conditions are not
modied and the disclaimer is present. Furthermore you must not use the names of
the authors to promote derivatives of the software without written consent.
The full license text can be found below (Flask License). For the documentation and
artwork different licenses apply.
31.1 Authors
Flask is written and maintained by Armin Ronacher and various contributors:
31.1.1 Development Lead
Armin Ronacher <[email protected]>
31.1.2 Patches and Suggestions
Adam Zapletal
Ali Afshar
Chris Edgemon
Chris Grindstaff
Christopher Grebs
Daniel Neuhuser
Florent Xicluna
Georg Brandl
Justin Quick
Kenneth Reitz
287
Marian Sigler
Matt Campell
Matthew Frazier
Michael van Tellingen
Ron DuPlain
Sebastien Estienne
Simon Sapin
Stephane Wirtel
Thomas Schranz
Zhao Xiaohong
Edmond Burnett
31.2 General License Denitions
The following section contains the full license texts for Flask and the documentation.
AUTHORS hereby refers to all the authors listed in the Authors section.
The Flask License applies to all the sourcecode shipped as part of Flask (Flask
itself as well as the examples and the unittests) as well as documentation.
The Flask Artwork License applies to the projects Horn-Logo.
31.3 Flask License
Copyright (c) 2014 by Armin Ronacher and contributors. See AUTHORS for more
details.
Some rights reserved.
Redistribution and use in source and binary forms of the software as well as docu-
mentation, with or without modication, are permitted provided that the following
conditions are met:
Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
The names of the contributors may not be used to endorse or promote products
derived from this software without specic prior written permission.
288
THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE COPYRIGHT
HOLDERS AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED WAR-
RANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DIS-
CLAIMED. INNOEVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PRO-
CUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE AND DOCUMENTATION, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
31.4 Flask Artwork License
Copyright (c) 2010 by Armin Ronacher.
Some rights reserved.
This logo or a modied version may be used by anyone to refer to the Flask project,
but does not indicate endorsement by the project.
Redistribution and use in source (the SVG le) and binary forms (rendered PNG les
etc.) of the image, with or without modication, are permitted provided that the fol-
lowing conditions are met:
Redistributions of source code must retain the above copyright notice and this
list of conditions.
The names of the contributors to the Flask software (see AUTHORS) may not be
used to endorse or promote products derived fromthis software without specic
prior written permission.
Note: we would appreciate that you make the image a link to http://ask.pocoo.org/
if you use it on a web page.
289
290
INDEX
Symbols
_app_ctx_stack (in module ask), 227
_request_ctx_stack (in module ask), 227
A
abort() (in module ask), 214
add_app_template_lter()
(ask.Blueprint method), 198
add_app_template_global()
(ask.Blueprint method), 198
add_app_template_test() (ask.Blueprint
method), 198
add_template_lter() (ask.Flask
method), 178
add_template_global() (ask.Flask
method), 178
add_template_test() (ask.Flask method),
179
add_url_rule() (ask.Blueprint method),
198
add_url_rule()
(ask.blueprints.BlueprintSetupState
method), 228
add_url_rule() (ask.Flask method), 179
after_app_request() (ask.Blueprint
method), 198
after_request() (ask.Blueprint method),
199
after_request() (ask.Flask method), 180
after_request_funcs (ask.Flask attribute),
180
after_this_request() (in module ask), 215
app (ask.blueprints.BlueprintSetupState
attribute), 228
app_context() (ask.Flask method), 180
app_context_processor() (ask.Blueprint
method), 199
app_ctx_globals_class (ask.Flask at-
tribute), 180
app_errorhandler() (ask.Blueprint
method), 199
app_template_lter() (ask.Blueprint
method), 199
app_template_global() (ask.Blueprint
method), 199
app_template_test() (ask.Blueprint
method), 199
app_url_defaults() (ask.Blueprint
method), 199
app_url_value_preprocessor()
(ask.Blueprint method), 199
AppContext (class in ask.ctx), 227
appcontext_popped (in module ask), 229
appcontext_pushed (in module ask), 229
appcontext_tearing_down (in module
ask), 229
args (ask.Request attribute), 202
as_view() (ask.views.View class
method), 230
auto_nd_instance_path() (ask.Flask
method), 180
B
base_url (ask.Request attribute), 203
before_app_rst_request()
(ask.Blueprint method), 199
before_app_request() (ask.Blueprint
method), 199
before_rst_request() (ask.Flask
method), 181
before_rst_request_funcs (ask.Flask at-
tribute), 181
before_request() (ask.Blueprint method),
199
before_request() (ask.Flask method), 181
291
before_request_funcs (ask.Flask at-
tribute), 181
Blueprint (class in ask), 198
blueprint (ask.blueprints.BlueprintSetupState
attribute), 228
blueprint (ask.Request attribute), 203
blueprints (ask.Flask attribute), 181
BlueprintSetupState (class in
ask.blueprints), 228
C
Cong (class in ask), 222
cong (ask.Flask attribute), 181
cong_class (ask.Flask attribute), 181
context_processor() (ask.Blueprint
method), 200
context_processor() (ask.Flask method),
181
cookies (ask.Request attribute), 202
copy() (ask.ctx.RequestContext method),
226
copy_current_request_context() (in mod-
ule ask), 212
create_global_jinja_loader() (ask.Flask
method), 181
create_jinja_environment() (ask.Flask
method), 182
create_url_adapter() (ask.Flask method),
182
current_app (in module ask), 211
D
data (ask.Request attribute), 203
data (ask.Response attribute), 205
debug (ask.Flask attribute), 182
debug_log_format (ask.Flask attribute),
182
decorators (ask.views.View attribute),
230
default() (ask.json.JSONEncoder
method), 221
default_cong (ask.Flask attribute), 182
digest_method()
(ask.sessions.SecureCookieSessionInterface
method), 209
dispatch_request() (ask.Flask method),
182
dispatch_request() (ask.views.View
method), 231
do_teardown_appcontext() (ask.Flask
method), 182
do_teardown_request() (ask.Flask
method), 183
dump() (in module ask.json), 221
dumps() (in module ask.json), 221
E
enable_modules (ask.Flask attribute),
183
endpoint (ask.Request attribute), 203
endpoint() (ask.Blueprint method), 200
endpoint() (ask.Flask method), 183
environ (ask.Request attribute), 203
environment variable
FLASKR_SETTINGS, 30
YOURAPPLICATION_SETTINGS, 62
error_handler_spec (ask.Flask attribute),
183
errorhandler() (ask.Blueprint method),
200
errorhandler() (ask.Flask method), 183
escape() (ask.Markup class method), 218
escape() (in module ask), 217
extensions (ask.Flask attribute), 184
F
les (ask.Request attribute), 203
rst_registration
(ask.blueprints.BlueprintSetupState
attribute), 228
ash() (in module ask), 218
Flask (class in ask), 177
ask (module), 177
ask.ext (in module ask), 225
ask.json (module), 219
ask.signals.Namespace (built-in class),
229
FlaskClient (class in ask.testing), 210
FLASKR_SETTINGS, 30
form (ask.Request attribute), 202
from_envvar() (ask.Cong method), 223
from_json() (ask.Cong method), 223
from_object() (ask.Cong method), 224
from_pyle() (ask.Cong method), 224
full_dispatch_request() (ask.Flask
method), 184
292
G
g (in module ask), 211
get_cookie_domain()
(ask.sessions.SessionInterface
method), 207
get_cookie_httponly()
(ask.sessions.SessionInterface
method), 207
get_cookie_path()
(ask.sessions.SessionInterface
method), 208
get_cookie_secure()
(ask.sessions.SessionInterface
method), 208
get_expiration_time()
(ask.sessions.SessionInterface
method), 208
get_ashed_messages() (in module ask),
219
get_json() (ask.Request method), 204
get_namespace() (ask.Cong method),
224
get_send_le_max_age() (ask.Blueprint
method), 200
get_send_le_max_age() (ask.Flask
method), 184
get_template_attribute() (in module
ask), 222
got_rst_request (ask.Flask attribute),
185
got_request_exception (in module ask),
229
H
handle_exception() (ask.Flask method),
185
handle_http_exception() (ask.Flask
method), 185
handle_url_build_error() (ask.Flask
method), 185
handle_user_exception() (ask.Flask
method), 185
has_app_context() (in module ask), 212
has_request_context() (in module ask),
211
has_static_folder (ask.Blueprint at-
tribute), 200
has_static_folder (ask.Flask attribute),
185
headers (ask.Request attribute), 202
headers (ask.Response attribute), 205
I
init_jinja_globals() (ask.Flask method),
185
inject_url_defaults() (ask.Flask method),
185
instance_path (ask.Flask attribute), 186
is_json (ask.Request attribute), 204
is_null_session()
(ask.sessions.SessionInterface
method), 208
is_xhr (ask.Request attribute), 203
J
jinja_env (ask.Flask attribute), 186
jinja_loader (ask.Blueprint attribute),
200
jinja_loader (ask.Flask attribute), 186
jinja_options (ask.Flask attribute), 186
json (ask.Request attribute), 204
json_decoder (ask.Flask attribute), 186
json_encoder (ask.Flask attribute), 186
JSONDecoder (class in ask.json), 221
JSONEncoder (class in ask.json), 221
jsonify() (in module ask.json), 220
K
key_derivation
(ask.sessions.SecureCookieSessionInterface
attribute), 209
L
load() (in module ask.json), 221
loads() (in module ask.json), 221
log_exception() (ask.Flask method), 186
logger (ask.Flask attribute), 186
logger_name (ask.Flask attribute), 186
M
make_cong() (ask.Flask method), 186
make_default_options_response()
(ask.Flask method), 187
make_null_session() (ask.Flask method),
187
293
make_null_session()
(ask.sessions.SessionInterface
method), 208
make_response() (ask.Flask method),
187
make_response() (in module ask), 214
make_setup_state() (ask.Blueprint
method), 200
Markup (class in ask), 217
match_request()
(ask.ctx.RequestContext
method), 227
max_content_length (ask.Request at-
tribute), 204
message_ashed (in module ask), 229
method (ask.Request attribute), 203
methods (ask.views.View attribute), 231
MethodView (class in ask.views), 231
mimetype (ask.Response attribute), 205
modied (ask.session attribute), 206
modied (ask.sessions.SessionMixin at-
tribute), 209
module (ask.Request attribute), 204
N
name (ask.Flask attribute), 187
new (ask.session attribute), 206
new (ask.sessions.SessionMixin at-
tribute), 209
null_session_class
(ask.sessions.SessionInterface
attribute), 208
NullSession (class in ask.sessions), 209
O
on_json_loading_failed() (ask.Request
method), 204
open_instance_resource() (ask.Flask
method), 187
open_resource() (ask.Blueprint method),
201
open_resource() (ask.Flask method), 188
open_session() (ask.Flask method), 188
open_session()
(ask.sessions.SessionInterface
method), 208
options (ask.blueprints.BlueprintSetupState
attribute), 228
P
path (ask.Request attribute), 203
permanent (ask.session attribute), 207
permanent (ask.sessions.SessionMixin
attribute), 210
permanent_session_lifetime (ask.Flask
attribute), 188
pickle_based
(ask.sessions.SessionInterface
attribute), 208
pop() (ask.ctx.AppContext method), 227
pop() (ask.ctx.RequestContext method),
227
preprocess_request() (ask.Flask
method), 188
preserve_context_on_exception
(ask.Flask attribute), 189
process_response() (ask.Flask method),
189
propagate_exceptions (ask.Flask at-
tribute), 189
push() (ask.ctx.AppContext method),
227
push() (ask.ctx.RequestContext
method), 227
Python Enhancement Proposals
PEP 8, 261
R
record() (ask.Blueprint method), 201
record_once() (ask.Blueprint method),
201
redirect() (in module ask), 214
register() (ask.Blueprint method), 201
register_blueprint() (ask.Flask method),
189
register_error_handler() (ask.Flask
method), 189
register_module() (ask.Flask method),
189
render_template() (in module ask), 222
render_template_string() (in module
ask), 222
Request (class in ask), 202
request (class in ask), 205
request_class (ask.Flask attribute), 189
request_context() (ask.Flask method),
190
294
request_nished (in module ask), 229
request_started (in module ask), 229
request_tearing_down (in module ask),
229
RequestContext (class in ask.ctx), 226
Response (class in ask), 205
response_class (ask.Flask attribute), 190
RFC
RFC 822, 220
route() (ask.Blueprint method), 201
route() (ask.Flask method), 190
routing_exception (ask.Request at-
tribute), 204
run() (ask.Flask method), 191
S
safe_join() (in module ask), 217
salt (ask.sessions.SecureCookieSessionInterface
attribute), 209
save_session() (ask.Flask method), 191
save_session()
(ask.sessions.SessionInterface
method), 208
script_root (ask.Request attribute), 203
secret_key (ask.Flask attribute), 191
SecureCookieSession (class in
ask.sessions), 209
SecureCookieSessionInterface (class in
ask.sessions), 209
select_jinja_autoescape() (ask.Flask
method), 192
send_le() (in module ask), 215
send_from_directory() (in module ask),
216
send_static_le() (ask.Blueprint
method), 201
send_static_le() (ask.Flask method),
192
serializer (ask.sessions.SecureCookieSessionInterface
attribute), 209
session (class in ask), 206
session_class
(ask.sessions.SecureCookieSessionInterface
attribute), 209
session_cookie_name (ask.Flask at-
tribute), 192
session_interface (ask.Flask attribute),
192
session_json_serializer (in module
ask.sessions), 210
session_transaction()
(ask.testing.FlaskClient method),
210
SessionInterface (class in ask.sessions),
207
SessionMixin (class in ask.sessions), 209
set_cookie() (ask.Response method), 206
should_ignore_error() (ask.Flask
method), 192
should_set_cookie()
(ask.sessions.SessionInterface
method), 209
signal() (ask.signals.Namespace
method), 229
signals_available (in module ask), 228
status (ask.Response attribute), 205
status_code (ask.Response attribute),
205
stream (ask.Request attribute), 202
stream_with_context() (in module ask),
225
striptags() (ask.Markup method), 218
subdomain (ask.blueprints.BlueprintSetupState
attribute), 228
T
teardown_app_request() (ask.Blueprint
method), 202
teardown_appcontext() (ask.Flask
method), 192
teardown_appcontext_funcs (ask.Flask
attribute), 193
teardown_request() (ask.Blueprint
method), 202
teardown_request() (ask.Flask method),
193
teardown_request_funcs (ask.Flask at-
tribute), 193
template_context_processors (ask.Flask
attribute), 193
template_lter() (ask.Flask method), 194
template_global() (ask.Flask method),
194
template_rendered (in module ask), 228
template_test() (ask.Flask method), 194
test_client() (ask.Flask method), 194
295
test_client_class (ask.Flask attribute),
195
test_request_context() (ask.Flask
method), 195
testing (ask.Flask attribute), 195
trap_http_exception() (ask.Flask
method), 195
U
unescape() (ask.Markup method), 218
update_template_context() (ask.Flask
method), 196
url (ask.Request attribute), 203
url_build_error_handlers (ask.Flask at-
tribute), 196
url_default_functions (ask.Flask at-
tribute), 196
url_defaults (ask.blueprints.BlueprintSetupState
attribute), 228
url_defaults() (ask.Blueprint method),
202
url_defaults() (ask.Flask method), 196
url_for() (in module ask), 212
url_map (ask.Flask attribute), 196
url_prex (ask.blueprints.BlueprintSetupState
attribute), 228
url_root (ask.Request attribute), 203
url_rule (ask.Request attribute), 205
url_rule_class (ask.Flask attribute), 196
url_value_preprocessor() (ask.Blueprint
method), 202
url_value_preprocessor() (ask.Flask
method), 197
url_value_preprocessors (ask.Flask at-
tribute), 197
use_x_sendle (ask.Flask attribute), 197
V
values (ask.Request attribute), 202
View (class in ask.views), 230
view_args (ask.Request attribute), 205
view_functions (ask.Flask attribute), 197
W
wsgi_app() (ask.Flask method), 197
Y
YOURAPPLICATION_SETTINGS, 62
296