-
-
Notifications
You must be signed in to change notification settings - Fork 16.2k
/
api.rst
722 lines (488 loc) · 21.3 KB
/
api.rst
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
API
===
.. module:: flask
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.
Application Object
------------------
.. autoclass:: Flask
:members:
:inherited-members:
Blueprint Objects
-----------------
.. autoclass:: Blueprint
:members:
:inherited-members:
Incoming Request Data
---------------------
.. autoclass:: Request
:members:
:inherited-members:
:exclude-members: json_module
.. attribute:: 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 :ref:`notes-on-proxies` for more information.
The request object is an instance of a :class:`~flask.Request`.
Response Objects
----------------
.. autoclass:: flask.Response
:members:
:inherited-members:
:exclude-members: json_module
Sessions
--------
If you have set :attr:`Flask.secret_key` (or configured it from
:data:`SECRET_KEY`) you can use sessions in Flask applications. A session makes
it possible to remember information from one request to another. The way Flask
does this is by using a signed cookie. The user can look at the session
contents, but can't 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 :class:`session` object:
.. class:: session
The session object works pretty much like an ordinary dict, with the
difference that it keeps track of modifications.
This is a proxy. See :ref:`notes-on-proxies` for more information.
The following attributes are interesting:
.. attribute:: new
``True`` if the session is new, ``False`` otherwise.
.. attribute:: modified
``True`` if the session object detected a modification. Be advised
that modifications 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
.. attribute:: permanent
If set to ``True`` the session lives for
:attr:`~flask.Flask.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.
Session Interface
-----------------
.. versionadded:: 0.8
The session interface provides a simple way to replace the session
implementation that Flask is using.
.. currentmodule:: flask.sessions
.. autoclass:: SessionInterface
:members:
.. autoclass:: SecureCookieSessionInterface
:members:
.. autoclass:: SecureCookieSession
:members:
.. autoclass:: NullSession
:members:
.. autoclass:: SessionMixin
:members:
.. admonition:: Notice
The :data:`PERMANENT_SESSION_LIFETIME` config can be an integer or ``timedelta``.
The :attr:`~flask.Flask.permanent_session_lifetime` attribute is always a
``timedelta``.
Test Client
-----------
.. currentmodule:: flask.testing
.. autoclass:: FlaskClient
:members:
Test CLI Runner
---------------
.. currentmodule:: flask.testing
.. autoclass:: FlaskCliRunner
:members:
Application Globals
-------------------
.. currentmodule:: flask
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 :class:`request` and :class:`session`.
.. data:: g
A namespace object that can store data during an
:doc:`application context </appcontext>`. This is an instance of
:attr:`Flask.app_ctx_globals_class`, which defaults to
:class:`ctx._AppCtxGlobals`.
This is a good place to store resources during a request. For
example, a ``before_request`` function could load a user object from
a session id, then set ``g.user`` to be used in the view function.
This is a proxy. See :ref:`notes-on-proxies` for more information.
.. versionchanged:: 0.10
Bound to the application context instead of the request context.
.. autoclass:: flask.ctx._AppCtxGlobals
:members:
Useful Functions and Classes
----------------------------
.. data:: current_app
A proxy to the application handling the current request. This is
useful to access the application without needing to import it, or if
it can't be imported, such as when using the application factory
pattern or in blueprints and extensions.
This is only available when an
:doc:`application context </appcontext>` is pushed. This happens
automatically during requests and CLI commands. It can be controlled
manually with :meth:`~flask.Flask.app_context`.
This is a proxy. See :ref:`notes-on-proxies` for more information.
.. autofunction:: has_request_context
.. autofunction:: copy_current_request_context
.. autofunction:: has_app_context
.. autofunction:: url_for
.. autofunction:: abort
.. autofunction:: redirect
.. autofunction:: make_response
.. autofunction:: after_this_request
.. autofunction:: send_file
.. autofunction:: send_from_directory
Message Flashing
----------------
.. autofunction:: flash
.. autofunction:: get_flashed_messages
JSON Support
------------
.. module:: flask.json
Flask uses Python's built-in :mod:`json` module for handling JSON by
default. The JSON implementation can be changed by assigning a different
provider to :attr:`flask.Flask.json_provider_class` or
:attr:`flask.Flask.json`. The functions provided by ``flask.json`` will
use methods on ``app.json`` if an app context is active.
Jinja's ``|tojson`` filter is configured to use the app's JSON provider.
The filter marks the output with ``|safe``. Use it to render data inside
HTML ``<script>`` tags.
.. sourcecode:: html+jinja
<script>
const names = {{ names|tojson }};
renderChart(names, {{ axis_data|tojson }});
</script>
.. autofunction:: jsonify
.. autofunction:: dumps
.. autofunction:: dump
.. autofunction:: loads
.. autofunction:: load
.. autoclass:: flask.json.provider.JSONProvider
:members:
:member-order: bysource
.. autoclass:: flask.json.provider.DefaultJSONProvider
:members:
:member-order: bysource
.. automodule:: flask.json.tag
Template Rendering
------------------
.. currentmodule:: flask
.. autofunction:: render_template
.. autofunction:: render_template_string
.. autofunction:: stream_template
.. autofunction:: stream_template_string
.. autofunction:: get_template_attribute
Configuration
-------------
.. autoclass:: Config
:members:
Stream Helpers
--------------
.. autofunction:: stream_with_context
Useful Internals
----------------
.. autoclass:: flask.ctx.RequestContext
:members:
.. data:: flask.globals.request_ctx
The current :class:`~flask.ctx.RequestContext`. If a request context
is not active, accessing attributes on this proxy will raise a
``RuntimeError``.
This is an internal object that is essential to how Flask handles
requests. Accessing this should not be needed in most cases. Most
likely you want :data:`request` and :data:`session` instead.
.. autoclass:: flask.ctx.AppContext
:members:
.. data:: flask.globals.app_ctx
The current :class:`~flask.ctx.AppContext`. If an app context is not
active, accessing attributes on this proxy will raise a
``RuntimeError``.
This is an internal object that is essential to how Flask handles
requests. Accessing this should not be needed in most cases. Most
likely you want :data:`current_app` and :data:`g` instead.
.. autoclass:: flask.blueprints.BlueprintSetupState
:members:
.. _core-signals-list:
Signals
-------
Signals are provided by the `Blinker`_ library. See :doc:`signals` for an introduction.
.. _blinker: https://blinker.readthedocs.io/
.. data:: template_rendered
This signal is sent when a template was successfully rendered. The
signal is invoked 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)
.. data:: flask.before_render_template
:noindex:
This signal is sent before template rendering process. The
signal is invoked 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 before_render_template
before_render_template.connect(log_template_renders, app)
.. data:: request_started
This signal is sent when the request context is set up, before
any request processing happens. Because the request context is already
bound, the subscriber can access the request with the standard global
proxies such as :class:`~flask.request`.
Example subscriber::
def log_request(sender, **extra):
sender.logger.debug('Request context is set up')
from flask import request_started
request_started.connect(log_request, app)
.. data:: 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)
.. data:: got_request_exception
This signal is sent when an unhandled exception happens during
request processing, including when debugging. The exception is
passed to the subscriber as ``exception``.
This signal is not sent for
:exc:`~werkzeug.exceptions.HTTPException`, or other exceptions that
have error handlers registered, unless the exception was raised from
an error handler.
This example shows how to do some extra logging if a theoretical
``SecurityException`` was raised:
.. code-block:: python
from flask import got_request_exception
def log_security_exception(sender, exception, **extra):
if not isinstance(exception, SecurityException):
return
security_logger.exception(
f"SecurityException at {request.url!r}",
exc_info=exception,
)
got_request_exception.connect(log_security_exception, app)
.. data:: 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.
.. data:: 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::
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.
.. data:: 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'
.. versionadded:: 0.10
.. data:: appcontext_popped
This signal is sent when an application context is popped. The sender
is the application. This usually falls in line with the
:data:`appcontext_tearing_down` signal.
.. versionadded:: 0.10
.. data:: message_flashed
This signal is sent when the application is flashing 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)
.. versionadded:: 0.10
.. data:: signals.signals_available
.. deprecated:: 2.3
Will be removed in Flask 2.4. Signals are always available
Class-Based Views
-----------------
.. versionadded:: 0.7
.. currentmodule:: None
.. autoclass:: flask.views.View
:members:
.. autoclass:: flask.views.MethodView
:members:
.. _url-route-registrations:
URL Route Registrations
-----------------------
Generally there are three ways to define rules for the routing system:
1. You can use the :meth:`flask.Flask.route` decorator.
2. You can use the :meth:`flask.Flask.add_url_rule` function.
3. You can directly access the underlying Werkzeug routing system
which is exposed as :attr:`flask.Flask.url_map`.
Variable parts in the route can be specified 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 specified 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
`float` like `int` but for floating point values
`path` like the default but also accepts slashes
`any` matches one of the items provided
`uuid` accepts UUID strings
=========== ===============================================
Custom converters can be defined using :attr:`flask.Flask.url_map`.
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 files. This
also makes it possible to use relative link targets safely.
You can also define multiple rules for the same function. They have to be
unique however. Defaults can also be specified. Here for example is a
definition 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 specifies that ``/users/`` will be the URL for page one and
``/users/page/N`` will be the URL for page ``N``.
If a URL contains a default value, it will be redirected to its simpler
form with a 301 redirect. In the above example, ``/users/page/1`` will
be redirected to ``/users/``. If your route handles ``GET`` and ``POST``
requests, make sure the default route only handles ``GET``, as redirects
can't preserve form data. ::
@app.route('/region/', defaults={'id': 1})
@app.route('/region/<int:id>', methods=['GET', 'POST'])
def region(id):
pass
Here are the parameters that :meth:`~flask.Flask.route` and
:meth:`~flask.Flask.add_url_rule` accept. The only difference is that
with the route parameter the view function is defined with the decorator
instead of the `view_func` parameter.
=============== ==========================================================
`rule` the URL rule as string
`endpoint` 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
:attr:`~flask.Flask.view_functions` dictionary with the
endpoint as key.
`defaults` A dictionary with defaults for this rule. See the
example above for how defaults work.
`subdomain` specifies the rule for the subdomain in case subdomain
matching is in use. If not specified the default
subdomain is assumed.
`**options` the options to be forwarded to the underlying
:class:`~werkzeug.routing.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 specified as keyword arguments.
=============== ==========================================================
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 attributes can be provided optionally to either override
some defaults to :meth:`~flask.Flask.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 prefixed 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 if a `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
...
return 'Hello World!'
index.provide_automatic_options = False
index.methods = ['GET', 'OPTIONS']
app.add_url_rule('/', index)
.. versionadded:: 0.8
The `provide_automatic_options` functionality was added.
Command Line Interface
----------------------
.. currentmodule:: flask.cli
.. autoclass:: FlaskGroup
:members:
.. autoclass:: AppGroup
:members:
.. autoclass:: ScriptInfo
:members:
.. autofunction:: load_dotenv
.. autofunction:: with_appcontext
.. autofunction:: pass_script_info
Marks a function so that an instance of :class:`ScriptInfo` is passed
as first argument to the click callback.
.. autodata:: run_command
.. autodata:: shell_command