INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Binds the parameter value specified by binding_key to value. | def bind_parameter(binding_key, value):
"""Binds the parameter value specified by `binding_key` to `value`.
The `binding_key` argument should either be a string of the form
`maybe/scope/optional.module.names.configurable_name.parameter_name`, or a
list or tuple of `(scope, selector, parameter_name)`, where `se... |
Returns the currently bound value to the specified binding_key. | def query_parameter(binding_key):
"""Returns the currently bound value to the specified `binding_key`.
The `binding_key` argument should look like
'maybe/some/scope/maybe.moduels.configurable_name.parameter_name'. Note that
this will not include default parameters.
Args:
binding_key: The parameter whose... |
Returns True if arg_name might be a valid parameter for fn_or_cls. | def _might_have_parameter(fn_or_cls, arg_name):
"""Returns True if `arg_name` might be a valid parameter for `fn_or_cls`.
Specifically, this means that `fn_or_cls` either has a parameter named
`arg_name`, or has a `**kwargs` parameter.
Args:
fn_or_cls: The function or class to check.
arg_name: The nam... |
Gets cached argspec for fn. | def _get_cached_arg_spec(fn):
"""Gets cached argspec for `fn`."""
arg_spec = _ARG_SPEC_CACHE.get(fn)
if arg_spec is None:
arg_spec_fn = inspect.getfullargspec if six.PY3 else inspect.getargspec
try:
arg_spec = arg_spec_fn(fn)
except TypeError:
# `fn` might be a callable object.
arg_... |
Returns the names of the supplied arguments to the given function. | def _get_supplied_positional_parameter_names(fn, args):
"""Returns the names of the supplied arguments to the given function."""
arg_spec = _get_cached_arg_spec(fn)
# May be shorter than len(args) if args contains vararg (*args) arguments.
return arg_spec.args[:len(args)] |
Returns the names of all positional arguments to the given function. | def _get_all_positional_parameter_names(fn):
"""Returns the names of all positional arguments to the given function."""
arg_spec = _get_cached_arg_spec(fn)
args = arg_spec.args
if arg_spec.defaults:
args = args[:-len(arg_spec.defaults)]
return args |
Retrieve all default values for configurable parameters of a function. | def _get_default_configurable_parameter_values(fn, whitelist, blacklist):
"""Retrieve all default values for configurable parameters of a function.
Any parameters included in the supplied blacklist, or not included in the
supplied whitelist, are excluded.
Args:
fn: The function whose parameter values shou... |
Opens a new configuration scope. | def config_scope(name_or_scope):
"""Opens a new configuration scope.
Provides a context manager that opens a new explicit configuration
scope. Explicit configuration scopes restrict parameter bindings to only
certain sections of code that run within the scope. Scopes can be nested to
arbitrary depth; any con... |
Wraps fn_or_cls to make it configurable. | def _make_configurable(fn_or_cls,
name=None,
module=None,
whitelist=None,
blacklist=None,
subclass=False):
"""Wraps `fn_or_cls` to make it configurable.
Infers the configurable name from `fn_or_cls.__... |
Decorator to make a function or class configurable. | def configurable(name_or_fn=None, module=None, whitelist=None, blacklist=None):
"""Decorator to make a function or class configurable.
This decorator registers the decorated function/class as configurable, which
allows its parameters to be supplied from the global configuration (i.e., set
through `bind_paramet... |
Allow referencing/ configuring an external class or function. | def external_configurable(fn_or_cls,
name=None,
module=None,
whitelist=None,
blacklist=None):
"""Allow referencing/configuring an external class or function.
This alerts Gin to the existence of the class or func... |
Retrieve the operative configuration as a config string. | def operative_config_str(max_line_length=80, continuation_indent=4):
"""Retrieve the "operative" configuration as a config string.
The operative configuration consists of all parameter values used by
configurable functions that are actually called during execution of the
current program. Parameters associated ... |
Parse a file string or list of strings containing parameter bindings. | def parse_config(bindings, skip_unknown=False):
"""Parse a file, string, or list of strings containing parameter bindings.
Parses parameter binding strings to set up the global configuration. Once
`parse_config` has been called, any calls to configurable functions will have
parameter values set according to t... |
Register a file reader for use in parse_config_file. | def register_file_reader(*args):
"""Register a file reader for use in parse_config_file.
Registered file readers will be used to try reading files passed to
`parse_config_file`. All file readers (beginning with the default `open`) will
be tried until one of them succeeds at opening the file.
This function m... |
Parse a Gin config file. | def parse_config_file(config_file, skip_unknown=False):
"""Parse a Gin config file.
Args:
config_file: The path to a Gin config file.
skip_unknown: A boolean indicating whether unknown configurables and imports
should be skipped instead of causing errors (alternatively a list of
configurable na... |
Parse a list of config files followed by extra Gin bindings. | def parse_config_files_and_bindings(config_files,
bindings,
finalize_config=True,
skip_unknown=False):
"""Parse a list of config files followed by extra Gin bindings.
This function is equivalent to:
f... |
Parse and return a single Gin value. | def parse_value(value):
"""Parse and return a single Gin value."""
if not isinstance(value, six.string_types):
raise ValueError('value ({}) should be a string type.'.format(value))
return config_parser.ConfigParser(value, ParserDelegate()).parse_value() |
A function that should be called after parsing all Gin config files. | def finalize():
"""A function that should be called after parsing all Gin config files.
Calling this function allows registered "finalize hooks" to inspect (and
potentially modify) the Gin config, to provide additional functionality. Hooks
should not modify the configuration object they receive directly; inste... |
Provides an iterator over all values in a nested structure. | def _iterate_flattened_values(value):
"""Provides an iterator over all values in a nested structure."""
if isinstance(value, six.string_types):
yield value
return
if isinstance(value, collections.Mapping):
value = collections.ValuesView(value)
if isinstance(value, collections.Iterable):
for ne... |
Provides an iterator over references in the given config. | def iterate_references(config, to=None):
"""Provides an iterator over references in the given config.
Args:
config: A dictionary mapping scoped configurable names to argument bindings.
to: If supplied, only yield references whose `configurable_fn` matches `to`.
Yields:
`ConfigurableReference` instan... |
Creates a constant that can be referenced from gin config files. | def constant(name, value):
"""Creates a constant that can be referenced from gin config files.
After calling this function in Python, the constant can be referenced from
within a Gin config file using the macro syntax. For example, in Python:
gin.constant('THE_ANSWER', 42)
Then, in a Gin config file:
... |
Decorator for an enum class that generates Gin constants from values. | def constants_from_enum(cls, module=None):
"""Decorator for an enum class that generates Gin constants from values.
Generated constants have format `module.ClassName.ENUM_VALUE`. The module
name is optional when using the constant.
Args:
cls: Class type.
module: The module to associate with the consta... |
Hook to find/ raise errors for references to unknown configurables. | def find_unknown_references_hook(config):
"""Hook to find/raise errors for references to unknown configurables."""
additional_msg_fmt = " In binding for '{}'."
for (scope, selector), param_bindings in six.iteritems(config):
for param_name, param_value in six.iteritems(param_bindings):
for maybe_unknown ... |
Retrieves all selectors matching partial_selector. | def matching_selectors(self, partial_selector):
"""Retrieves all selectors matching `partial_selector`.
For instance, if "one.a.b" and "two.a.b" are stored in a `SelectorMap`, both
`matching_selectors('b')` and `matching_selectors('a.b')` will return them.
In the event that `partial_selector` exactly ... |
Gets a ( single ) value matching partial_selector. | def get_match(self, partial_selector, default=None):
"""Gets a (single) value matching `partial_selector`.
If the partial_selector exactly matches a complete selector, the value
associated with the complete selector is returned.
Args:
partial_selector: The partial selector to find values for.
... |
Returns all values matching partial_selector as a list. | def get_all_matches(self, partial_selector):
"""Returns all values matching `partial_selector` as a list."""
matching_selectors = self.matching_selectors(partial_selector)
return [self._selector_map[selector] for selector in matching_selectors] |
Returns the minimal selector that uniquely matches complete_selector. | def minimal_selector(self, complete_selector):
"""Returns the minimal selector that uniquely matches `complete_selector`.
Args:
complete_selector: A complete selector stored in the map.
Returns:
A partial selector that unambiguously matches `complete_selector`.
Raises:
KeyError: If ... |
Translate a Mopidy search query to a Spotify search query | def sp_search_query(query):
"""Translate a Mopidy search query to a Spotify search query"""
result = []
for (field, values) in query.items():
field = SEARCH_FIELD_MAP.get(field, field)
if field is None:
continue
for value in values:
if field == 'year':
... |
Parse Retry - After header from response if it is set. | def _parse_retry_after(self, response):
"""Parse Retry-After header from response if it is set."""
value = response.headers.get('Retry-After')
if not value:
seconds = 0
elif re.match(r'^\s*[0-9]+\s*$', value):
seconds = int(value)
else:
date_t... |
Validate new property value before setting it. | def validate_value(self, value):
"""
Validate new property value before setting it.
value -- New value
"""
if 'readOnly' in self.metadata and self.metadata['readOnly']:
raise PropertyError('Read-only property')
try:
validate(value, self.metadata)... |
Get the property description. | def as_property_description(self):
"""
Get the property description.
Returns a dictionary describing the property.
"""
description = deepcopy(self.metadata)
if 'links' not in description:
description['links'] = []
description['links'].append(
... |
Set the current value of the property. | def set_value(self, value):
"""
Set the current value of the property.
value -- the value to set
"""
self.validate_value(value)
self.value.set(value) |
Get the thing at the given index. | def get_thing(self, idx):
"""
Get the thing at the given index.
idx -- the index
"""
try:
idx = int(idx)
except ValueError:
return None
if idx < 0 or idx >= len(self.things):
return None
return self.things[idx] |
Initialize the handler. | def initialize(self, things, hosts):
"""
Initialize the handler.
things -- list of Things managed by this server
hosts -- list of allowed hostnames
"""
self.things = things
self.hosts = hosts |
Set the default headers for all requests. | def set_default_headers(self, *args, **kwargs):
"""Set the default headers for all requests."""
self.set_header('Access-Control-Allow-Origin', '*')
self.set_header('Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept')
self.set_header('A... |
Handle a GET request. | def get(self):
"""
Handle a GET request.
property_name -- the name of the property from the URL path
"""
self.set_header('Content-Type', 'application/json')
ws_href = '{}://{}'.format(
'wss' if self.request.protocol == 'https' else 'ws',
self.requ... |
Validate Host header. | def prepare(self):
"""Validate Host header."""
host = self.request.headers.get('Host', None)
if host is not None and host in self.hosts:
return
raise tornado.web.HTTPError(403) |
Handle a GET request including websocket requests. | def get(self, thing_id='0'):
"""
Handle a GET request, including websocket requests.
thing_id -- ID of the thing this request is for
"""
self.thing = self.get_thing(thing_id)
if self.thing is None:
self.set_status(404)
self.finish()
re... |
Handle an incoming message. | def on_message(self, message):
"""
Handle an incoming message.
message -- message to handle
"""
try:
message = json.loads(message)
except ValueError:
try:
self.write_message(json.dumps({
'messageType': 'error',
... |
Handle a GET request. | def get(self, thing_id='0', property_name=None):
"""
Handle a GET request.
thing_id -- ID of the thing this request is for
property_name -- the name of the property from the URL path
"""
thing = self.get_thing(thing_id)
if thing is None:
self.set_stat... |
Handle a PUT request. | def put(self, thing_id='0', property_name=None):
"""
Handle a PUT request.
thing_id -- ID of the thing this request is for
property_name -- the name of the property from the URL path
"""
thing = self.get_thing(thing_id)
if thing is None:
self.set_stat... |
Handle a POST request. | def post(self, thing_id='0'):
"""
Handle a POST request.
thing_id -- ID of the thing this request is for
"""
thing = self.get_thing(thing_id)
if thing is None:
self.set_status(404)
return
try:
message = json.loads(self.request... |
Handle a GET request. | def get(self, thing_id='0', action_name=None, action_id=None):
"""
Handle a GET request.
thing_id -- ID of the thing this request is for
action_name -- name of the action from the URL path
action_id -- the action ID from the URL path
"""
thing = self.get_thing(th... |
Handle a PUT request. | def put(self, thing_id='0', action_name=None, action_id=None):
"""
Handle a PUT request.
TODO: this is not yet defined in the spec
thing_id -- ID of the thing this request is for
action_name -- name of the action from the URL path
action_id -- the action ID from the URL... |
Handle a DELETE request. | def delete(self, thing_id='0', action_name=None, action_id=None):
"""
Handle a DELETE request.
thing_id -- ID of the thing this request is for
action_name -- name of the action from the URL path
action_id -- the action ID from the URL path
"""
thing = self.get_th... |
Handle a GET request. | def get(self, thing_id='0'):
"""
Handle a GET request.
thing_id -- ID of the thing this request is for
"""
thing = self.get_thing(thing_id)
if thing is None:
self.set_status(404)
return
self.set_header('Content-Type', 'application/json')
... |
Start listening for incoming connections. | def start(self):
"""Start listening for incoming connections."""
self.service_info = ServiceInfo(
'_webthing._tcp.local.',
'{}._webthing._tcp.local.'.format(self.name),
address=socket.inet_aton(get_ip()),
port=self.port,
properties={
... |
Stop listening. | def stop(self):
"""Stop listening."""
self.zeroconf.unregister_service(self.service_info)
self.zeroconf.close()
self.server.stop() |
Get the action description. | def as_action_description(self):
"""
Get the action description.
Returns a dictionary describing the action.
"""
description = {
self.name: {
'href': self.href_prefix + self.href,
'timeRequested': self.time_requested,
'... |
Start performing the action. | def start(self):
"""Start performing the action."""
self.status = 'pending'
self.thing.action_notify(self)
self.perform_action()
self.finish() |
Finish performing the action. | def finish(self):
"""Finish performing the action."""
self.status = 'completed'
self.time_completed = timestamp()
self.thing.action_notify(self) |
Get the event description. | def as_event_description(self):
"""
Get the event description.
Returns a dictionary describing the event.
"""
description = {
self.name: {
'timestamp': self.time,
},
}
if self.data is not None:
description[self... |
Get the default local IP address. | def get_ip():
"""
Get the default local IP address.
From: https://stackoverflow.com/a/28950776
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('10.255.255.255', 1))
ip = s.getsockname()[0]
except (socket.error, IndexError):
ip = '127.0.0.1'
... |
Get all IP addresses. | def get_addresses():
"""
Get all IP addresses.
Returns list of addresses.
"""
addresses = set()
for iface in ifaddr.get_adapters():
for addr in iface.ips:
# Filter out link-local addresses.
if addr.is_IPv4:
ip = addr.ip
if not ip... |
Set a new value for this thing. | def set(self, value):
"""
Set a new value for this thing.
value -- value to set
"""
if self.value_forwarder is not None:
self.value_forwarder(value)
self.notify_of_external_update(value) |
Notify observers of a new value. | def notify_of_external_update(self, value):
"""
Notify observers of a new value.
value -- new value
"""
if value is not None and value != self.last_value:
self.last_value = value
self.emit('update', value) |
Return the thing state as a Thing Description. | def as_thing_description(self):
"""
Return the thing state as a Thing Description.
Returns the state as a dictionary.
"""
thing = {
'name': self.name,
'href': self.href_prefix if self.href_prefix else '/',
'@context': self.context,
... |
Set the prefix of any hrefs associated with this thing. | def set_href_prefix(self, prefix):
"""
Set the prefix of any hrefs associated with this thing.
prefix -- the prefix
"""
self.href_prefix = prefix
for property_ in self.properties.values():
property_.set_href_prefix(prefix)
for action_name in self.ac... |
Get the thing s properties as a dictionary. | def get_property_descriptions(self):
"""
Get the thing's properties as a dictionary.
Returns the properties as a dictionary, i.e. name -> description.
"""
return {k: v.as_property_description()
for k, v in self.properties.items()} |
Get the thing s actions as an array. | def get_action_descriptions(self, action_name=None):
"""
Get the thing's actions as an array.
action_name -- Optional action name to get descriptions for
Returns the action descriptions.
"""
descriptions = []
if action_name is None:
for name in self... |
Get the thing s events as an array. | def get_event_descriptions(self, event_name=None):
"""
Get the thing's events as an array.
event_name -- Optional event name to get descriptions for
Returns the event descriptions.
"""
if event_name is None:
return [e.as_event_description() for e in self.eve... |
Add a property to this thing. | def add_property(self, property_):
"""
Add a property to this thing.
property_ -- property to add
"""
property_.set_href_prefix(self.href_prefix)
self.properties[property_.name] = property_ |
Remove a property from this thing. | def remove_property(self, property_):
"""
Remove a property from this thing.
property_ -- property to remove
"""
if property_.name in self.properties:
del self.properties[property_.name] |
Get a property s value. | def get_property(self, property_name):
"""
Get a property's value.
property_name -- the property to get the value of
Returns the properties value, if found, else None.
"""
prop = self.find_property(property_name)
if prop:
return prop.get_value()
... |
Get a mapping of all properties and their values. | def get_properties(self):
"""
Get a mapping of all properties and their values.
Returns a dictionary of property_name -> value.
"""
return {prop.get_name(): prop.get_value()
for prop in self.properties.values()} |
Set a property value. | def set_property(self, property_name, value):
"""
Set a property value.
property_name -- name of the property to set
value -- value to set
"""
prop = self.find_property(property_name)
if not prop:
return
prop.set_value(value) |
Get an action. | def get_action(self, action_name, action_id):
"""
Get an action.
action_name -- name of the action
action_id -- ID of the action
Returns the requested action if found, else None.
"""
if action_name not in self.actions:
return None
for action... |
Add a new event and notify subscribers. | def add_event(self, event):
"""
Add a new event and notify subscribers.
event -- the event that occurred
"""
self.events.append(event)
self.event_notify(event) |
Add an available event. | def add_available_event(self, name, metadata):
"""
Add an available event.
name -- name of the event
metadata -- event metadata, i.e. type, description, etc., as a dict
"""
if metadata is None:
metadata = {}
self.available_events[name] = {
... |
Perform an action on the thing. | def perform_action(self, action_name, input_=None):
"""
Perform an action on the thing.
action_name -- name of the action
input_ -- any action inputs
Returns the action that was created.
"""
if action_name not in self.available_actions:
return None
... |
Remove an existing action. | def remove_action(self, action_name, action_id):
"""
Remove an existing action.
action_name -- name of the action
action_id -- ID of the action
Returns a boolean indicating the presence of the action.
"""
action = self.get_action(action_name, action_id)
... |
Add an available action. | def add_available_action(self, name, metadata, cls):
"""
Add an available action.
name -- name of the action
metadata -- action metadata, i.e. type, description, etc., as a dict
cls -- class to instantiate for this action
"""
if metadata is None:
meta... |
Remove a websocket subscriber. | def remove_subscriber(self, ws):
"""
Remove a websocket subscriber.
ws -- the websocket
"""
if ws in self.subscribers:
self.subscribers.remove(ws)
for name in self.available_events:
self.remove_event_subscriber(name, ws) |
Add a new websocket subscriber to an event. | def add_event_subscriber(self, name, ws):
"""
Add a new websocket subscriber to an event.
name -- name of the event
ws -- the websocket
"""
if name in self.available_events:
self.available_events[name]['subscribers'].add(ws) |
Remove a websocket subscriber from an event. | def remove_event_subscriber(self, name, ws):
"""
Remove a websocket subscriber from an event.
name -- name of the event
ws -- the websocket
"""
if name in self.available_events and \
ws in self.available_events[name]['subscribers']:
self.avail... |
Notify all subscribers of a property change. | def property_notify(self, property_):
"""
Notify all subscribers of a property change.
property_ -- the property that changed
"""
message = json.dumps({
'messageType': 'propertyStatus',
'data': {
property_.name: property_.get_value(),
... |
Notify all subscribers of an action status change. | def action_notify(self, action):
"""
Notify all subscribers of an action status change.
action -- the action whose status changed
"""
message = json.dumps({
'messageType': 'actionStatus',
'data': action.as_action_description(),
})
for sub... |
Notify all subscribers of an event. | def event_notify(self, event):
"""
Notify all subscribers of an event.
event -- the event that occurred
"""
if event.name not in self.available_events:
return
message = json.dumps({
'messageType': 'event',
'data': event.as_event_descr... |
Custom version of the standard annotate function that allows using field names as annotated fields. | def annotate(self, **annotations):
"""Custom version of the standard annotate function
that allows using field names as annotated fields.
Normally, the annotate function doesn't allow you
to use the name of an existing field on the model
as the alias name. This version of the fu... |
Updates all rows that match the filter. | def update(self, **fields):
"""Updates all rows that match the filter."""
# build up the query to execute
self._for_write = True
if django.VERSION >= (2, 0):
query = self.query.chain(UpdateQuery)
else:
query = self.query.clone(UpdateQuery)
query._... |
Sets the action to take when conflicts arise when attempting to insert/ create a new row. | def on_conflict(self, fields: List[Union[str, Tuple[str]]], action, index_predicate: str=None):
"""Sets the action to take when conflicts arise when attempting
to insert/create a new row.
Arguments:
fields:
The fields the conflicts can occur in.
action:
... |
Creates multiple new records in the database. | def bulk_insert(self, rows, return_model=False):
"""Creates multiple new records in the database.
This allows specifying custom conflict behavior using .on_conflict().
If no special behavior was specified, this uses the normal Django create(..)
Arguments:
rows:
... |
Creates a new record in the database. | def insert(self, **fields):
"""Creates a new record in the database.
This allows specifying custom conflict behavior using .on_conflict().
If no special behavior was specified, this uses the normal Django create(..)
Arguments:
fields:
The fields of the row t... |
Creates a new record in the database and then gets the entire row. | def insert_and_get(self, **fields):
"""Creates a new record in the database and then gets
the entire row.
This allows specifying custom conflict behavior using .on_conflict().
If no special behavior was specified, this uses the normal Django create(..)
Arguments:
fi... |
Creates a new record or updates the existing one with the specified data. | def upsert(self, conflict_target: List, fields: Dict, index_predicate: str=None) -> int:
"""Creates a new record or updates the existing one
with the specified data.
Arguments:
conflict_target:
Fields to pass into the ON CONFLICT clause.
fields:
... |
Creates a new record or updates the existing one with the specified data and then gets the row. | def upsert_and_get(self, conflict_target: List, fields: Dict, index_predicate: str=None):
"""Creates a new record or updates the existing one
with the specified data and then gets the row.
Arguments:
conflict_target:
Fields to pass into the ON CONFLICT clause.
... |
Creates a set of new records or updates the existing ones with the specified data. | def bulk_upsert(self, conflict_target: List, rows: List[Dict], index_predicate: str=None):
"""Creates a set of new records or updates the existing
ones with the specified data.
Arguments:
conflict_target:
Fields to pass into the ON CONFLICT clause.
rows:... |
Builds the SQL compiler for a insert query. | def _build_insert_compiler(self, rows: List[Dict]):
"""Builds the SQL compiler for a insert query.
Arguments:
rows:
A list of dictionaries, where each entry
describes a record to insert.
Returns:
The SQL compiler for the insert.
"... |
Verifies whether this field is gonna modify something on its own. | def _is_magical_field(self, model_instance, field, is_insert: bool):
"""Verifies whether this field is gonna modify something
on its own.
"Magical" means that a field modifies the field value
during the pre_save.
Arguments:
model_instance:
The model ... |
Gets the fields to use in an upsert. | def _get_upsert_fields(self, kwargs):
"""Gets the fields to use in an upsert.
This some nice magic. We'll split the fields into
a group of "insert fields" and "update fields":
INSERT INTO bla ("val1", "val2") ON CONFLICT DO UPDATE SET val1 = EXCLUDED.val1
^^^^... |
Sets the action to take when conflicts arise when attempting to insert/ create a new row. | def on_conflict(self, fields: List[Union[str, Tuple[str]]], action, index_predicate: str=None):
"""Sets the action to take when conflicts arise when attempting
to insert/create a new row.
Arguments:
fields:
The fields the conflicts can occur in.
action:
... |
Creates a new record or updates the existing one with the specified data. | def upsert(self, conflict_target: List, fields: Dict, index_predicate: str=None) -> int:
"""Creates a new record or updates the existing one
with the specified data.
Arguments:
conflict_target:
Fields to pass into the ON CONFLICT clause.
fields:
... |
Creates a new record or updates the existing one with the specified data and then gets the row. | def upsert_and_get(self, conflict_target: List, fields: Dict, index_predicate: str=None):
"""Creates a new record or updates the existing one
with the specified data and then gets the row.
Arguments:
conflict_target:
Fields to pass into the ON CONFLICT clause.
... |
Creates a set of new records or updates the existing ones with the specified data. | def bulk_upsert(self, conflict_target: List, rows: List[Dict], index_predicate: str=None):
"""Creates a set of new records or updates the existing
ones with the specified data.
Arguments:
conflict_target:
Fields to pass into the ON CONFLICT clause.
index... |
When a model gets created or updated. | def _on_model_save(sender, **kwargs):
"""When a model gets created or updated."""
created, instance = kwargs['created'], kwargs['instance']
if created:
signals.create.send(sender, pk=instance.pk)
else:
signals.update.send(sender, pk=instance.pk) |
When a model gets deleted. | def _on_model_delete(sender, **kwargs):
"""When a model gets deleted."""
instance = kwargs['instance']
signals.delete.send(sender, pk=instance.pk) |
Selects whichever field is not None in the specified order. | def IsNotNone(*fields, default=None):
"""Selects whichever field is not None, in the specified order.
Arguments:
fields:
The fields to attempt to get a value from,
in order.
default:
The value to return in case all values are None.
Returns:
A Ca... |
Resolves expressions inside the dictionary. | def resolve_expression(self, *args, **kwargs):
"""Resolves expressions inside the dictionary."""
result = dict()
for key, value in self.value.items():
if hasattr(value, 'resolve_expression'):
result[key] = value.resolve_expression(
*args, **kwargs... |
Compiles the HStore value into SQL. | def as_sql(self, compiler, connection):
"""Compiles the HStore value into SQL.
Compiles expressions contained in the values
of HStore entries as well.
Given a dictionary like:
dict(key1='val1', key2='val2')
The resulting SQL will be:
hstore(hstore('ke... |
Compiles this expression into SQL. | def as_sql(self, compiler, connection):
"""Compiles this expression into SQL."""
qn = compiler.quote_name_unless_alias
return "%s.%s->'%s'" % (qn(self.alias), qn(self.target.column), self.hstore_key), [] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.