0
# Flask
1
2
A lightweight WSGI web application framework designed to make getting started quick and easy, with the ability to scale up to complex applications. Flask offers suggestions but doesn't enforce any dependencies or project layout, giving developers the freedom to choose their tools and libraries, with many community extensions available for adding new functionality.
3
4
## Package Information
5
6
- **Package Name**: Flask
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install flask`
10
11
## Core Imports
12
13
```python
14
from flask import Flask
15
```
16
17
Common imports for web development:
18
19
```python
20
from flask import (
21
Flask, request, session, g, redirect, url_for,
22
abort, render_template, flash, jsonify, make_response
23
)
24
```
25
26
## Basic Usage
27
28
```python
29
from flask import Flask, render_template, request, jsonify
30
31
# Create Flask application
32
app = Flask(__name__)
33
app.secret_key = 'your-secret-key'
34
35
# Simple route
36
@app.route('/')
37
def home():
38
return 'Hello, Flask!'
39
40
# Route with parameters
41
@app.route('/user/<name>')
42
def user_profile(name):
43
return f'User: {name}'
44
45
# Handle different HTTP methods
46
@app.route('/api/data', methods=['GET', 'POST'])
47
def api_data():
48
if request.method == 'POST':
49
data = request.get_json()
50
return jsonify({'status': 'created', 'data': data}), 201
51
else:
52
return jsonify({'message': 'Hello from API'})
53
54
# Template rendering
55
@app.route('/hello/<name>')
56
def hello(name):
57
return render_template('hello.html', name=name)
58
59
# Run the application
60
if __name__ == '__main__':
61
app.run(debug=True)
62
```
63
64
## Architecture
65
66
Flask follows the WSGI specification and provides a minimalist foundation that can be extended:
67
68
- **Application Object**: Central registry for views, URL rules, template configuration
69
- **Request Context**: Per-request data (request, session, g) available during request processing
70
- **Application Context**: Application-level data available during request processing and CLI commands
71
- **Blueprints**: Modular applications that can be registered with the main app
72
- **Extensions**: Third-party packages that extend Flask functionality
73
74
Flask's design philosophy emphasizes simplicity and flexibility, allowing developers to choose their preferred tools for databases, authentication, form validation, and other common web development tasks.
75
76
## Capabilities
77
78
### Core Application
79
80
The Flask application class and core functionality for creating WSGI applications, handling routing, and managing the request-response cycle.
81
82
```python { .api }
83
class Flask:
84
def __init__(
85
self,
86
import_name: str,
87
static_url_path: str | None = None,
88
static_folder: str | os.PathLike[str] | None = "static",
89
static_host: str | None = None,
90
host_matching: bool = False,
91
subdomain_matching: bool = False,
92
template_folder: str | os.PathLike[str] | None = "templates",
93
instance_path: str | None = None,
94
instance_relative_config: bool = False,
95
root_path: str | None = None,
96
): ...
97
98
def run(
99
self,
100
host: str | None = None,
101
port: int | None = None,
102
debug: bool | None = None,
103
load_dotenv: bool = True,
104
**options: Any
105
) -> None: ...
106
107
def test_client(self, use_cookies: bool = True, **kwargs) -> FlaskClient: ...
108
```
109
110
[Core Application](./core-application.md)
111
112
### Routing and URL Handling
113
114
URL routing, endpoint registration, and URL generation functionality for mapping URLs to view functions and generating URLs from endpoints.
115
116
```python { .api }
117
def route(self, rule: str, **options) -> Callable: ...
118
def add_url_rule(
119
self,
120
rule: str,
121
endpoint: str | None = None,
122
view_func: Callable | None = None,
123
provide_automatic_options: bool | None = None,
124
**options: Any
125
) -> None: ...
126
def url_for(
127
endpoint: str,
128
*,
129
_anchor: str | None = None,
130
_method: str | None = None,
131
_scheme: str | None = None,
132
_external: bool | None = None,
133
**values: Any,
134
) -> str: ...
135
```
136
137
[Routing](./routing.md)
138
139
### Request and Response Handling
140
141
Request and response objects for handling HTTP data, along with utilities for creating responses and handling request data.
142
143
```python { .api }
144
class Request:
145
method: str
146
url: str
147
base_url: str
148
url_root: str
149
path: str
150
query_string: bytes
151
args: ImmutableMultiDict
152
form: ImmutableMultiDict
153
files: ImmutableMultiDict
154
values: ImmutableMultiDict
155
json: Any
156
headers: EnvironHeaders
157
cookies: ImmutableMultiDict
158
159
def get_json(self, force: bool = False, silent: bool = False, cache: bool = True): ...
160
161
class Response:
162
def __init__(
163
self,
164
response=None,
165
status=None,
166
headers=None,
167
mimetype=None,
168
content_type=None,
169
direct_passthrough=False
170
): ...
171
```
172
173
[Request Response](./request-response.md)
174
175
### Templates and Rendering
176
177
Template rendering using Jinja2, including template loading, context processing, and streaming templates.
178
179
```python { .api }
180
def render_template(template_name_or_list: str, **context) -> str: ...
181
def render_template_string(source: str, **context) -> str: ...
182
def stream_template(template_name_or_list: str, **context) -> Iterator[str]: ...
183
def stream_template_string(source: str, **context) -> Iterator[str]: ...
184
```
185
186
[Templates](./templates.md)
187
188
### Application Context and Globals
189
190
Context management and global objects available during request processing, including application context, request context, and proxy objects.
191
192
```python { .api }
193
def has_app_context() -> bool: ...
194
def has_request_context() -> bool: ...
195
def copy_current_request_context(f: Callable) -> Callable: ...
196
def after_this_request(f: Callable) -> Callable: ...
197
198
# Global proxy objects
199
current_app: LocalProxy
200
request: LocalProxy
201
session: LocalProxy
202
g: LocalProxy
203
```
204
205
[Context and Globals](./context-globals.md)
206
207
### Helpers and Utilities
208
209
Utility functions for common web development tasks including redirects, aborts, file sending, and message flashing.
210
211
```python { .api }
212
def redirect(location: str, code: int = 302) -> Response: ...
213
def abort(code: int | Response, *args, **kwargs) -> NoReturn: ...
214
def flash(message: str, category: str = "message") -> None: ...
215
def get_flashed_messages(
216
with_categories: bool = False,
217
category_filter: list = []
218
) -> list: ...
219
def send_file(
220
path_or_file: os.PathLike | str | IO[bytes],
221
mimetype: str | None = None,
222
as_attachment: bool = False,
223
download_name: str | None = None,
224
conditional: bool = True,
225
etag: bool | str = True,
226
last_modified: datetime | int | float | None = None,
227
max_age: int | Callable[[str | None], int | None] | None = None
228
) -> Response: ...
229
def send_from_directory(directory: str, path: str, **kwargs) -> Response: ...
230
```
231
232
[Helpers](./helpers.md)
233
234
### JSON Support
235
236
JSON serialization and deserialization functionality with Flask-specific enhancements and response creation.
237
238
```python { .api }
239
def jsonify(*args, **kwargs) -> Response: ...
240
def dumps(obj, **kwargs) -> str: ...
241
def loads(s: str | bytes, **kwargs): ...
242
def dump(obj, fp, **kwargs) -> None: ...
243
def load(fp, **kwargs): ...
244
```
245
246
[JSON Support](./json-support.md)
247
248
### Blueprints
249
250
Modular application components that allow organizing related functionality and can be registered with Flask applications.
251
252
```python { .api }
253
class Blueprint:
254
def __init__(
255
self,
256
name: str,
257
import_name: str,
258
static_folder: str | None = None,
259
static_url_path: str | None = None,
260
template_folder: str | None = None,
261
url_prefix: str | None = None,
262
subdomain: str | None = None,
263
url_defaults: dict | None = None,
264
root_path: str | None = None,
265
cli_group: str | None = None,
266
): ...
267
268
def route(self, rule: str, **options) -> Callable: ...
269
```
270
271
[Blueprints](./blueprints.md)
272
273
### Configuration Management
274
275
Application configuration system for managing settings, loading configuration from various sources, and environment-based configuration.
276
277
```python { .api }
278
class Config(dict):
279
def from_envvar(self, variable_name: str, silent: bool = False) -> bool: ...
280
def from_file(self, filename: str, load: Callable = None, silent: bool = False) -> bool: ...
281
def from_object(self, obj) -> None: ...
282
def from_prefixed_env(self, prefix: str = "FLASK", *, loads: Callable = None) -> bool: ...
283
def get_namespace(self, namespace: str, lowercase: bool = True, trim_namespace: bool = True) -> dict: ...
284
```
285
286
[Configuration](./configuration.md)
287
288
### Session Management
289
290
Session handling for maintaining user state across requests, including secure cookie sessions and custom session interfaces.
291
292
```python { .api }
293
class SessionInterface:
294
def get_cookie_name(self, app: Flask) -> str: ...
295
def get_cookie_domain(self, app: Flask) -> str | None: ...
296
def should_set_cookie(self, app: Flask, session) -> bool: ...
297
def open_session(self, app: Flask, request: Request): ...
298
def save_session(self, app: Flask, session, response: Response) -> None: ...
299
300
class SecureCookieSessionInterface(SessionInterface): ...
301
```
302
303
[Sessions](./sessions.md)
304
305
### Testing Support
306
307
Testing utilities including test client for making requests and CLI runner for testing command-line interfaces.
308
309
```python { .api }
310
class FlaskClient:
311
def get(self, *args, **kwargs) -> TestResponse: ...
312
def post(self, *args, **kwargs) -> TestResponse: ...
313
def put(self, *args, **kwargs) -> TestResponse: ...
314
def delete(self, *args, **kwargs) -> TestResponse: ...
315
def patch(self, *args, **kwargs) -> TestResponse: ...
316
def head(self, *args, **kwargs) -> TestResponse: ...
317
def options(self, *args, **kwargs) -> TestResponse: ...
318
def trace(self, *args, **kwargs) -> TestResponse: ...
319
320
class FlaskCliRunner:
321
def invoke(self, cli, args=None, input=None, env=None, **extra): ...
322
```
323
324
[Testing](./testing.md)
325
326
### Signals
327
328
Event system for hooking into Flask's request processing lifecycle and application events.
329
330
```python { .api }
331
# Signal objects (instances of blinker.base.NamedSignal)
332
template_rendered: NamedSignal
333
before_render_template: NamedSignal
334
request_started: NamedSignal
335
request_finished: NamedSignal
336
request_tearing_down: NamedSignal
337
got_request_exception: NamedSignal
338
appcontext_tearing_down: NamedSignal
339
appcontext_pushed: NamedSignal
340
appcontext_popped: NamedSignal
341
message_flashed: NamedSignal
342
```
343
344
[Signals](./signals.md)
345
346
### Command Line Interface
347
348
CLI system for creating custom commands and managing Flask applications from the command line.
349
350
```python { .api }
351
def with_appcontext(f: Callable) -> Callable: ...
352
def load_dotenv(path: str | None = None) -> bool: ...
353
354
class FlaskGroup(click.Group): ...
355
class AppGroup(click.Group): ...
356
```
357
358
[CLI](./cli.md)
359
360
## Types
361
362
```python { .api }
363
from typing import Any, Callable, Iterator, Union, IO
364
import os
365
from datetime import datetime
366
from werkzeug.wrappers import Response as BaseResponse
367
from werkzeug.datastructures import ImmutableMultiDict, EnvironHeaders
368
from werkzeug.local import LocalProxy
369
370
# Type aliases for return values
371
ResponseReturnValue = Union[
372
Response,
373
BaseResponse,
374
str,
375
bytes,
376
list,
377
dict,
378
tuple,
379
Iterator
380
]
381
382
StatusCode = Union[int, str]
383
HeadersValue = Union[dict, list, tuple]
384
```