doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
classmatplotlib.widgets.Button(ax, label, image=None, color='0.85', hovercolor='0.95')[source] Bases: matplotlib.widgets.AxesWidget A GUI neutral button. For the button to remain responsive you must keep a reference to it. Call on_clicked to connect to the button. Attributes ax The matplotlib.axes.Axes the button renders into. label A matplotlib.text.Text instance. color The color of the button when not hovering. hovercolor The color of the button when hovering. Parameters axAxes The Axes instance the button will be placed into. labelstr The button text. imagearray-like or PIL Image The image to place in the button, if not None. The parameter is directly forwarded to imshow. colorcolor The color of the button when not activated. hovercolorcolor The color of the button when the mouse is over it. propertycnt[source] disconnect(cid)[source] Remove the callback function with connection id cid. propertyobservers[source] on_clicked(func)[source] Connect the callback function func to button click events. Returns a connection id, which can be used to disconnect the callback.
matplotlib.widgets_api#matplotlib.widgets.Button
disconnect(cid)[source] Remove the callback function with connection id cid.
matplotlib.widgets_api#matplotlib.widgets.Button.disconnect
on_clicked(func)[source] Connect the callback function func to button click events. Returns a connection id, which can be used to disconnect the callback.
matplotlib.widgets_api#matplotlib.widgets.Button.on_clicked
classmatplotlib.widgets.CheckButtons(ax, labels, actives=None)[source] Bases: matplotlib.widgets.AxesWidget A GUI neutral set of check buttons. For the check buttons to remain responsive you must keep a reference to this object. Connect to the CheckButtons with the on_clicked method. Attributes axAxes The parent axes for the widget. labelslist of Text rectangleslist of Rectangle lineslist of (Line2D, Line2D) pairs List of lines for the x's in the check boxes. These lines exist for each box, but have set_visible(False) when its box is not checked. Add check buttons to matplotlib.axes.Axes instance ax. Parameters axAxes The parent axes for the widget. labelslist of str The labels of the check buttons. activeslist of bool, optional The initial check states of the buttons. The list must have the same length as labels. If not given, all buttons are unchecked. propertycnt[source] disconnect(cid)[source] Remove the observer with connection id cid. get_status()[source] Return a tuple of the status (True/False) of all of the check buttons. propertyobservers[source] on_clicked(func)[source] Connect the callback function func to button click events. Returns a connection id, which can be used to disconnect the callback. set_active(index)[source] Toggle (activate or deactivate) a check button by index. Callbacks will be triggered if eventson is True. Parameters indexint Index of the check button to toggle. Raises ValueError If index is invalid.
matplotlib.widgets_api#matplotlib.widgets.CheckButtons
disconnect(cid)[source] Remove the observer with connection id cid.
matplotlib.widgets_api#matplotlib.widgets.CheckButtons.disconnect
get_status()[source] Return a tuple of the status (True/False) of all of the check buttons.
matplotlib.widgets_api#matplotlib.widgets.CheckButtons.get_status
on_clicked(func)[source] Connect the callback function func to button click events. Returns a connection id, which can be used to disconnect the callback.
matplotlib.widgets_api#matplotlib.widgets.CheckButtons.on_clicked
set_active(index)[source] Toggle (activate or deactivate) a check button by index. Callbacks will be triggered if eventson is True. Parameters indexint Index of the check button to toggle. Raises ValueError If index is invalid.
matplotlib.widgets_api#matplotlib.widgets.CheckButtons.set_active
classmatplotlib.widgets.Cursor(ax, horizOn=True, vertOn=True, useblit=False, **lineprops)[source] Bases: matplotlib.widgets.AxesWidget A crosshair cursor that spans the axes and moves with mouse cursor. For the cursor to remain responsive you must keep a reference to it. Parameters axmatplotlib.axes.Axes The Axes to attach the cursor to. horizOnbool, default: True Whether to draw the horizontal line. vertOnbool, default: True Whether to draw the vertical line. useblitbool, default: False Use blitting for faster drawing if supported by the backend. Other Parameters **lineprops Line2D properties that control the appearance of the lines. See also axhline. Examples See Cursor. clear(event)[source] Internal event handler to clear the cursor. onmove(event)[source] Internal event handler to draw the cursor when the mouse moves.
matplotlib.widgets_api#matplotlib.widgets.Cursor
clear(event)[source] Internal event handler to clear the cursor.
matplotlib.widgets_api#matplotlib.widgets.Cursor.clear
onmove(event)[source] Internal event handler to draw the cursor when the mouse moves.
matplotlib.widgets_api#matplotlib.widgets.Cursor.onmove
classmatplotlib.widgets.EllipseSelector(ax, onselect, drawtype=<deprecated parameter>, minspanx=0, minspany=0, useblit=False, lineprops=<deprecated parameter>, props=None, spancoords='data', button=None, grab_range=10, handle_props=None, interactive=False, state_modifier_keys=None, drag_from_anywhere=False, ignore_event_outside=False)[source] Bases: matplotlib.widgets.RectangleSelector Select an elliptical region of an axes. For the cursor to remain responsive you must keep a reference to it. Press and release events triggered at the same coordinates outside the selection will clear the selector, except when ignore_event_outside=True. Parameters axAxes The parent axes for the widget. onselectfunction A callback function that is called after a release event and the selection is created, changed or removed. It must have the signature: def onselect(eclick: MouseEvent, erelease: MouseEvent) where eclick and erelease are the mouse click and release MouseEvents that start and complete the selection. minspanxfloat, default: 0 Selections with an x-span less than or equal to minspanx are removed (when already existing) or cancelled. minspanyfloat, default: 0 Selections with an y-span less than or equal to minspanx are removed (when already existing) or cancelled. useblitbool, default: False Whether to use blitting for faster drawing (if supported by the backend). propsdict, optional Properties with which the ellipse is drawn. See matplotlib.patches.Patch for valid properties. Default: dict(facecolor='red', edgecolor='black', alpha=0.2, fill=True) spancoords{"data", "pixels"}, default: "data" Whether to interpret minspanx and minspany in data or in pixel coordinates. buttonMouseButton, list of MouseButton, default: all buttons Button(s) that trigger rectangle selection. grab_rangefloat, default: 10 Distance in pixels within which the interactive tool handles can be activated. handle_propsdict, optional Properties with which the interactive handles (marker artists) are drawn. See the marker arguments in matplotlib.lines.Line2D for valid properties. Default values are defined in mpl.rcParams except for the default value of markeredgecolor which will be the same as the edgecolor property in props. interactivebool, default: False Whether to draw a set of handles that allow interaction with the widget after it is drawn. state_modifier_keysdict, optional Keyboard modifiers which affect the widget's behavior. Values amend the defaults. "move": Move the existing shape, default: no modifier. "clear": Clear the current shape, default: "escape". "square": Make the shape square, default: "shift". "center": Make the initial point the center of the shape, default: "ctrl". "square" and "center" can be combined. drag_from_anywherebool, default: False If True, the widget can be moved by clicking anywhere within its bounds. ignore_event_outsidebool, default: False If True, the event triggered outside the span selector will be ignored. Examples Rectangle and ellipse selectors propertydraw_shape[source]
matplotlib.widgets_api#matplotlib.widgets.EllipseSelector
classmatplotlib.widgets.Lasso(ax, xy, callback=None, useblit=True)[source] Bases: matplotlib.widgets.AxesWidget Selection curve of an arbitrary shape. The selected path can be used in conjunction with contains_point to select data points from an image. Unlike LassoSelector, this must be initialized with a starting point xy, and the Lasso events are destroyed upon release. Parameters axAxes The parent axes for the widget. xy(float, float) Coordinates of the start of the lasso. useblitbool, default: True Whether to use blitting for faster drawing (if supported by the backend). callbackcallable Whenever the lasso is released, the callback function is called and passed the vertices of the selected path. onmove(event)[source] onrelease(event)[source]
matplotlib.widgets_api#matplotlib.widgets.Lasso
onmove(event)[source]
matplotlib.widgets_api#matplotlib.widgets.Lasso.onmove
onrelease(event)[source]
matplotlib.widgets_api#matplotlib.widgets.Lasso.onrelease
classmatplotlib.widgets.LassoSelector(ax, onselect=None, useblit=True, props=None, button=None)[source] Bases: matplotlib.widgets._SelectorWidget Selection curve of an arbitrary shape. For the selector to remain responsive you must keep a reference to it. The selected path can be used in conjunction with contains_point to select data points from an image. In contrast to Lasso, LassoSelector is written with an interface similar to RectangleSelector and SpanSelector, and will continue to interact with the axes until disconnected. Example usage: ax = plt.subplot() ax.plot(x, y) def onselect(verts): print(verts) lasso = LassoSelector(ax, onselect) Parameters axAxes The parent axes for the widget. onselectfunction Whenever the lasso is released, the onselect function is called and passed the vertices of the selected path. useblitbool, default: True Whether to use blitting for faster drawing (if supported by the backend). propsdict, optional Properties with which the line is drawn, see matplotlib.lines.Line2D for valid properties. Default values are defined in mpl.rcParams. buttonMouseButton or list of MouseButton, optional The mouse buttons used for rectangle selection. Default is None, which corresponds to all buttons. onpress(event)[source] [Deprecated] Notes Deprecated since version 3.5: onrelease(event)[source] [Deprecated] Notes Deprecated since version 3.5:
matplotlib.widgets_api#matplotlib.widgets.LassoSelector
onpress(event)[source] [Deprecated] Notes Deprecated since version 3.5:
matplotlib.widgets_api#matplotlib.widgets.LassoSelector.onpress
onrelease(event)[source] [Deprecated] Notes Deprecated since version 3.5:
matplotlib.widgets_api#matplotlib.widgets.LassoSelector.onrelease
classmatplotlib.widgets.LockDraw[source] Bases: object Some widgets, like the cursor, draw onto the canvas, and this is not desirable under all circumstances, like when the toolbar is in zoom-to-rect mode and drawing a rectangle. To avoid this, a widget can acquire a canvas' lock with canvas.widgetlock(widget) before drawing on the canvas; this will prevent other widgets from doing so at the same time (if they also try to acquire the lock first). available(o)[source] Return whether drawing is available to o. isowner(o)[source] Return whether o owns this lock. locked()[source] Return whether the lock is currently held by an owner. release(o)[source] Release the lock from o.
matplotlib.widgets_api#matplotlib.widgets.LockDraw
available(o)[source] Return whether drawing is available to o.
matplotlib.widgets_api#matplotlib.widgets.LockDraw.available
isowner(o)[source] Return whether o owns this lock.
matplotlib.widgets_api#matplotlib.widgets.LockDraw.isowner
locked()[source] Return whether the lock is currently held by an owner.
matplotlib.widgets_api#matplotlib.widgets.LockDraw.locked
release(o)[source] Release the lock from o.
matplotlib.widgets_api#matplotlib.widgets.LockDraw.release
classmatplotlib.widgets.MultiCursor(canvas, axes, useblit=True, horizOn=False, vertOn=True, **lineprops)[source] Bases: matplotlib.widgets.Widget Provide a vertical (default) and/or horizontal line cursor shared between multiple axes. For the cursor to remain responsive you must keep a reference to it. Parameters canvasmatplotlib.backend_bases.FigureCanvasBase The FigureCanvas that contains all the axes. axeslist of matplotlib.axes.Axes The Axes to attach the cursor to. useblitbool, default: True Use blitting for faster drawing if supported by the backend. horizOnbool, default: False Whether to draw the horizontal line. vertOn: bool, default: True Whether to draw the vertical line. Other Parameters **lineprops Line2D properties that control the appearance of the lines. See also axhline. Examples See Multicursor. clear(event)[source] Clear the cursor. connect()[source] Connect events. disconnect()[source] Disconnect events. onmove(event)[source]
matplotlib.widgets_api#matplotlib.widgets.MultiCursor
clear(event)[source] Clear the cursor.
matplotlib.widgets_api#matplotlib.widgets.MultiCursor.clear
connect()[source] Connect events.
matplotlib.widgets_api#matplotlib.widgets.MultiCursor.connect
disconnect()[source] Disconnect events.
matplotlib.widgets_api#matplotlib.widgets.MultiCursor.disconnect
onmove(event)[source]
matplotlib.widgets_api#matplotlib.widgets.MultiCursor.onmove
classmatplotlib.widgets.PolygonSelector(ax, onselect, useblit=False, props=None, handle_props=None, grab_range=10)[source] Bases: matplotlib.widgets._SelectorWidget Select a polygon region of an axes. Place vertices with each mouse click, and make the selection by completing the polygon (clicking on the first vertex). Once drawn individual vertices can be moved by clicking and dragging with the left mouse button, or removed by clicking the right mouse button. In addition, the following modifier keys can be used: Hold ctrl and click and drag a vertex to reposition it before the polygon has been completed. Hold the shift key and click and drag anywhere in the axes to move all vertices. Press the esc key to start a new polygon. For the selector to remain responsive you must keep a reference to it. Parameters axAxes The parent axes for the widget. onselectfunction When a polygon is completed or modified after completion, the onselect function is called and passed a list of the vertices as (xdata, ydata) tuples. useblitbool, default: False Whether to use blitting for faster drawing (if supported by the backend). propsdict, optional Properties with which the line is drawn, see matplotlib.lines.Line2D for valid properties. Default: dict(color='k', linestyle='-', linewidth=2, alpha=0.5) handle_propsdict, optional Artist properties for the markers drawn at the vertices of the polygon. See the marker arguments in matplotlib.lines.Line2D for valid properties. Default values are defined in mpl.rcParams except for the default value of markeredgecolor which will be the same as the color property in props. grab_rangefloat, default: 10 A vertex is selected (to complete the polygon or to move a vertex) if the mouse click is within grab_range pixels of the vertex. Notes If only one point remains after removing points, the selector reverts to an incomplete state and you can start drawing a new polygon from the existing point. Examples Polygon Selector propertyline[source] onmove(event)[source] Cursor move event handler and validator. propertyvertex_select_radius[source] propertyverts The polygon vertices, as a list of (x, y) pairs.
matplotlib.widgets_api#matplotlib.widgets.PolygonSelector
onmove(event)[source] Cursor move event handler and validator.
matplotlib.widgets_api#matplotlib.widgets.PolygonSelector.onmove
classmatplotlib.widgets.RadioButtons(ax, labels, active=0, activecolor='blue')[source] Bases: matplotlib.widgets.AxesWidget A GUI neutral radio button. For the buttons to remain responsive you must keep a reference to this object. Connect to the RadioButtons with the on_clicked method. Attributes axAxes The parent axes for the widget. activecolorcolor The color of the selected button. labelslist of Text The button labels. circleslist of Circle The buttons. value_selectedstr The label text of the currently selected button. Add radio buttons to an Axes. Parameters axAxes The axes to add the buttons to. labelslist of str The button labels. activeint The index of the initially selected button. activecolorcolor The color of the selected button. propertycnt[source] disconnect(cid)[source] Remove the observer with connection id cid. propertyobservers[source] on_clicked(func)[source] Connect the callback function func to button click events. Returns a connection id, which can be used to disconnect the callback. set_active(index)[source] Select button with number index. Callbacks will be triggered if eventson is True.
matplotlib.widgets_api#matplotlib.widgets.RadioButtons
disconnect(cid)[source] Remove the observer with connection id cid.
matplotlib.widgets_api#matplotlib.widgets.RadioButtons.disconnect
on_clicked(func)[source] Connect the callback function func to button click events. Returns a connection id, which can be used to disconnect the callback.
matplotlib.widgets_api#matplotlib.widgets.RadioButtons.on_clicked
set_active(index)[source] Select button with number index. Callbacks will be triggered if eventson is True.
matplotlib.widgets_api#matplotlib.widgets.RadioButtons.set_active
classmatplotlib.widgets.RangeSlider(ax, label, valmin, valmax, valinit=None, valfmt=None, closedmin=True, closedmax=True, dragging=True, valstep=None, orientation='horizontal', track_color='lightgrey', handle_style=None, **kwargs)[source] Bases: matplotlib.widgets.SliderBase A slider representing a range of floating point values. Defines the min and max of the range via the val attribute as a tuple of (min, max). Create a slider that defines a range contained within [valmin, valmax] in axes ax. For the slider to remain responsive you must maintain a reference to it. Call on_changed() to connect to the slider event. Attributes valtuple of float Slider value. Parameters axAxes The Axes to put the slider in. labelstr Slider label. valminfloat The minimum value of the slider. valmaxfloat The maximum value of the slider. valinittuple of float or None, default: None The initial positions of the slider. If None the initial positions will be at the 25th and 75th percentiles of the range. valfmtstr, default: None %-format string used to format the slider values. If None, a ScalarFormatter is used instead. closedminbool, default: True Whether the slider interval is closed on the bottom. closedmaxbool, default: True Whether the slider interval is closed on the top. draggingbool, default: True If True the slider can be dragged by the mouse. valstepfloat, default: None If given, the slider will snap to multiples of valstep. orientation{'horizontal', 'vertical'}, default: 'horizontal' The orientation of the slider. track_colorcolor, default: 'lightgrey' The color of the background track. The track is accessible for further styling via the track attribute. handle_styledict Properties of the slider handles. Default values are Key Value Default Description facecolor color 'white' The facecolor of the slider handles. edgecolor color '.75' The edgecolor of the slider handles. size int 10 The size of the slider handles in points. Other values will be transformed as marker{foo} and passed to the Line2D constructor. e.g. handle_style = {'style'='x'} will result in markerstyle = 'x'. Notes Additional kwargs are passed on to self.poly which is the Polygon that draws the slider knob. See the Polygon documentation for valid property names (facecolor, edgecolor, alpha, etc.). on_changed(func)[source] Connect func as callback function to changes of the slider value. Parameters funccallable Function to call when slider is changed. The function must accept a numpy array with shape (2,) as its argument. Returns int Connection id (which can be used to disconnect func). set_max(max)[source] Set the lower value of the slider to max. Parameters maxfloat set_min(min)[source] Set the lower value of the slider to min. Parameters minfloat set_val(val)[source] Set slider value to val. Parameters valtuple or array-like of float
matplotlib.widgets_api#matplotlib.widgets.RangeSlider
on_changed(func)[source] Connect func as callback function to changes of the slider value. Parameters funccallable Function to call when slider is changed. The function must accept a numpy array with shape (2,) as its argument. Returns int Connection id (which can be used to disconnect func).
matplotlib.widgets_api#matplotlib.widgets.RangeSlider.on_changed
set_max(max)[source] Set the lower value of the slider to max. Parameters maxfloat
matplotlib.widgets_api#matplotlib.widgets.RangeSlider.set_max
set_min(min)[source] Set the lower value of the slider to min. Parameters minfloat
matplotlib.widgets_api#matplotlib.widgets.RangeSlider.set_min
set_val(val)[source] Set slider value to val. Parameters valtuple or array-like of float
matplotlib.widgets_api#matplotlib.widgets.RangeSlider.set_val
classmatplotlib.widgets.RectangleSelector(ax, onselect, drawtype=<deprecated parameter>, minspanx=0, minspany=0, useblit=False, lineprops=<deprecated parameter>, props=None, spancoords='data', button=None, grab_range=10, handle_props=None, interactive=False, state_modifier_keys=None, drag_from_anywhere=False, ignore_event_outside=False)[source] Bases: matplotlib.widgets._SelectorWidget Select a rectangular region of an axes. For the cursor to remain responsive you must keep a reference to it. Press and release events triggered at the same coordinates outside the selection will clear the selector, except when ignore_event_outside=True. Parameters axAxes The parent axes for the widget. onselectfunction A callback function that is called after a release event and the selection is created, changed or removed. It must have the signature: def onselect(eclick: MouseEvent, erelease: MouseEvent) where eclick and erelease are the mouse click and release MouseEvents that start and complete the selection. minspanxfloat, default: 0 Selections with an x-span less than or equal to minspanx are removed (when already existing) or cancelled. minspanyfloat, default: 0 Selections with an y-span less than or equal to minspanx are removed (when already existing) or cancelled. useblitbool, default: False Whether to use blitting for faster drawing (if supported by the backend). propsdict, optional Properties with which the rectangle is drawn. See matplotlib.patches.Patch for valid properties. Default: dict(facecolor='red', edgecolor='black', alpha=0.2, fill=True) spancoords{"data", "pixels"}, default: "data" Whether to interpret minspanx and minspany in data or in pixel coordinates. buttonMouseButton, list of MouseButton, default: all buttons Button(s) that trigger rectangle selection. grab_rangefloat, default: 10 Distance in pixels within which the interactive tool handles can be activated. handle_propsdict, optional Properties with which the interactive handles (marker artists) are drawn. See the marker arguments in matplotlib.lines.Line2D for valid properties. Default values are defined in mpl.rcParams except for the default value of markeredgecolor which will be the same as the edgecolor property in props. interactivebool, default: False Whether to draw a set of handles that allow interaction with the widget after it is drawn. state_modifier_keysdict, optional Keyboard modifiers which affect the widget's behavior. Values amend the defaults. "move": Move the existing shape, default: no modifier. "clear": Clear the current shape, default: "escape". "square": Make the shape square, default: "shift". "center": Make the initial point the center of the shape, default: "ctrl". "square" and "center" can be combined. drag_from_anywherebool, default: False If True, the widget can be moved by clicking anywhere within its bounds. ignore_event_outsidebool, default: False If True, the event triggered outside the span selector will be ignored. Examples >>> import matplotlib.pyplot as plt >>> import matplotlib.widgets as mwidgets >>> fig, ax = plt.subplots() >>> ax.plot([1, 2, 3], [10, 50, 100]) >>> def onselect(eclick, erelease): ... print(eclick.xdata, eclick.ydata) ... print(erelease.xdata, erelease.ydata) >>> props = dict(facecolor='blue', alpha=0.5) >>> rect = mwidgets.RectangleSelector(ax, onselect, interactive=True, props=props) >>> fig.show() See also: Rectangle and ellipse selectors propertyactive_handle[source] propertycenter Center of rectangle. propertycorners Corners of rectangle from lower left, moving clockwise. propertydraw_shape[source] propertydrawtype[source] propertyedge_centers Midpoint of rectangle edges from left, moving anti-clockwise. propertyextents Return (xmin, xmax, ymin, ymax). propertygeometry Return an array of shape (2, 5) containing the x (RectangleSelector.geometry[1, :]) and y (RectangleSelector.geometry[0, :]) coordinates of the four corners of the rectangle starting and ending in the top left corner. propertyinteractive[source] propertymaxdist[source] propertyto_draw[source]
matplotlib.widgets_api#matplotlib.widgets.RectangleSelector
classmatplotlib.widgets.Slider(ax, label, valmin, valmax, valinit=0.5, valfmt=None, closedmin=True, closedmax=True, slidermin=None, slidermax=None, dragging=True, valstep=None, orientation='horizontal', *, initcolor='r', track_color='lightgrey', handle_style=None, **kwargs)[source] Bases: matplotlib.widgets.SliderBase A slider representing a floating point range. Create a slider from valmin to valmax in axes ax. For the slider to remain responsive you must maintain a reference to it. Call on_changed() to connect to the slider event. Attributes valfloat Slider value. Parameters axAxes The Axes to put the slider in. labelstr Slider label. valminfloat The minimum value of the slider. valmaxfloat The maximum value of the slider. valinitfloat, default: 0.5 The slider initial position. valfmtstr, default: None %-format string used to format the slider value. If None, a ScalarFormatter is used instead. closedminbool, default: True Whether the slider interval is closed on the bottom. closedmaxbool, default: True Whether the slider interval is closed on the top. sliderminSlider, default: None Do not allow the current slider to have a value less than the value of the Slider slidermin. slidermaxSlider, default: None Do not allow the current slider to have a value greater than the value of the Slider slidermax. draggingbool, default: True If True the slider can be dragged by the mouse. valstepfloat or array-like, default: None If a float, the slider will snap to multiples of valstep. If an array the slider will snap to the values in the array. orientation{'horizontal', 'vertical'}, default: 'horizontal' The orientation of the slider. initcolorcolor, default: 'r' The color of the line at the valinit position. Set to 'none' for no line. track_colorcolor, default: 'lightgrey' The color of the background track. The track is accessible for further styling via the track attribute. handle_styledict Properties of the slider handle. Default values are Key Value Default Description facecolor color 'white' The facecolor of the slider handle. edgecolor color '.75' The edgecolor of the slider handle. size int 10 The size of the slider handle in points. Other values will be transformed as marker{foo} and passed to the Line2D constructor. e.g. handle_style = {'style'='x'} will result in markerstyle = 'x'. Notes Additional kwargs are passed on to self.poly which is the Polygon that draws the slider knob. See the Polygon documentation for valid property names (facecolor, edgecolor, alpha, etc.). propertycnt[source] propertyobservers[source] on_changed(func)[source] Connect func as callback function to changes of the slider value. Parameters funccallable Function to call when slider is changed. The function must accept a single float as its arguments. Returns int Connection id (which can be used to disconnect func). set_val(val)[source] Set slider value to val. Parameters valfloat
matplotlib.widgets_api#matplotlib.widgets.Slider
on_changed(func)[source] Connect func as callback function to changes of the slider value. Parameters funccallable Function to call when slider is changed. The function must accept a single float as its arguments. Returns int Connection id (which can be used to disconnect func).
matplotlib.widgets_api#matplotlib.widgets.Slider.on_changed
set_val(val)[source] Set slider value to val. Parameters valfloat
matplotlib.widgets_api#matplotlib.widgets.Slider.set_val
classmatplotlib.widgets.SliderBase(ax, orientation, closedmin, closedmax, valmin, valmax, valfmt, dragging, valstep)[source] Bases: matplotlib.widgets.AxesWidget The base class for constructing Slider widgets. Not intended for direct usage. For the slider to remain responsive you must maintain a reference to it. disconnect(cid)[source] Remove the observer with connection id cid. Parameters cidint Connection id of the observer to be removed. reset()[source] Reset the slider to the initial value.
matplotlib.widgets_api#matplotlib.widgets.SliderBase
disconnect(cid)[source] Remove the observer with connection id cid. Parameters cidint Connection id of the observer to be removed.
matplotlib.widgets_api#matplotlib.widgets.SliderBase.disconnect
reset()[source] Reset the slider to the initial value.
matplotlib.widgets_api#matplotlib.widgets.SliderBase.reset
classmatplotlib.widgets.SpanSelector(ax, onselect, direction, minspan=0, useblit=False, props=None, onmove_callback=None, interactive=False, button=None, handle_props=None, grab_range=10, drag_from_anywhere=False, ignore_event_outside=False)[source] Bases: matplotlib.widgets._SelectorWidget Visually select a min/max range on a single axis and call a function with those values. To guarantee that the selector remains responsive, keep a reference to it. In order to turn off the SpanSelector, set span_selector.active to False. To turn it back on, set it to True. Press and release events triggered at the same coordinates outside the selection will clear the selector, except when ignore_event_outside=True. Parameters axmatplotlib.axes.Axes onselectcallable A callback function that is called after a release event and the selection is created, changed or removed. It must have the signature: def on_select(min: float, max: float) -> Any direction{"horizontal", "vertical"} The direction along which to draw the span selector. minspanfloat, default: 0 If selection is less than or equal to minspan, the selection is removed (when already existing) or cancelled. useblitbool, default: False If True, use the backend-dependent blitting features for faster canvas updates. propsdict, optional Dictionary of matplotlib.patches.Patch properties. Default: dict(facecolor='red', alpha=0.5) onmove_callbackfunc(min, max), min/max are floats, default: None Called on mouse move while the span is being selected. span_staysbool, default: False If True, the span stays visible after the mouse is released. Deprecated, use interactive instead. interactivebool, default: False Whether to draw a set of handles that allow interaction with the widget after it is drawn. buttonMouseButton or list of MouseButton, default: all buttons The mouse buttons which activate the span selector. handle_propsdict, default: None Properties of the handle lines at the edges of the span. Only used when interactive is True. See matplotlib.lines.Line2D for valid properties. grab_rangefloat, default: 10 Distance in pixels within which the interactive tool handles can be activated. drag_from_anywherebool, default: False If True, the widget can be moved by clicking anywhere within its bounds. ignore_event_outsidebool, default: False If True, the event triggered outside the span selector will be ignored. Examples >>> import matplotlib.pyplot as plt >>> import matplotlib.widgets as mwidgets >>> fig, ax = plt.subplots() >>> ax.plot([1, 2, 3], [10, 50, 100]) >>> def onselect(vmin, vmax): ... print(vmin, vmax) >>> span = mwidgets.SpanSelector(ax, onselect, 'horizontal', ... props=dict(facecolor='blue', alpha=0.5)) >>> fig.show() See also: Span Selector propertyactive_handle[source] connect_default_events()[source] Connect the major canvas events to methods. propertydirection Direction of the span selector: 'vertical' or 'horizontal'. propertyextents Return extents of the span selector. new_axes(ax)[source] Set SpanSelector to operate on a new Axes. propertypressv[source] propertyprev[source] propertyrect[source] propertyrectprops[source] propertyspan_stays[source]
matplotlib.widgets_api#matplotlib.widgets.SpanSelector
connect_default_events()[source] Connect the major canvas events to methods.
matplotlib.widgets_api#matplotlib.widgets.SpanSelector.connect_default_events
new_axes(ax)[source] Set SpanSelector to operate on a new Axes.
matplotlib.widgets_api#matplotlib.widgets.SpanSelector.new_axes
classmatplotlib.widgets.SubplotTool(targetfig, toolfig)[source] Bases: matplotlib.widgets.Widget A tool to adjust the subplot params of a matplotlib.figure.Figure. Parameters targetfigFigure The figure instance to adjust. toolfigFigure The figure instance to embed the subplot tool into.
matplotlib.widgets_api#matplotlib.widgets.SubplotTool
classmatplotlib.widgets.TextBox(ax, label, initial='', color='.95', hovercolor='1', label_pad=0.01, textalignment='left')[source] Bases: matplotlib.widgets.AxesWidget A GUI neutral text input box. For the text box to remain responsive you must keep a reference to it. Call on_text_change to be updated whenever the text changes. Call on_submit to be updated whenever the user hits enter or leaves the text entry field. Attributes axAxes The parent axes for the widget. labelText colorcolor The color of the text box when not hovering. hovercolorcolor The color of the text box when hovering. Parameters axAxes The Axes instance the button will be placed into. labelstr Label for this text box. initialstr Initial value in the text box. colorcolor The color of the box. hovercolorcolor The color of the box when the mouse is over it. label_padfloat The distance between the label and the right side of the textbox. textalignment{'left', 'center', 'right'} The horizontal location of the text. propertyDIST_FROM_LEFT[source] begin_typing(x)[source] propertychange_observers[source] propertycnt[source] disconnect(cid)[source] Remove the observer with connection id cid. on_submit(func)[source] When the user hits enter or leaves the submission box, call this func with event. A connection id is returned which can be used to disconnect. on_text_change(func)[source] When the text changes, call this func with event. A connection id is returned which can be used to disconnect. position_cursor(x)[source] set_val(val)[source] stop_typing()[source] propertysubmit_observers[source] propertytext
matplotlib.widgets_api#matplotlib.widgets.TextBox
begin_typing(x)[source]
matplotlib.widgets_api#matplotlib.widgets.TextBox.begin_typing
disconnect(cid)[source] Remove the observer with connection id cid.
matplotlib.widgets_api#matplotlib.widgets.TextBox.disconnect
on_submit(func)[source] When the user hits enter or leaves the submission box, call this func with event. A connection id is returned which can be used to disconnect.
matplotlib.widgets_api#matplotlib.widgets.TextBox.on_submit
on_text_change(func)[source] When the text changes, call this func with event. A connection id is returned which can be used to disconnect.
matplotlib.widgets_api#matplotlib.widgets.TextBox.on_text_change
position_cursor(x)[source]
matplotlib.widgets_api#matplotlib.widgets.TextBox.position_cursor
set_val(val)[source]
matplotlib.widgets_api#matplotlib.widgets.TextBox.set_val
stop_typing()[source]
matplotlib.widgets_api#matplotlib.widgets.TextBox.stop_typing
classmatplotlib.widgets.ToolHandles(ax, x, y, marker='o', marker_props=None, useblit=True)[source] Bases: object Control handles for canvas tools. Parameters axmatplotlib.axes.Axes Matplotlib axes where tool handles are displayed. x, y1D arrays Coordinates of control handles. markerstr, default: 'o' Shape of marker used to display handle. See matplotlib.pyplot.plot. marker_propsdict, optional Additional marker properties. See matplotlib.lines.Line2D. useblitbool, default: True Whether to use blitting for faster drawing (if supported by the backend). propertyartists closest(x, y)[source] Return index and pixel distance to closest index. set_animated(val)[source] set_data(pts, y=None)[source] Set x and y positions of handles. set_visible(val)[source] propertyx propertyy
matplotlib.widgets_api#matplotlib.widgets.ToolHandles
closest(x, y)[source] Return index and pixel distance to closest index.
matplotlib.widgets_api#matplotlib.widgets.ToolHandles.closest
set_animated(val)[source]
matplotlib.widgets_api#matplotlib.widgets.ToolHandles.set_animated
set_data(pts, y=None)[source] Set x and y positions of handles.
matplotlib.widgets_api#matplotlib.widgets.ToolHandles.set_data
set_visible(val)[source]
matplotlib.widgets_api#matplotlib.widgets.ToolHandles.set_visible
classmatplotlib.widgets.ToolLineHandles(ax, positions, direction, line_props=None, useblit=True)[source] Bases: object Control handles for canvas tools. Parameters axmatplotlib.axes.Axes Matplotlib axes where tool handles are displayed. positions1D array Positions of handles in data coordinates. direction{"horizontal", "vertical"} Direction of handles, either 'vertical' or 'horizontal' line_propsdict, optional Additional line properties. See matplotlib.lines.Line2D. useblitbool, default: True Whether to use blitting for faster drawing (if supported by the backend). propertyartists closest(x, y)[source] Return index and pixel distance to closest handle. Parameters x, yfloat x, y position from which the distance will be calculated to determinate the closest handle Returns index, distanceindex of the handle and its distance from position x, y propertydirection Direction of the handle: 'vertical' or 'horizontal'. propertypositions Positions of the handle in data coordinates. remove()[source] Remove the handles artist from the figure. set_animated(value)[source] Set the animated state of the handles artist. set_data(positions)[source] Set x or y positions of handles, depending if the lines are vertical of horizontal. Parameters positionstuple of length 2 Set the positions of the handle in data coordinates set_visible(value)[source] Set the visibility state of the handles artist.
matplotlib.widgets_api#matplotlib.widgets.ToolLineHandles
closest(x, y)[source] Return index and pixel distance to closest handle. Parameters x, yfloat x, y position from which the distance will be calculated to determinate the closest handle Returns index, distanceindex of the handle and its distance from position x, y
matplotlib.widgets_api#matplotlib.widgets.ToolLineHandles.closest
remove()[source] Remove the handles artist from the figure.
matplotlib.widgets_api#matplotlib.widgets.ToolLineHandles.remove
set_animated(value)[source] Set the animated state of the handles artist.
matplotlib.widgets_api#matplotlib.widgets.ToolLineHandles.set_animated
set_data(positions)[source] Set x or y positions of handles, depending if the lines are vertical of horizontal. Parameters positionstuple of length 2 Set the positions of the handle in data coordinates
matplotlib.widgets_api#matplotlib.widgets.ToolLineHandles.set_data
set_visible(value)[source] Set the visibility state of the handles artist.
matplotlib.widgets_api#matplotlib.widgets.ToolLineHandles.set_visible
classmatplotlib.widgets.Widget[source] Bases: object Abstract base class for GUI neutral widgets. propertyactive Is the widget active? drawon=True eventson=True get_active()[source] Get whether the widget is active. ignore(event)[source] Return whether event should be ignored. This method should be called at the beginning of any event callback. set_active(active)[source] Set whether the widget is active.
matplotlib.widgets_api#matplotlib.widgets.Widget
drawon=True
matplotlib.widgets_api#matplotlib.widgets.Widget.drawon
eventson=True
matplotlib.widgets_api#matplotlib.widgets.Widget.eventson
get_active()[source] Get whether the widget is active.
matplotlib.widgets_api#matplotlib.widgets.Widget.get_active
ignore(event)[source] Return whether event should be ignored. This method should be called at the beginning of any event callback.
matplotlib.widgets_api#matplotlib.widgets.Widget.ignore
set_active(active)[source] Set whether the widget is active.
matplotlib.widgets_api#matplotlib.widgets.Widget.set_active
flask.abort(status, *args, **kwargs) Raises an HTTPException for the given status code or WSGI application. If a status code is given, it will be looked up in the list of exceptions and will raise that exception. If passed a WSGI application, it will wrap it in a proxy WSGI exception and raise that: abort(404) # 404 Not Found abort(Response('Hello World')) Parameters status (Union[int, Response]) – args (Any) – kwargs (Any) – Return type NoReturn
flask.api.index#flask.abort
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. Changelog New in version 0.9. Parameters f (Callable[[Response], Response]) – Return type Callable[[Response], Response]
flask.api.index#flask.after_this_request
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 information. 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. Parameters app (Flask) – Return type None pop(exc=<object object>) Pops the app context. Parameters exc (Optional[BaseException]) – Return type None push() Binds the app context to the current context. Return type None
flask.api.index#flask.ctx.AppContext
pop(exc=<object object>) Pops the app context. Parameters exc (Optional[BaseException]) – Return type None
flask.api.index#flask.ctx.AppContext.pop
push() Binds the app context to the current context. Return type None
flask.api.index#flask.ctx.AppContext.push
class flask.cli.AppGroup(name=None, commands=None, **attrs) This works similar to a regular click Group but it changes the behavior of the command() decorator so that it automatically wraps the functions in with_appcontext(). Not to be confused with FlaskGroup. Parameters name (Optional[str]) – commands (Optional[Union[Dict[str, click.core.Command], Sequence[click.core.Command]]]) – attrs (Any) – Return type None command(*args, **kwargs) This works exactly like the method of the same name on a regular click.Group but it wraps callbacks in with_appcontext() unless it’s disabled by passing with_appcontext=False. group(*args, **kwargs) This works exactly like the method of the same name on a regular click.Group but it defaults the group class to AppGroup.
flask.api.index#flask.cli.AppGroup
command(*args, **kwargs) This works exactly like the method of the same name on a regular click.Group but it wraps callbacks in with_appcontext() unless it’s disabled by passing with_appcontext=False.
flask.api.index#flask.cli.AppGroup.command
group(*args, **kwargs) This works exactly like the method of the same name on a regular click.Group but it defaults the group class to AppGroup.
flask.api.index#flask.cli.AppGroup.group
APPLICATION_ROOT Inform the application what path it is mounted under by the application / web server. This is used for generating URLs outside the context of a request (inside a request, the dispatcher is responsible for setting SCRIPT_NAME instead; see Application Dispatching for examples of dispatch configuration). Will be used for the session cookie path if SESSION_COOKIE_PATH is not set. Default: '/'
flask.config.index#APPLICATION_ROOT
ASGI If you’d like to use an ASGI server you will need to utilise WSGI to ASGI middleware. The asgiref [WsgiToAsgi](https://github.com/django/asgiref#wsgi-to-asgi-adapter) adapter is recommended as it integrates with the event loop used for Flask’s Using async and await support. You can use the adapter by wrapping the Flask app, from asgiref.wsgi import WsgiToAsgi from flask import Flask app = Flask(__name__) ... asgi_app = WsgiToAsgi(app) and then serving the asgi_app with the asgi server, e.g. using Hypercorn, $ hypercorn module:asgi_app
flask.deploying.asgi.index
class flask.Blueprint(name, import_name, static_folder=None, static_url_path=None, template_folder=None, url_prefix=None, subdomain=None, url_defaults=None, root_path=None, cli_group=<object object>) Represents a blueprint, a collection of routes and other app-related functions that can be registered on a real application later. A blueprint is an object that allows defining application functions without requiring an application object ahead of time. It uses the same decorators as Flask, but defers the need for an application by recording them for later registration. Decorating a function with a blueprint creates a deferred function that is called with BlueprintSetupState when the blueprint is registered on an application. See Modular Applications with Blueprints for more information. Parameters name (str) – The name of the blueprint. Will be prepended to each endpoint name. import_name (str) – The name of the blueprint package, usually __name__. This helps locate the root_path for the blueprint. static_folder (Optional[str]) – A folder with static files that should be served by the blueprint’s static route. The path is relative to the blueprint’s root path. Blueprint static files are disabled by default. static_url_path (Optional[str]) – The url to serve static files from. Defaults to static_folder. If the blueprint does not have a url_prefix, the app’s static route will take precedence, and the blueprint’s static files won’t be accessible. template_folder (Optional[str]) – A folder with templates that should be added to the app’s template search path. The path is relative to the blueprint’s root path. Blueprint templates are disabled by default. Blueprint templates have a lower precedence than those in the app’s templates folder. url_prefix (Optional[str]) – A path to prepend to all of the blueprint’s URLs, to make them distinct from the rest of the app’s routes. subdomain (Optional[str]) – A subdomain that blueprint routes will match on by default. url_defaults (Optional[dict]) – A dict of default values that blueprint routes will receive by default. root_path (Optional[str]) – By default, the blueprint will automatically set this based on import_name. In certain situations this automatic detection can fail, so the path can be specified manually instead. cli_group (Optional[str]) – Changelog Changed in version 1.1.0: Blueprints have a cli group to register nested CLI commands. The cli_group parameter controls the name of the group under the flask command. New in version 0.7. add_app_template_filter(f, name=None) Register a custom template filter, available application wide. Like Flask.add_template_filter() but for a blueprint. Works exactly like the app_template_filter() decorator. Parameters name (Optional[str]) – the optional name of the filter, otherwise the function name will be used. f (Callable[[Any], str]) – Return type None 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. Changelog New in version 0.10. Parameters name (Optional[str]) – the optional name of the global, otherwise the function name will be used. f (Callable[[], Any]) – Return type None 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. Changelog New in version 0.10. Parameters name (Optional[str]) – the optional name of the test, otherwise the function name will be used. f (Callable[[Any], bool]) – Return type None 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 prefixed with the name of the blueprint. Parameters rule (str) – endpoint (Optional[str]) – view_func (Optional[Callable]) – options (Any) – Return type None 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. Parameters f (Callable[[Response], Response]) – Return type Callable[[Response], Response] after_request(f) Register a function to run after each request to this object. The function is called with the response object, and must return a response object. This allows the functions to modify or replace the response before it is sent. If a function raises an exception, any remaining after_request functions will not be called. Therefore, this should not be used for actions that must execute, such as to close resources. Use teardown_request() for that. Parameters f (Callable[[Response], Response]) – Return type Callable[[Response], Response] after_request_funcs: t.Dict[AppOrBlueprintKey, t.List[AfterRequestCallable]] A data structure of functions to call at the end of each request, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests. To register a function, use the after_request() decorator. This data structure is internal. It should not be modified directly and its format may change at any time. app_context_processor(f) Like Flask.context_processor() but for a blueprint. Such a function is executed each request, even if outside of the blueprint. Parameters f (Callable[[], Dict[str, Any]]) – Return type Callable[[], Dict[str, Any]] app_errorhandler(code) Like Flask.errorhandler() but for a blueprint. This handler is used for all requests, even if outside of the blueprint. Parameters code (Union[Type[Exception], int]) – Return type Callable app_template_filter(name=None) Register a custom template filter, available application wide. Like Flask.template_filter() but for a blueprint. Parameters name (Optional[str]) – the optional name of the filter, otherwise the function name will be used. Return type Callable app_template_global(name=None) Register a custom template global, available application wide. Like Flask.template_global() but for a blueprint. Changelog New in version 0.10. Parameters name (Optional[str]) – the optional name of the global, otherwise the function name will be used. Return type Callable app_template_test(name=None) Register a custom template test, available application wide. Like Flask.template_test() but for a blueprint. Changelog New in version 0.10. Parameters name (Optional[str]) – the optional name of the test, otherwise the function name will be used. Return type Callable app_url_defaults(f) Same as url_defaults() but application wide. Parameters f (Callable[[str, dict], None]) – Return type Callable[[str, dict], None] app_url_value_preprocessor(f) Same as url_value_preprocessor() but application wide. Parameters f (Callable[[Optional[str], Optional[dict]], None]) – Return type Callable[[Optional[str], Optional[dict]], None] before_app_first_request(f) Like Flask.before_first_request(). Such a function is executed before the first request to the application. Parameters f (Callable[[], None]) – Return type Callable[[], None] before_app_request(f) Like Flask.before_request(). Such a function is executed before each request, even if outside of a blueprint. Parameters f (Callable[[], None]) – Return type Callable[[], None] before_request(f) Register a function to run before each request. For example, this can be used to open a database connection, or to load the logged in user from the session. @app.before_request def load_user(): if "user_id" in session: g.user = db.session.get(session["user_id"]) The function will be called without any arguments. If it returns a non-None value, the value is handled as if it was the return value from the view, and further request handling is stopped. Parameters f (Callable[[], None]) – Return type Callable[[], None] before_request_funcs: t.Dict[AppOrBlueprintKey, t.List[BeforeRequestCallable]] A data structure of functions to call at the beginning of each request, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests. To register a function, use the before_request() decorator. This data structure is internal. It should not be modified directly and its format may change at any time. cli The Click command group for registering CLI commands for this object. The commands are available from the flask command once the application has been discovered and blueprints have been registered. context_processor(f) Registers a template context processor function. Parameters f (Callable[[], Dict[str, Any]]) – Return type Callable[[], Dict[str, Any]] delete(rule, **options) Shortcut for route() with methods=["DELETE"]. New in version 2.0. Parameters rule (str) – options (Any) – Return type Callable endpoint(endpoint) Decorate a view function to register it for the given endpoint. Used if a rule is added without a view_func with add_url_rule(). app.add_url_rule("/ex", endpoint="example") @app.endpoint("example") def example(): ... Parameters endpoint (str) – The endpoint name to associate with the view function. Return type Callable error_handler_spec: t.Dict[AppOrBlueprintKey, t.Dict[t.Optional[int], t.Dict[t.Type[Exception], ErrorHandlerCallable]]] A data structure of registered error handlers, in the format {scope: {code: {class: handler}}}`. The scope key is the name of a blueprint the handlers are active for, or None for all requests. The code key is the HTTP status code for HTTPException, or None for other exceptions. The innermost dictionary maps exception classes to handler functions. To register an error handler, use the errorhandler() decorator. This data structure is internal. It should not be modified directly and its format may change at any time. errorhandler(code_or_exception) Register a function to handle errors by code or exception class. A decorator that is used to register a function given an error code. Example: @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 Changelog New in version 0.7: Use register_error_handler() instead of modifying error_handler_spec directly, for application wide error handlers. New in version 0.7: One can now additionally also register custom exception types that do not necessarily have to be a subclass of the HTTPException class. Parameters code_or_exception (Union[Type[Exception], int]) – the code as integer for the handler, or an arbitrary exception Return type Callable get(rule, **options) Shortcut for route() with methods=["GET"]. New in version 2.0. Parameters rule (str) – options (Any) – Return type Callable get_send_file_max_age(filename) Used by send_file() to determine the max_age cache value for a given file path if it wasn’t passed. By default, this returns SEND_FILE_MAX_AGE_DEFAULT from the configuration of current_app. This defaults to None, which tells the browser to use conditional requests instead of a timed cache, which is usually preferable. Changed in version 2.0: The default configuration is None instead of 12 hours. Changelog New in version 0.9. Parameters filename (str) – Return type Optional[int] property has_static_folder: bool True if static_folder is set. Changelog New in version 0.5. import_name The name of the package or module that this object belongs to. Do not change this once it is set by the constructor. property jinja_loader: Optional[jinja2.loaders.FileSystemLoader] The Jinja loader for this object’s templates. By default this is a class jinja2.loaders.FileSystemLoader to template_folder if it is set. Changelog New in version 0.5. json_decoder: Optional[Type[json.decoder.JSONDecoder]] = None Blueprint local JSON decoder class to use. Set to None to use the app’s json_decoder. json_encoder: Optional[Type[json.encoder.JSONEncoder]] = None Blueprint local JSON encoder class to use. Set to None to use the app’s json_encoder. make_setup_state(app, options, first_registration=False) Creates an instance of BlueprintSetupState() object that is later passed to the register callback functions. Subclasses can override this to return a subclass of the setup state. Parameters app (Flask) – options (dict) – first_registration (bool) – Return type flask.blueprints.BlueprintSetupState open_resource(resource, mode='rb') Open a resource file relative to root_path for reading. For example, if the file schema.sql is next to the file app.py where the Flask app is defined, it can be opened with: with app.open_resource("schema.sql") as f: conn.executescript(f.read()) Parameters resource (str) – Path to the resource relative to root_path. mode (str) – Open the file in this mode. Only reading is supported, valid values are “r” (or “rt”) and “rb”. Return type IO patch(rule, **options) Shortcut for route() with methods=["PATCH"]. New in version 2.0. Parameters rule (str) – options (Any) – Return type Callable post(rule, **options) Shortcut for route() with methods=["POST"]. New in version 2.0. Parameters rule (str) – options (Any) – Return type Callable put(rule, **options) Shortcut for route() with methods=["PUT"]. New in version 2.0. Parameters rule (str) – options (Any) – Return type Callable 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. Parameters func (Callable) – Return type None 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. Parameters func (Callable) – Return type None register(app, options) Called by Flask.register_blueprint() to register all views and callbacks registered on the blueprint with the application. Creates a BlueprintSetupState and calls each record() callbackwith it. Parameters app (Flask) – The application this blueprint is being registered with. options (dict) – Keyword arguments forwarded from register_blueprint(). first_registration – Whether this is the first time this blueprint has been registered on the application. Return type None register_blueprint(blueprint, **options) Register a Blueprint on this blueprint. Keyword arguments passed to this method will override the defaults set on the blueprint. New in version 2.0. Parameters blueprint (flask.blueprints.Blueprint) – options (Any) – Return type None 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. Changelog New in version 0.7. Parameters code_or_exception (Union[Type[Exception], int]) – f (Callable[[Exception], Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], Union[Headers, Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int, Union[Headers, Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], WSGIApplication]]) – Return type None root_path Absolute path to the package on the filesystem. Used to look up resources contained in the package. route(rule, **options) Decorate a view function to register it with the given URL rule and options. Calls add_url_rule(), which has more details about the implementation. @app.route("/") def index(): return "Hello, World!" See URL Route Registrations. The endpoint name for the route defaults to the name of the view function if the endpoint parameter isn’t passed. The methods parameter defaults to ["GET"]. HEAD and OPTIONS are added automatically. Parameters rule (str) – The URL rule string. options (Any) – Extra options passed to the Rule object. Return type Callable send_static_file(filename) The view function used to serve files from static_folder. A route is automatically registered for this view at static_url_path if static_folder is set. Changelog New in version 0.5. Parameters filename (str) – Return type Response property static_folder: Optional[str] The absolute path to the configured static folder. None if no static folder is set. property static_url_path: Optional[str] The URL prefix that the static route will be accessible from. If it was not configured during init, it is derived from static_folder. teardown_app_request(f) Like Flask.teardown_request() but for a blueprint. Such a function is executed when tearing down each request, even if outside of the blueprint. Parameters f (Callable[[Optional[BaseException]], Response]) – Return type Callable[[Optional[BaseException]], Response] teardown_request(f) 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 contexts. This becomes relevant if you are using such constructs in tests. Teardown functions must avoid raising exceptions, since they . If they execute code that might fail they will have to surround the execution of these code by try/except statements and log occurring errors. When a teardown function was called because of an exception it will be passed an error object. The return values of teardown functions are ignored. Debug Note In debug mode Flask will not tear down a request on an exception immediately. Instead it will keep it alive so that the interactive debugger can still access it. This behavior can be controlled by the PRESERVE_CONTEXT_ON_EXCEPTION configuration variable. Parameters f (Callable[[Optional[BaseException]], Response]) – Return type Callable[[Optional[BaseException]], Response] teardown_request_funcs: t.Dict[AppOrBlueprintKey, t.List[TeardownCallable]] A data structure of functions to call at the end of each request even if an exception is raised, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests. To register a function, use the teardown_request() decorator. This data structure is internal. It should not be modified directly and its format may change at any time. template_context_processors: t.Dict[AppOrBlueprintKey, t.List[TemplateContextProcessorCallable]] A data structure of functions to call to pass extra context values when rendering templates, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests. To register a function, use the context_processor() decorator. This data structure is internal. It should not be modified directly and its format may change at any time. template_folder The path to the templates folder, relative to root_path, to add to the template loader. None if templates should not be added. url_default_functions: t.Dict[AppOrBlueprintKey, t.List[URLDefaultCallable]] A data structure of functions to call to modify the keyword arguments when generating URLs, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests. To register a function, use the url_defaults() decorator. This data structure is internal. It should not be modified directly and its format may change at any time. url_defaults(f) Callback function for URL defaults for all view functions of the application. It’s called with the endpoint and values and should update the values passed in place. Parameters f (Callable[[str, dict], None]) – Return type Callable[[str, dict], None] url_value_preprocessor(f) Register a URL value preprocessor function for all view functions in the application. These functions will be called before the before_request() functions. The function can modify the values captured from the matched url before they are passed to the view. For example, this can be used to pop a common language code value and place it in g rather than pass it to every view. The function is passed the endpoint name and values dict. The return value is ignored. Parameters f (Callable[[Optional[str], Optional[dict]], None]) – Return type Callable[[Optional[str], Optional[dict]], None] url_value_preprocessors: t.Dict[AppOrBlueprintKey, t.List[URLValuePreprocessorCallable]] A data structure of functions to call to modify the keyword arguments passed to the view function, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests. To register a function, use the url_value_preprocessor() decorator. This data structure is internal. It should not be modified directly and its format may change at any time. view_functions: t.Dict[str, t.Callable] A dictionary mapping endpoint names to view functions. To register a view function, use the route() decorator. This data structure is internal. It should not be modified directly and its format may change at any time.
flask.api.index#flask.Blueprint
add_app_template_filter(f, name=None) Register a custom template filter, available application wide. Like Flask.add_template_filter() but for a blueprint. Works exactly like the app_template_filter() decorator. Parameters name (Optional[str]) – the optional name of the filter, otherwise the function name will be used. f (Callable[[Any], str]) – Return type None
flask.api.index#flask.Blueprint.add_app_template_filter
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. Changelog New in version 0.10. Parameters name (Optional[str]) – the optional name of the global, otherwise the function name will be used. f (Callable[[], Any]) – Return type None
flask.api.index#flask.Blueprint.add_app_template_global
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. Changelog New in version 0.10. Parameters name (Optional[str]) – the optional name of the test, otherwise the function name will be used. f (Callable[[Any], bool]) – Return type None
flask.api.index#flask.Blueprint.add_app_template_test
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 prefixed with the name of the blueprint. Parameters rule (str) – endpoint (Optional[str]) – view_func (Optional[Callable]) – options (Any) – Return type None
flask.api.index#flask.Blueprint.add_url_rule
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. Parameters f (Callable[[Response], Response]) – Return type Callable[[Response], Response]
flask.api.index#flask.Blueprint.after_app_request
after_request(f) Register a function to run after each request to this object. The function is called with the response object, and must return a response object. This allows the functions to modify or replace the response before it is sent. If a function raises an exception, any remaining after_request functions will not be called. Therefore, this should not be used for actions that must execute, such as to close resources. Use teardown_request() for that. Parameters f (Callable[[Response], Response]) – Return type Callable[[Response], Response]
flask.api.index#flask.Blueprint.after_request
after_request_funcs: t.Dict[AppOrBlueprintKey, t.List[AfterRequestCallable]] A data structure of functions to call at the end of each request, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests. To register a function, use the after_request() decorator. This data structure is internal. It should not be modified directly and its format may change at any time.
flask.api.index#flask.Blueprint.after_request_funcs
app_context_processor(f) Like Flask.context_processor() but for a blueprint. Such a function is executed each request, even if outside of the blueprint. Parameters f (Callable[[], Dict[str, Any]]) – Return type Callable[[], Dict[str, Any]]
flask.api.index#flask.Blueprint.app_context_processor
app_errorhandler(code) Like Flask.errorhandler() but for a blueprint. This handler is used for all requests, even if outside of the blueprint. Parameters code (Union[Type[Exception], int]) – Return type Callable
flask.api.index#flask.Blueprint.app_errorhandler
app_template_filter(name=None) Register a custom template filter, available application wide. Like Flask.template_filter() but for a blueprint. Parameters name (Optional[str]) – the optional name of the filter, otherwise the function name will be used. Return type Callable
flask.api.index#flask.Blueprint.app_template_filter
app_template_global(name=None) Register a custom template global, available application wide. Like Flask.template_global() but for a blueprint. Changelog New in version 0.10. Parameters name (Optional[str]) – the optional name of the global, otherwise the function name will be used. Return type Callable
flask.api.index#flask.Blueprint.app_template_global
app_template_test(name=None) Register a custom template test, available application wide. Like Flask.template_test() but for a blueprint. Changelog New in version 0.10. Parameters name (Optional[str]) – the optional name of the test, otherwise the function name will be used. Return type Callable
flask.api.index#flask.Blueprint.app_template_test
app_url_defaults(f) Same as url_defaults() but application wide. Parameters f (Callable[[str, dict], None]) – Return type Callable[[str, dict], None]
flask.api.index#flask.Blueprint.app_url_defaults
app_url_value_preprocessor(f) Same as url_value_preprocessor() but application wide. Parameters f (Callable[[Optional[str], Optional[dict]], None]) – Return type Callable[[Optional[str], Optional[dict]], None]
flask.api.index#flask.Blueprint.app_url_value_preprocessor