text stringlengths 81 112k |
|---|
Resets the receive and transmit queues of the PCAN Channel
Remarks:
A reset of the CAN controller is not performed
Parameters:
Channel : A TPCANHandle representing a PCAN Channel
Returns:
A TPCANStatus error code
def Reset(
self,
Channel):
... |
Gets the current status of a PCAN Channel
Parameters:
Channel : A TPCANHandle representing a PCAN Channel
Returns:
A TPCANStatus error code
def GetStatus(
self,
Channel):
"""
Gets the current status of a PCAN Channel
Parameters:
... |
Reads a CAN message from the receive queue of a PCAN Channel
Remarks:
The return value of this method is a 3-touple, where
the first value is the result (TPCANStatus) of the method.
The order of the values are:
[0]: A TPCANStatus error code
[1]: A TPCANMsg stru... |
Reads a CAN message from the receive queue of a FD capable PCAN Channel
Remarks:
The return value of this method is a 3-touple, where
the first value is the result (TPCANStatus) of the method.
The order of the values are:
[0]: A TPCANStatus error code
[1]: A TP... |
Transmits a CAN message
Parameters:
Channel : A TPCANHandle representing a PCAN Channel
MessageBuffer: A TPCANMsg representing the CAN message to be sent
Returns:
A TPCANStatus error code
def Write(
self,
Channel,
MessageBuffer):
"""... |
Transmits a CAN message over a FD capable PCAN Channel
Parameters:
Channel : The handle of a FD capable PCAN Channel
MessageBuffer: A TPCANMsgFD buffer with the message to be sent
Returns:
A TPCANStatus error code
def WriteFD(
self,
Channel,
... |
Configures the reception filter
Remarks:
The message filter will be expanded with every call to this function.
If it is desired to reset the filter, please use the 'SetValue' function.
Parameters:
Channel : A TPCANHandle representing a PCAN Channel
FromID : A c... |
Retrieves a PCAN Channel value
Remarks:
Parameters can be present or not according with the kind
of Hardware (PCAN Channel) being used. If a parameter is not available,
a PCAN_ERROR_ILLPARAMTYPE error will be returned.
The return value of this method is a 2-touple, wher... |
Returns a descriptive text of a given TPCANStatus error
code, in any desired language
Remarks:
Parameters can be present or not according with the kind
of Hardware (PCAN Channel) being used. If a parameter is not available,
a PCAN_ERROR_ILLPARAMTYPE error will be returne... |
Configures or sets a PCAN Channel value
Remarks:
The current languages available for translation are:
Neutral (0x00), German (0x07), English (0x09), Spanish (0x0A),
Italian (0x10) and French (0x0C)
The return value of this method is a 2-touple, where
the firs... |
Add a message to the log file.
:param str message: an arbitrary message
:param float timestamp: the absolute timestamp of the event
def log_event(self, message, timestamp=None):
"""Add a message to the log file.
:param str message: an arbitrary message
:param float timestamp: ... |
Returns all currently used channels as well as
one other currently unused channel.
.. note::
This method will run into problems if thousands of
autodetected busses are used at once.
def _detect_available_configs():
"""
Returns all currently used channels as wel... |
convert the message from the CANAL type to pythoncan type
def message_convert_rx(message_rx):
"""convert the message from the CANAL type to pythoncan type"""
is_extended_id = bool(message_rx.flags & IS_ID_TYPE)
is_remote_frame = bool(message_rx.flags & IS_REMOTE_FRAME)
is_error_frame = bool(message_rx.... |
Shuts down connection to the device safely.
:raise cam.CanError: is closing the connection did not work
def shutdown(self):
"""
Shuts down connection to the device safely.
:raise cam.CanError: is closing the connection did not work
"""
status = self.can.close(self.hand... |
Uses the Windows Management Instrumentation to identify serial devices.
:param str serial_matcher (optional):
search string for automatic detection of the device serial
def _detect_available_configs(serial_matcher=None):
"""
Uses the Windows Management Instrumentation to identify s... |
Returns the main bus class for the given interface.
:raises:
NotImplementedError if the interface is not known
:raises:
ImportError if there was a problem while importing the
interface or the bus class within that
def _get_class_for_interface(interface):
"""
... |
Detect all configurations/channels that the interfaces could
currently connect with.
This might be quite time consuming.
Automated configuration detection may not be implemented by
every interface on every platform. This method will not raise
an error in that case, but with rather return an empty ... |
Add a bus for notification.
:param can.BusABC bus:
CAN bus instance.
def add_bus(self, bus):
"""Add a bus for notification.
:param can.BusABC bus:
CAN bus instance.
"""
if self._loop is not None and hasattr(bus, 'fileno') and bus.fileno() >= 0:
... |
Stop notifying Listeners when new :class:`~can.Message` objects arrive
and call :meth:`~can.Listener.stop` on each Listener.
:param float timeout:
Max time in seconds to wait for receive threads to finish.
Should be longer than timeout given at instantiation.
def stop(self, tim... |
Send a message over the serial device.
:param can.Message msg:
Message to send.
.. note:: Flags like ``extended_id``, ``is_remote_frame`` and
``is_error_frame`` will be ignored.
.. note:: If the timestamp is a float value it will be converted
... |
Read a message from the serial device.
:param timeout:
.. warning::
This parameter will be ignored. The timeout value of the channel is used.
:returns:
Received message and False (because not filtering as taken place).
.. warning::
... |
Sends a message every 20ms with no explicit timeout
Sleeps for 2 seconds then stops the task.
def simple_periodic_send(bus):
"""
Sends a message every 20ms with no explicit timeout
Sleeps for 2 seconds then stops the task.
"""
print("Starting to send a message every 200ms for 2s")
msg = can... |
Sends one CAN message.
When a transmission timeout is set the firmware tries to send
a message within this timeout. If it could not be sent the firmware sets
the "auto delete" state. Within this state all transmit CAN messages for
this channel will be deleted automatically for not block... |
Flushes the transmit buffer.
:raises can.CanError:
If flushing of the transmit buffer failed.
def flush_tx_buffer(self):
"""
Flushes the transmit buffer.
:raises can.CanError:
If flushing of the transmit buffer failed.
"""
log.info('Flushing tra... |
Calculates AMR and ACR using CAN-ID as parameter.
:param bool extended:
if True parameters from_id and to_id contains 29-bit CAN-ID
:param int from_id:
first CAN-ID which should be received
:param int to_id:
last CAN-ID which should be received
:pa... |
Shuts down all CAN interfaces and hardware interface.
def shutdown(self):
"""
Shuts down all CAN interfaces and hardware interface.
"""
try:
self._ucan.shutdown()
except Exception as ex:
log.error(ex) |
Loads configuration from file with following content::
[default]
interface = socketcan
channel = can0
:param path:
path to config file. If not specified, several sensible
default locations are tried depending on platform.
:param section:
name of the section to r... |
Loads config dict from environmental variables (if set):
* CAN_INTERFACE
* CAN_CHANNEL
* CAN_BITRATE
def load_environment_config():
"""
Loads config dict from environmental variables (if set):
* CAN_INTERFACE
* CAN_CHANNEL
* CAN_BITRATE
"""
mapper = {
'interface': 'CA... |
Returns a dict with configuration details which is loaded from (in this order):
- config
- can.rc
- Environment variables CAN_INTERFACE, CAN_CHANNEL, CAN_BITRATE
- Config files ``/etc/can.conf`` or ``~/.can`` or ``~/.canrc``
where the latter may add or replace values of the former.
Interface... |
Set the logging level for the "can" logger.
Expects one of: 'critical', 'error', 'warning', 'info', 'debug', 'subdebug'
def set_logging_level(level_name=None):
"""Set the logging level for the "can" logger.
Expects one of: 'critical', 'error', 'warning', 'info', 'debug', 'subdebug'
"""
can_logger =... |
Calculate the DLC from data length.
:param int length: Length in number of bytes (0-64)
:returns: DLC (0-15)
:rtype: int
def len2dlc(length):
"""Calculate the DLC from data length.
:param int length: Length in number of bytes (0-64)
:returns: DLC (0-15)
:rtype: int
"""
if length... |
Try to convert the channel to an integer.
:param channel:
Channel string (e.g. can0, CAN1) or integer
:returns: Channel integer or `None` if unsuccessful
:rtype: int
def channel2int(channel):
"""Try to convert the channel to an integer.
:param channel:
Channel string (e.g. ca... |
Block waiting for a message from the Bus.
:type timeout: float or None
:param timeout:
seconds to wait for a message or None to wait indefinitely
:rtype: can.Message or None
:return:
None on timeout or a :class:`can.Message` object.
:raises can.CanError:... |
Start sending a message at a given period on this bus.
The task will be active until one of the following conditions are met:
- the (optional) duration expires
- the Bus instance goes out of scope
- the Bus instance is shutdown
- :meth:`BusABC.stop_all_periodic_tasks()` is call... |
Default implementation of periodic message sending using threading.
Override this method to enable a more efficient backend specific approach.
:param can.Message msg:
Message to transmit
:param float period:
Period in seconds between each message
:param float du... |
Stop sending any messages that were started using bus.send_periodic
:param bool remove_tasks:
Stop tracking the stopped tasks.
def stop_all_periodic_tasks(self, remove_tasks=True):
"""Stop sending any messages that were started using bus.send_periodic
:param bool remove_tasks:
... |
Apply filtering to all messages received by this Bus.
All messages that match at least one filter are returned.
If `filters` is `None` or a zero length sequence, all
messages are matched.
Calling without passing any filters will reset the applied
filters to `None`.
:pa... |
Checks whether the given message matches at least one of the
current filters. See :meth:`~can.BusABC.set_filters` for details
on how the filters work.
This method should not be overridden.
:param can.Message msg:
the message to check if matching
:rtype: bool
... |
Checks if function :meth:`UcanServer.read_can_msg` returns a valid CAN message.
:param ReturnCode result: Error code of the function.
:return: True if a valid CAN messages was received, otherwise False.
:rtype: bool
def check_valid_rx_can_msg(result):
"""
Checks if function :meth:`UcanServer.read_... |
Checks if function :meth:`UcanServer.write_can_msg` successfully wrote CAN message(s).
While using :meth:`UcanServer.write_can_msg_ex` the number of sent CAN messages can be less than
the number of CAN messages which should be sent.
:param ReturnCode result: Error code of the function.
:return: True i... |
Checks if any function returns an error from USB-CAN-library.
:param ReturnCode result: Error code of the function.
:return: True if a function returned error, otherwise False.
:rtype: bool
def check_error(result):
"""
Checks if any function returns an error from USB-CAN-library.
:param Retur... |
Checks if any function returns an error from firmware in USB-CANmodul.
:param ReturnCode result: Error code of the function.
:return: True if a function returned error from firmware, otherwise False.
:rtype: bool
def check_error_cmd(result):
"""
Checks if any function returns an error from firmwar... |
Initializes the device with the corresponding serial or device number.
:param int or None serial: Serial number of the USB-CANmodul.
:param int device_number: Device number (0 – 254, or :const:`ANY_MODULE` for the first device).
def init_hardware(self, serial=None, device_number=ANY_MODULE):
"... |
Initializes a specific CAN channel of a device.
:param int channel: CAN channel to be initialized (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:param int BTR:
Baud rate register BTR0 as high byte, baud rate register BTR1 as low byte (see enum :class:`Baudrate`).
:pa... |
Reads one or more CAN-messages from the buffer of the specified CAN channel.
:param int channel:
CAN channel to read from (:data:`Channel.CHANNEL_CH0`, :data:`Channel.CHANNEL_CH1`,
:data:`Channel.CHANNEL_ANY`).
:param int count: The number of CAN messages to be received.
... |
Transmits one ore more CAN messages through the specified CAN channel of the device.
:param int channel:
CAN channel, which is to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:param list(CanMsg) can_msg: List of CAN message structure (see structure :class:`CanMsg`).... |
This function is used to configure the baud rate of specific CAN channel of a device.
:param int channel:
CAN channel, which is to be configured (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:param int BTR:
Baud rate register BTR0 as high byte, baud rate register... |
This function is used to change the acceptance filter values for a specific CAN channel on a device.
:param int channel:
CAN channel, which is to be configured (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:param int AMR: Acceptance filter mask (AMR).
:param int ACR:... |
Returns the error status of a specific CAN channel.
:param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:return: Tuple with CAN and USB status (see structure :class:`Status`).
:rtype: tuple(int, int)
def get_status(self, channel=Channel.CHA... |
Reads the message counters of the specified CAN channel.
:param int channel:
CAN channel, which is to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:return: Tuple with number of CAN messages sent and received.
:rtype: tuple(int, int)
def get_msg_count_info(s... |
Resets a CAN channel of a device (hardware reset, empty buffer, and so on).
:param int channel: CAN channel, to be reset (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:param int flags: Flags defines what should be reset (see enum :class:`ResetFlags`).
def reset_can(self, channel=Channe... |
Returns the extended hardware information of a device. With multi-channel USB-CANmoduls the information for
both CAN channels are returned separately.
:return:
Tuple with extended hardware information structure (see structure :class:`HardwareInfoEx`) and
structures with informat... |
Defines a list of CAN messages for automatic transmission.
:param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:param list(CanMsg) can_msg:
List of CAN messages (up to 16, see structure :class:`CanMsg`), or None to delete an older list.
... |
Reads back the list of CAN messages for automatically sending.
:param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:param int count: The number of cyclic CAN messages to be received.
:return: List of received CAN messages (up to 16, see stru... |
Returns the number of pending CAN messages.
:param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:param int flags: Flags specifies which buffers should be checked (see enum :class:`PendingFlags`).
:return: The number of pending messages.
... |
Reads the current value of the error counters within the CAN controller.
:param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:return: Tuple with the TX and RX error counter.
:rtype: tuple(int, int)
.. note:: Only available for syste... |
Sets the transmission timeout.
:param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:param float timeout: Transmit timeout in seconds (value 0 disables this feature).
def set_tx_timeout(self, channel, timeout):
"""
Sets the transmiss... |
Shuts down all CAN interfaces and/or the hardware interface.
:param int channel:
CAN channel, to be used (:data:`Channel.CHANNEL_CH0`, :data:`Channel.CHANNEL_CH1` or
:data:`Channel.CHANNEL_ALL`)
:param bool shutdown_hardware: If true then the hardware interface will be closed to... |
Converts a given CAN status value to the appropriate message string.
:param can_status: CAN status value from method :meth:`get_status` (see enum :class:`CanStatus`)
:return: Status message string.
:rtype: str
def get_can_status_message(can_status):
"""
Converts a given CAN sta... |
Converts a given baud rate value for GW-001/GW-002 to the appropriate message string.
:param Baudrate baudrate:
Bus Timing Registers, BTR0 in high order byte and BTR1 in low order byte
(see enum :class:`Baudrate`)
:return: Baud rate message string.
:rtype: str
def get_b... |
Converts a given baud rate value for systec USB-CANmoduls to the appropriate message string.
:param BaudrateEx baudrate_ex: Bus Timing Registers (see enum :class:`BaudrateEx`)
:return: Baud rate message string.
:rtype: str
def get_baudrate_ex_message(baudrate_ex):
"""
Converts ... |
Checks if the version is equal or higher than a specified value.
:param int version: Version number to be checked.
:param int cmp_major: Major version to be compared with.
:param int cmp_minor: Minor version to be compared with.
:return: True if equal or higher, otherwise False.
... |
Checks whether the module supports automatically transmission of cyclic CAN messages.
:param HardwareInfoEx hw_info_ex:
Extended hardware information structure (see method :meth:`get_hardware_info`).
:return: True when the module does support cyclic CAN messages, otherwise False.
:r... |
Checks whether the module supports a user I/O port.
:param HardwareInfoEx hw_info_ex:
Extended hardware information structure (see method :meth:`get_hardware_info`).
:return: True when the module supports a user I/O port, otherwise False.
:rtype: bool
def check_support_user_port(cl... |
Checks whether the module supports the usage of USB-CANnetwork driver.
:param HardwareInfoEx hw_info_ex:
Extended hardware information structure (see method :meth:`get_hardware_info`).
:return: True when the module does support the usage of the USB-CANnetwork driver, otherwise False.
... |
Calculates AMR using CAN-ID range as parameter.
:param bool is_extended: If True parameters from_id and to_id contains 29-bit CAN-ID.
:param int from_id: First CAN-ID which should be received.
:param int to_id: Last CAN-ID which should be received.
:param bool rtr_only: If True only RTR... |
Is the actual callback function for :meth:`init_hw_connect_control_ex`.
:param event:
Event (:data:`CbEvent.EVENT_CONNECT`, :data:`CbEvent.EVENT_DISCONNECT` or
:data:`CbEvent.EVENT_FATALDISCON`).
:param param: Additional parameter depending on the event.
- CbEvent.EVENT_... |
Is called if a working event occurred.
:param int handle: USB-CAN-Handle returned by the function :meth:`init_hardware`.
:param int event: Event type.
:param int channel:
CAN channel (:data:`Channel.CHANNEL_CH0`, :data:`Channel.CHANNEL_CH1` or :data:`Channel.CHANNEL_ANY`).
:... |
Colors API using schema
This example is using marshmallow schemas
def get(self, palette):
"""
Colors API using schema
This example is using marshmallow schemas
"""
all_colors = {
'cmyk': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'gree... |
Custom validation function which drops parameter '_id' if present
in data
def drop_id_validate(data, schema):
"""
Custom validation function which drops parameter '_id' if present
in data
"""
jsonschema.validate(data, schema)
if data.get('_id') is not None:
del data['_id'] |
Custom validation function which inserts a timestamp for when the
validation occurred
def timestamping_validate(data, schema):
"""
Custom validation function which inserts a timestamp for when the
validation occurred
"""
jsonschema.validate(data, schema)
data['timestamp'] = str(time.time()) |
Custom validation function which inserts an special flag depending
on the cat's name
def special_validate(data, schema):
"""
Custom validation function which inserts an special flag depending
on the cat's name
"""
jsonschema.validate(data, schema)
data['special'] = str(data['name'] == 'Garf... |
Custom validation error handler which produces 404 Bad Request
response in case validation fails and returns the error
def validation_error_inform_error(err, data, schema):
"""
Custom validation error handler which produces 404 Bad Request
response in case validation fails and returns the error
"""... |
Custom validation error handler which attempts alternative
validation
def validation_error_try_to_accept(err, data, schema):
"""
Custom validation error handler which attempts alternative
validation
"""
if not isinstance(err, ValidationError):
abort(Response(err, status=HTTPStatus.BAD_R... |
Convert Marshmallow schemas to dict definitions
Also updates the optional definitions argument with any definitions
entries contained within the schema.
def convert_schemas(d, definitions=None):
"""
Convert Marshmallow schemas to dict definitions
Also updates the optional definitions argument wit... |
Converts APISpec dict to flasgger suitable dict
also adds definitions and paths (optional)
def to_flasgger(self, app=None, definitions=None, paths=None):
"""
Converts APISpec dict to flasgger suitable dict
also adds definitions and paths (optional)
"""
if Schema is None:... |
If validation=True perform validation
def dispatch_request(self, *args, **kwargs):
"""
If validation=True perform validation
"""
if self.validation:
specs = {}
attrs = flasgger.constants.OPTIONAL_FIELDS + [
'parameters', 'definitions', 'responses'... |
Update target dictionary with values from the source, recursively.
List items will be merged.
def merge_specs(target, source):
"""
Update target dictionary with values from the source, recursively.
List items will be merged.
"""
for key, value in source.items():
if isinstance(value, di... |
Takes a filename.yml, a dictionary or object and loads swagger specs.
:param specs: a filepath, a dictionary or an object
:param filetype: yml or yaml (json and py to be implemented)
:param endpoint: endpoint to build definition name
:param methods: method to build method based specs
:param validat... |
This method is available to use YAML swagger definitions file
or specs (dict or object) to validate data against its jsonschema.
example:
validate({"item": 1}, 'item_schema', 'defs.yml', root=__file__)
validate(request.json, 'User', specs={'definitions': {'User': ...}})
:param data: data t... |
Converts apispec object in to flasgger definitions template
:param app: Current app
:param spec: apispec.APISpec
:param definitions: a list of [Schema, ..] or [('Name', Schema), ..]
:param paths: A list of flask views
def apispec_to_template(app, spec, definitions=None, paths=None):
"""
Convert... |
Converts inner OrderedDict to bare dict
def ordered_dict_to_dict(d):
"""
Converts inner OrderedDict to bare dict
"""
ret = {}
new_d = deepcopy(d)
for k, v in new_d.items():
if isinstance(v, OrderedDict):
v = dict(v)
if isinstance(v, dict):
v = ordered_dic... |
*nix to python module path
def pathify(basenames, examples_dir="examples/"): # pragma: no cover
"""*nix to python module path"""
example = examples_dir.replace("/", ".")
return [example + basename for basename in basenames] |
All example modules
def get_examples(examples_dir="examples/"): # pragma: no cover
"""All example modules"""
all_files = os.listdir(examples_dir)
python_files = [f for f in all_files if is_python_file(f)]
basenames = [remove_suffix(f) for f in python_files]
modules = [import_module(module) for mod... |
If `file:` is provided import the file.
def get_path_from_doc(full_doc):
"""
If `file:` is provided import the file.
"""
swag_path = full_doc.replace('file:', '').strip()
swag_type = swag_path.split('.')[-1]
return swag_path, swag_type |
Load specs from YAML file
def load_from_file(swag_path, swag_type='yml', root_path=None):
"""
Load specs from YAML file
"""
if swag_type not in ('yaml', 'yml'):
raise AttributeError("Currently only yaml or yml supported")
# TODO: support JSON
try:
enc = detect_by_bom(swag_p... |
Gets swag data for method/view docstring
def parse_docstring(obj, process_doc, endpoint=None, verb=None):
"""
Gets swag data for method/view docstring
"""
first_line, other_lines, swag = None, None, None
full_doc = None
swag_path = getattr(obj, 'swag_path', None)
swag_type = getattr(obj, '... |
Get file path for object and returns its dirname
def get_root_path(obj):
"""
Get file path for object and returns its dirname
"""
try:
filename = os.path.abspath(obj.__globals__['__file__'])
except (KeyError, AttributeError):
if getattr(obj, '__wrapped__', None):
# decor... |
Gets swag data from docstring for class based definitions
def parse_definition_docstring(obj, process_doc):
"""
Gets swag data from docstring for class based definitions
"""
doc_lines, swag = None, None
full_doc = None
swag_path = getattr(obj, 'swag_path', None)
swag_type = getattr(obj, 's... |
Supports `import: otherfile.yml` in docstring specs
def parse_imports(full_doc, root_path=None):
"""
Supports `import: otherfile.yml` in docstring specs
"""
regex = re.compile('import: "(.*)"')
import_prop = regex.search(full_doc)
if import_prop:
start = import_prop.start()
spac... |
Since we couldn't be bothered to register models elsewhere
our definitions need to be extracted from the parameters.
We require an 'id' field for the schema to be correctly
added to the definitions list.
def extract_definitions(alist, level=None, endpoint=None, verb=None,
prefix_ids... |
Return True if dispatch_request is swaggable
def has_valid_dispatch_view_docs(endpoint):
"""
Return True if dispatch_request is swaggable
"""
klass = endpoint.__dict__.get('view_class', None)
return klass and hasattr(klass, 'dispatch_request') \
and hasattr(endpoint, 'methods') \
an... |
Return True if obj is MethodView
def is_valid_method_view(endpoint):
"""
Return True if obj is MethodView
"""
klass = endpoint.__dict__.get('view_class', None)
try:
return issubclass(klass, MethodView)
except TypeError:
return False |
Identify vendor extension fields and extract them into a new dictionary.
Examples:
>>> get_vendor_extension_fields({'test': 1})
{}
>>> get_vendor_extension_fields({'test': 1, 'x-test': 2})
{'x-test': 2}
def get_vendor_extension_fields(mapping):
"""
Identify vendor extension ... |
User authenticate method.
---
description: Authenticate user with supplied credentials.
parameters:
- name: username
in: formData
type: string
required: true
- name: password
in: formData
type: string
required: true
responses:
200:
... |
The data under /apidocs
json or Swagger UI
def get(self):
"""
The data under /apidocs
json or Swagger UI
"""
base_endpoint = self.config.get('endpoint', 'flasgger')
specs = [
{
"url": url_for(".".join((base_endpoint, spec['endpoint']))... |
Initialize the app with Swagger plugin
def init_app(self, app, decorators=None):
"""
Initialize the app with Swagger plugin
"""
self.decorators = decorators or self.decorators
self.app = app
self.load_config(app)
# self.load_apispec(app)
if self.template... |
Returns all werkzeug rules
def get_url_mappings(self, rule_filter=None):
"""
Returns all werkzeug rules
"""
rule_filter = rule_filter or (lambda rule: True)
app_rules = [
rule for rule in current_app.url_map.iter_rules()
if rule_filter(rule)
]
... |
Used for class based definitions
def get_def_models(self, definition_filter=None):
"""
Used for class based definitions
"""
model_filter = definition_filter or (lambda tag: True)
return {
definition.name: definition.obj
for definition in self.definition_m... |
Decorator to add class based definitions
def definition(self, name, tags=None):
"""
Decorator to add class based definitions
"""
def wrapper(obj):
self.definition_models.append(SwaggerDefinition(name, obj,
tags=tags... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.