INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Shows and persists warn symbol and text and exits.
Parameters
----------
text : None, optional
Text to be shown alongside warn symbol.
Returns
-------
self | def warn(self, text=None):
"""Shows and persists warn symbol and text and exits.
Parameters
----------
text : None, optional
Text to be shown alongside warn symbol.
Returns
-------
self
"""
return self.stop_and_persist(symbol=LogSymbols... |
Shows and persists info symbol and text and exits.
Parameters
----------
text : None, optional
Text to be shown alongside info symbol.
Returns
-------
self | def info(self, text=None):
"""Shows and persists info symbol and text and exits.
Parameters
----------
text : None, optional
Text to be shown alongside info symbol.
Returns
-------
self
"""
return self.stop_and_persist(symbol=LogSymbols... |
Stops the spinner and persists the final frame to be shown.
Parameters
----------
symbol : str, optional
Symbol to be shown in final frame
text: str, optional
Text to be shown in final frame
Returns
-------
self | def stop_and_persist(self, symbol=' ', text=None):
"""Stops the spinner and persists the final frame to be shown.
Parameters
----------
symbol : str, optional
Symbol to be shown in final frame
text: str, optional
Text to be shown in final frame
Re... |
Get the environment in which halo is running
Returns
-------
str
Environment name | def get_environment():
"""Get the environment in which halo is running
Returns
-------
str
Environment name
"""
try:
from IPython import get_ipython
except ImportError:
return 'terminal'
try:
shell = get_ipython().__class__.__name__
if shell == ... |
Check if given parameter is a string or not
Parameters
----------
text : *
Parameter to be checked for text type
Returns
-------
bool
Whether parameter is a string or not | def is_text_type(text):
"""Check if given parameter is a string or not
Parameters
----------
text : *
Parameter to be checked for text type
Returns
-------
bool
Whether parameter is a string or not
"""
if isinstance(text, six.text_type) or isinstance(text, six.strin... |
Stops the spinner and persists the final frame to be shown.
Parameters
----------
symbol : str, optional
Symbol to be shown in final frame
text: str, optional
Text to be shown in final frame
Returns
-------
self | def stop_and_persist(self, symbol=' ', text=None):
"""Stops the spinner and persists the final frame to be shown.
Parameters
----------
symbol : str, optional
Symbol to be shown in final frame
text: str, optional
Text to be shown in final frame
Re... |
Find stateless app given its name
First search the Django ORM, and if not found then look the app up in a local registry.
If the app does not have an ORM entry then a StatelessApp model instance is created. | def find_stateless_by_name(name):
'''
Find stateless app given its name
First search the Django ORM, and if not found then look the app up in a local registry.
If the app does not have an ORM entry then a StatelessApp model instance is created.
'''
try:
dsa_app = StatelessApp.objects.ge... |
Return a DjangoDash instance of the dash application | def as_dash_app(self):
'''
Return a DjangoDash instance of the dash application
'''
dateless_dash_app = getattr(self, '_stateless_dash_app_instance', None)
if not dateless_dash_app:
dateless_dash_app = get_stateless_by_name(self.app_name)
setattr(self, '_s... |
Check to see if the current hydrated state and the saved state are different.
If they are, then persist the current state in the database by saving the model instance. | def handle_current_state(self):
'''
Check to see if the current hydrated state and the saved state are different.
If they are, then persist the current state in the database by saving the model instance.
'''
if getattr(self, '_current_state_hydrated_changed', False) and self.sav... |
Return True if there is a cached current state for this app | def have_current_state_entry(self, wid, key):
'Return True if there is a cached current state for this app'
cscoll = self.current_state()
c_state = cscoll.get(wid, {})
return key in c_state |
Update current state with a (possibly new) value associated with key
If the key does not represent an existing entry, then ignore it | def update_current_state(self, wid, key, value):
'''
Update current state with a (possibly new) value associated with key
If the key does not represent an existing entry, then ignore it
'''
cscoll = self.current_state()
c_state = cscoll.get(wid, {})
if key in c_s... |
Return the current internal state of the model instance.
This is not necessarily the same as the persisted state
stored in the self.base_state variable. | def current_state(self):
'''
Return the current internal state of the model instance.
This is not necessarily the same as the persisted state
stored in the self.base_state variable.
'''
c_state = getattr(self, '_current_state_hydrated', None)
if not c_state:
... |
Return a dash application instance for this model instance | def as_dash_instance(self, cache_id=None):
'Return a dash application instance for this model instance'
dash_app = self.stateless_app.as_dash_app() # pylint: disable=no-member
base = self.current_state()
return dash_app.do_form_dash_instance(replacements=base,
... |
Get the base state of the object, as defined by the app.layout code, as a python dict | def _get_base_state(self):
'''
Get the base state of the object, as defined by the app.layout code, as a python dict
'''
base_app_inst = self.stateless_app.as_dash_app().as_dash_instance() # pylint: disable=no-member
# Get base layout response, from a base object
base_re... |
Add values from the underlying dash layout configuration | def populate_values(self):
'''
Add values from the underlying dash layout configuration
'''
obj = self._get_base_state()
self.base_state = json.dumps(obj) |
Locate a dash application, given either the
slug of an instance or the name for a stateless app | def locate_item(ident, stateless=False, cache_id=None):
'''Locate a dash application, given either the
slug of an instance or the name for a stateless app'''
if stateless:
dash_app = find_stateless_by_name(ident)
else:
dash_app = get_object_or_404(DashApp, slug=id... |
Send message through pipe to client component | def send_to_pipe_channel(channel_name,
label,
value):
'Send message through pipe to client component'
async_to_sync(async_send_to_pipe_channel)(channel_name=channel_name,
label=label,
... |
Send message asynchronously through pipe to client component | async def async_send_to_pipe_channel(channel_name,
label,
value):
'Send message asynchronously through pipe to client component'
pcn = _form_pipe_channel_name(channel_name)
channel_layer = get_channel_layer()
await channel_layer.... |
Send a new value into the ws pipe | def pipe_value(self, message):
'Send a new value into the ws pipe'
jmsg = json.dumps(message)
self.send(jmsg) |
Update this consumer to listen on channel_name for the js widget associated with uid | def update_pipe_channel(self, uid, channel_name, label): # pylint: disable=unused-argument
'''
Update this consumer to listen on channel_name for the js widget associated with uid
'''
pipe_group_name = _form_pipe_channel_name(channel_name)
if self.channel_layer:
curr... |
Store initial arguments, if any, and return a cache identifier | def store_initial_arguments(request, initial_arguments=None):
'Store initial arguments, if any, and return a cache identifier'
if initial_arguments is None:
return None
# Generate a cache id
cache_id = "dpd-initial-args-%s" % str(uuid.uuid4()).replace('-', '')
# Store args in json form in... |
Extract initial arguments for the dash app | def get_initial_arguments(request, cache_id=None):
'Extract initial arguments for the dash app'
if cache_id is None:
return None
if initial_argument_location():
return cache.get(cache_id)
return request.session[cache_id] |
Return the dependencies | def dependencies(request, ident, stateless=False, **kwargs):
'Return the dependencies'
_, app = DashApp.locate_item(ident, stateless)
with app.app_context():
view_func = app.locate_endpoint_function('dash-dependencies')
resp = view_func()
return HttpResponse(resp.data,
... |
Return the layout of the dash application | def layout(request, ident, stateless=False, cache_id=None, **kwargs):
'Return the layout of the dash application'
_, app = DashApp.locate_item(ident, stateless)
view_func = app.locate_endpoint_function('dash-layout')
resp = view_func()
initial_arguments = get_initial_arguments(request, cache_id)
... |
Generate update json response | def update(request, ident, stateless=False, **kwargs):
'Generate update json response'
dash_app, app = DashApp.locate_item(ident, stateless)
request_body = json.loads(request.body.decode('utf-8'))
if app.use_dash_dispatch():
# Force call through dash
view_func = app.locate_endpoint_fun... |
Main view for a dash app | def main_view(request, ident, stateless=False, cache_id=None, **kwargs):
'Main view for a dash app'
_, app = DashApp.locate_item(ident, stateless, cache_id=cache_id)
view_func = app.locate_endpoint_function()
resp = view_func()
return HttpResponse(resp) |
Return part of a client-side component, served locally for some reason | def component_component_suites(request, resource=None, component=None, **kwargs):
'Return part of a client-side component, served locally for some reason'
return component_suites(request,
resource=resource,
component=component,
... |
Return part of a client-side component, served locally for some reason | def component_suites(request, resource=None, component=None, extra_element="", **kwargs):
'Return part of a client-side component, served locally for some reason'
get_params = request.GET.urlencode()
if get_params and False:
redone_url = "/static/dash/component/%s/%s%s?%s" %(component, extra_elemen... |
Return a local dash app asset, served up through the Django static framework | def app_assets(request, **kwargs):
'Return a local dash app asset, served up through the Django static framework'
get_params = request.GET.urlencode()
extra_part = ""
if get_params:
redone_url = "/static/dash/assets/%s?%s" %(extra_part, get_params)
else:
redone_url = "/static/dash/as... |
Add some info to a session in a place that django-plotly-dash can pass to a callback | def add_to_session(request, template_name="index.html", **kwargs):
'Add some info to a session in a place that django-plotly-dash can pass to a callback'
django_plotly_dash = request.session.get("django_plotly_dash", dict())
session_add_count = django_plotly_dash.get('add_counter', 0)
django_plotly_da... |
Redirect static assets for a component | def asset_redirection(request, path, ident=None, stateless=False, **kwargs):
'Redirect static assets for a component'
X, app = DashApp.locate_item(ident, stateless)
# Redirect to a location based on the import path of the module containing the DjangoDash app
static_path = X.get_asset_static_url(path)
... |
Example view that inserts content into the dash context passed to the dash application | def dash_example_1_view(request, template_name="demo_six.html", **kwargs):
'Example view that inserts content into the dash context passed to the dash application'
context = {}
# create some context to send over to Dash:
dash_context = request.session.get("django_plotly_dash", dict())
dash_context... |
Example view that exhibits the use of sessions to store state | def session_state_view(request, template_name, **kwargs):
'Example view that exhibits the use of sessions to store state'
session = request.session
demo_count = session.get('django_plotly_dash', {})
ind_use = demo_count.get('ind_use', 0)
ind_use += 1
demo_count['ind_use'] = ind_use
conte... |
Update the output following a change of the input selection | def callback_c(*args, **kwargs):
'Update the output following a change of the input selection'
#da = kwargs['dash_app']
session_state = kwargs['session_state']
calls_so_far = session_state.get('calls_so_far', 0)
session_state['calls_so_far'] = calls_so_far + 1
user_counts = session_state.get(... |
Locate placeholder magic strings and replace with content | def adjust_response(self, response):
'Locate placeholder magic strings and replace with content'
try:
c1 = self._replace(response.content,
self.header_placeholder,
self.embedded_holder.css)
response.content = self._r... |
Input app button pressed, so do something interesting | def callback_liveIn_button_press(red_clicks, blue_clicks, green_clicks,
rc_timestamp, bc_timestamp, gc_timestamp, **kwargs): # pylint: disable=unused-argument
'Input app button pressed, so do something interesting'
if not rc_timestamp:
rc_timestamp = 0
if not bc_tim... |
Generate the layout per-app, generating each tine a new uuid for the state_uid argument | def generate_liveOut_layout():
'Generate the layout per-app, generating each tine a new uuid for the state_uid argument'
return html.Div([
dpd.Pipe(id="named_count_pipe",
value=None,
label="named_counts",
channel_name="live_button_counter"),
htm... |
Handle something changing the value of the input pipe or the associated state uid | def callback_liveOut_pipe_in(named_count, state_uid, **kwargs):
'Handle something changing the value of the input pipe or the associated state uid'
cache_key = _get_cache_key(state_uid)
state = cache.get(cache_key)
# If nothing in cache, prepopulate
if not state:
state = {}
# Guard ag... |
Build a timeseries from the internal state | def callback_show_timeseries(internal_state_string, state_uid, **kwargs):
'Build a timeseries from the internal state'
cache_key = _get_cache_key(state_uid)
state = cache.get(cache_key)
# If nothing in cache, prepopulate
if not state:
state = {}
colour_series = {}
colors = {'red'... |
Update output based just on state | def session_demo_danger_callback(da_children, session_state=None, **kwargs):
'Update output based just on state'
if not session_state:
return "Session state not yet available"
return "Session state contains: " + str(session_state.get('bootstrap_demo_state', "NOTHING")) + " and the page render count... |
Output text based on both app state and session state | def session_demo_alert_callback(n_clicks, session_state=None, **kwargs):
'Output text based on both app state and session state'
if session_state is None:
raise NotImplementedError("Cannot handle a missing session state")
csf = session_state.get('bootstrap_demo_state', None)
if not csf:
... |
Add app to local registry by name | def add_usable_app(name, app):
'Add app to local registry by name'
name = slugify(name)
global usable_apps # pylint: disable=global-statement
usable_apps[name] = app
return name |
Base path name of this instance, taking into account any state or statelessness | def get_base_pathname(self, specific_identifier, cache_id):
'Base path name of this instance, taking into account any state or statelessness'
if not specific_identifier:
app_pathname = "%s:app-%s"% (app_name, main_view_label)
ndid = self._uid
else:
app_pathnam... |
Perform the act of constructing a Dash instance taking into account state | def do_form_dash_instance(self, replacements=None, specific_identifier=None, cache_id=None):
'Perform the act of constructing a Dash instance taking into account state'
ndid, base_pathname = self.get_base_pathname(specific_identifier, cache_id)
return self.form_dash_instance(replacements, ndid,... |
Construct a Dash instance taking into account state | def form_dash_instance(self, replacements=None, ndid=None, base_pathname=None):
'Construct a Dash instance taking into account state'
if ndid is None:
ndid = self._uid
rd = WrappedDash(base_pathname=base_pathname,
expanded_callbacks=self._expanded_callbacks... |
Form a callback function by wrapping, in the same way as the underlying Dash application would | def callback(self, output, inputs=None, state=None, events=None):
'Form a callback function by wrapping, in the same way as the underlying Dash application would'
callback_set = {'output':output,
'inputs':inputs and inputs or dict(),
'state':state and stat... |
Form an expanded callback.
This function registers the callback function, and sets an internal flag that mandates that all
callbacks are passed the enhanced arguments. | def expanded_callback(self, output, inputs=[], state=[], events=[]): # pylint: disable=dangerous-default-value
'''
Form an expanded callback.
This function registers the callback function, and sets an internal flag that mandates that all
callbacks are passed the enhanced arguments.
... |
Add application state to initial values | def augment_initial_layout(self, base_response, initial_arguments=None):
'Add application state to initial values'
if self.use_dash_layout() and not initial_arguments and False:
return base_response.data, base_response.mimetype
# Adjust the base layout response
baseDataInByt... |
Walk tree of properties and extract identifiers and associated values | def walk_tree_and_extract(self, data, target):
'Walk tree of properties and extract identifiers and associated values'
if isinstance(data, dict):
for key in ['children', 'props',]:
self.walk_tree_and_extract(data.get(key, None), target)
ident = data.get('id', None... |
Walk the tree. Rely on json decoding to insert instances of dict and list
ie we use a dna test for anatine, rather than our eyes and ears... | def walk_tree_and_replace(self, data, overrides):
'''
Walk the tree. Rely on json decoding to insert instances of dict and list
ie we use a dna test for anatine, rather than our eyes and ears...
'''
if isinstance(data, dict):
response = {}
replacements = {... |
Locate endpoint function given name of view | def locate_endpoint_function(self, name=None):
'Locate endpoint function given name of view'
if name is not None:
ep = "%s_%s" %(self._base_pathname,
name)
else:
ep = self._base_pathname
return self._notflask.endpoints[ep]['view_func'] |
Overloaded layout function to fix component names as needed | def layout(self, value):
'Overloaded layout function to fix component names as needed'
if self._adjust_id:
self._fix_component_id(value)
return Dash.layout.fset(self, value) |
Fix name of component ad all of its children | def _fix_component_id(self, component):
'Fix name of component ad all of its children'
theID = getattr(component, "id", None)
if theID is not None:
setattr(component, "id", self._fix_id(theID))
try:
for c in component.children:
self._fix_component... |
Update component identifier | def _fix_callback_item(self, item):
'Update component identifier'
item.component_id = self._fix_id(item.component_id)
return item |
Invoke callback, adjusting variable names as needed | def callback(self, output, inputs=[], state=[], events=[]): # pylint: disable=dangerous-default-value
'Invoke callback, adjusting variable names as needed'
if isinstance(output, (list, tuple)):
fixed_outputs = [self._fix_callback_item(x) for x in output]
# Temporary check; can b... |
Perform dispatch, using request embedded within flask global state | def dispatch(self):
'Perform dispatch, using request embedded within flask global state'
import flask
body = flask.request.get_json()
return self. dispatch_with_args(body, argMap=dict()) |
Perform callback dispatching, with enhanced arguments and recording of response | def dispatch_with_args(self, body, argMap):
'Perform callback dispatching, with enhanced arguments and recording of response'
inputs = body.get('inputs', [])
state = body.get('state', [])
output = body['output']
try:
output_id = output['id']
output_proper... |
Return extra html properties to allow individual apps to be styled separately.
The content returned from this function is injected unescaped into templates. | def extra_html_properties(self, prefix=None, postfix=None, template_type=None):
'''
Return extra html properties to allow individual apps to be styled separately.
The content returned from this function is injected unescaped into templates.
'''
prefix = prefix if prefix else "d... |
Insert a dash application using a html iframe | def plotly_app(context, name=None, slug=None, da=None, ratio=0.1, use_frameborder=False, initial_arguments=None):
'Insert a dash application using a html iframe'
fbs = '1' if use_frameborder else '0'
dstyle = """
position: relative;
padding-bottom: %s%%;
height: 0;
overflow:hidden;
"""... |
Direct insertion of a Dash app | def plotly_direct(context, name=None, slug=None, da=None):
'Direct insertion of a Dash app'
da, app = _locate_daapp(name, slug, da)
view_func = app.locate_endpoint_function()
# Load embedded holder inserted by middleware
eh = context.request.dpd_content_handler.embedded_holder
app.set_embedde... |
Return a slug-friendly identifier | def plotly_app_identifier(name=None, slug=None, da=None, postfix=None):
'Return a slug-friendly identifier'
da, app = _locate_daapp(name, slug, da)
slugified_id = app.slugified_id()
if postfix:
return "%s-%s" %(slugified_id, postfix)
return slugified_id |
Return a string of space-separated class names | def plotly_class(name=None, slug=None, da=None, prefix=None, postfix=None, template_type=None):
'Return a string of space-separated class names'
da, app = _locate_daapp(name, slug, da)
return app.extra_html_properties(prefix=prefix,
postfix=postfix,
... |
Parse Wyckoff.csv
There are 530 data sets. For one example:
9:C 1 2 1:::::::
::4:c:1:(x,y,z):(-x,y,-z)::
::2:b:2:(0,y,1/2):::
::2:a:2:(0,y,0)::: | def parse_wyckoff_csv(wyckoff_file):
"""Parse Wyckoff.csv
There are 530 data sets. For one example:
9:C 1 2 1:::::::
::4:c:1:(x,y,z):(-x,y,-z)::
::2:b:2:(0,y,1/2):::
::2:a:2:(0,y,0):::
"""
rowdata = []
points = []
hP_nums = [433, 436, 444, 450, 452, 458, 460]
for i, line ... |
List up site symmetries
The data structure is as follows:
wyckoff[0]['wyckoff'][0]['site_symmetry']
Note
----
Maximum length of string is 6. | def get_site_symmetries(wyckoff):
"""List up site symmetries
The data structure is as follows:
wyckoff[0]['wyckoff'][0]['site_symmetry']
Note
----
Maximum length of string is 6.
"""
ssyms = []
for w in wyckoff:
ssyms += ["\"%-6s\"" % w_s['site_symmetry'] for w_s in w... |
Sleep an incremental amount of time after each attempt, starting at
wait_incrementing_start and incrementing by wait_incrementing_increment | def incrementing_sleep(self, previous_attempt_number, delay_since_first_attempt_ms):
"""
Sleep an incremental amount of time after each attempt, starting at
wait_incrementing_start and incrementing by wait_incrementing_increment
"""
result = self._wait_incrementing_start + (self.... |
Anything that uses the ModelMeta needs _meta and id.
Also keep track of relationships and make them in the related model class. | def transform_model(cls) -> None:
"""
Anything that uses the ModelMeta needs _meta and id.
Also keep track of relationships and make them in the related model class.
"""
if cls.name != "Model":
appname = "models"
for mcls in cls.get_children():
if isinstance(mcls, ClassDe... |
Morphs model fields to representative type | def apply_type_shim(cls, _context=None) -> Iterator:
"""
Morphs model fields to representative type
"""
if cls.name in ["IntField", "SmallIntField"]:
base_nodes = scoped_nodes.builtin_lookup("int")
elif cls.name in ["CharField", "TextField"]:
base_nodes = scoped_nodes.builtin_lookup(... |
Encodes an iterable of a given field into a database-compatible format. | def list_encoder(values, instance, field: Field):
"""Encodes an iterable of a given field into a database-compatible format."""
return [field.to_db_value(element, instance) for element in values] |
Clears ALL relations. | async def clear(self, using_db=None) -> None:
"""
Clears ALL relations.
"""
db = using_db if using_db else self.model._meta.db
through_table = Table(self.field.through)
query = (
db.query_class.from_(through_table)
.where(getattr(through_table, sel... |
Removes one or more of ``instances`` from the relation. | async def remove(self, *instances, using_db=None) -> None:
"""
Removes one or more of ``instances`` from the relation.
"""
db = using_db if using_db else self.model._meta.db
if not instances:
raise OperationalError("remove() called on no instances")
through_ta... |
Registers ``before_serving`` and ``after_serving`` hooks to set-up and tear-down Tortoise-ORM
inside a Quart service.
It also registers a CLI command ``generate_schemas`` that will generate the schemas.
You can configure using only one of ``config``, ``config_file``
and ``(db_url, modules)``.
Para... | def register_tortoise(
app: Quart,
config: Optional[dict] = None,
config_file: Optional[str] = None,
db_url: Optional[str] = None,
modules: Optional[Dict[str, List[str]]] = None,
generate_schemas: bool = False,
) -> None:
"""
Registers ``before_serving`` and ``after_serving`` hooks to se... |
Simple async runner that cleans up DB connections on exit.
This is meant for simple scripts.
Usage::
from tortoise import Tortoise, run_async
async def do_stuff():
await Tortoise.init(
db_url='sqlite://db.sqlite3',
models={'models': ['app.models']}
... | def run_async(coro: Coroutine) -> None:
"""
Simple async runner that cleans up DB connections on exit.
This is meant for simple scripts.
Usage::
from tortoise import Tortoise, run_async
async def do_stuff():
await Tortoise.init(
db_url='sqlite://db.sqlite3'... |
Sets up Tortoise-ORM.
You can configure using only one of ``config``, ``config_file``
and ``(db_url, modules)``.
Parameters
----------
config:
Dict containing config:
Example
-------
.. code-block:: python3
{
... | async def init(
cls,
config: Optional[dict] = None,
config_file: Optional[str] = None,
_create_db: bool = False,
db_url: Optional[str] = None,
modules: Optional[Dict[str, List[str]]] = None,
) -> None:
"""
Sets up Tortoise-ORM.
You can configu... |
Generate schemas according to models provided to ``.init()`` method.
Will fail if schemas already exists, so it's not recommended to be used as part
of application workflow
Parameters
----------
safe:
When set to true, creates the table only when it does not already ... | async def generate_schemas(cls, safe=True) -> None:
"""
Generate schemas according to models provided to ``.init()`` method.
Will fail if schemas already exists, so it's not recommended to be used as part
of application workflow
Parameters
----------
safe:
... |
Tries to drop all databases provided in config passed to ``.init()`` method.
Normally should be used only for testing purposes. | async def _drop_databases(cls) -> None:
"""
Tries to drop all databases provided in config passed to ``.init()`` method.
Normally should be used only for testing purposes.
"""
if not cls._inited:
raise ConfigurationError("You have to call .init() first before deleting... |
Transaction context manager.
You can run your code inside ``async with in_transaction():`` statement to run it
into one transaction. If error occurs transaction will rollback.
:param connection_name: name of connection to run with, optional if you have only
one db connection | def in_transaction(connection_name: Optional[str] = None) -> BaseTransactionWrapper:
"""
Transaction context manager.
You can run your code inside ``async with in_transaction():`` statement to run it
into one transaction. If error occurs transaction will rollback.
:param connection_name: name of c... |
Transaction decorator.
You can wrap your function with this decorator to run it into one transaction.
If error occurs transaction will rollback.
:param connection_name: name of connection to run with, optional if you have only
one db connection | def atomic(connection_name: Optional[str] = None) -> Callable:
"""
Transaction decorator.
You can wrap your function with this decorator to run it into one transaction.
If error occurs transaction will rollback.
:param connection_name: name of connection to run with, optional if you have only
... |
Function to manually control your transaction.
Returns transaction object with ``.rollback()`` and ``.commit()`` methods.
All db calls in same coroutine context will run into transaction
before ending transaction with above methods.
:param connection_name: name of connection to run with, optional if y... | async def start_transaction(connection_name: Optional[str] = None) -> BaseTransactionWrapper:
"""
Function to manually control your transaction.
Returns transaction object with ``.rollback()`` and ``.commit()`` methods.
All db calls in same coroutine context will run into transaction
before ending ... |
Filters QuerySet by given kwargs. You can filter by related objects like this:
.. code-block:: python3
Team.filter(events__tournament__name='Test')
You can also pass Q objects to filters as args. | def filter(self, *args, **kwargs) -> "QuerySet":
"""
Filters QuerySet by given kwargs. You can filter by related objects like this:
.. code-block:: python3
Team.filter(events__tournament__name='Test')
You can also pass Q objects to filters as args.
"""
retu... |
Same as .filter(), but with appends all args with NOT | def exclude(self, *args, **kwargs) -> "QuerySet":
"""
Same as .filter(), but with appends all args with NOT
"""
return self._filter_or_exclude(negate=True, *args, **kwargs) |
Accept args to filter by in format like this:
.. code-block:: python3
.order_by('name', '-tournament__name')
Supports ordering by related models too. | def order_by(self, *orderings: str) -> "QuerySet":
"""
Accept args to filter by in format like this:
.. code-block:: python3
.order_by('name', '-tournament__name')
Supports ordering by related models too.
"""
queryset = self._clone()
new_ordering = ... |
Limits QuerySet to given length. | def limit(self, limit: int) -> "QuerySet":
"""
Limits QuerySet to given length.
"""
queryset = self._clone()
queryset._limit = limit
return queryset |
Query offset for QuerySet. | def offset(self, offset: int) -> "QuerySet":
"""
Query offset for QuerySet.
"""
queryset = self._clone()
queryset._offset = offset
if self.capabilities.requires_limit and queryset._limit is None:
queryset._limit = 1000000
return queryset |
Annotate result with aggregation result. | def annotate(self, **kwargs) -> "QuerySet":
"""
Annotate result with aggregation result.
"""
queryset = self._clone()
for key, aggregation in kwargs.items():
if not isinstance(aggregation, Aggregate):
raise TypeError("value is expected to be Aggregate ... |
Make QuerySet returns list of tuples for given args instead of objects.
If ```flat=True`` and only one arg is passed can return flat list. | def values_list(
self, *fields_: str, flat: bool = False
) -> "ValuesListQuery": # pylint: disable=W0621
"""
Make QuerySet returns list of tuples for given args instead of objects.
If ```flat=True`` and only one arg is passed can return flat list.
"""
return ValuesLi... |
Make QuerySet return dicts instead of objects. | def values(self, *args: str, **kwargs: str) -> "ValuesQuery":
"""
Make QuerySet return dicts instead of objects.
"""
fields_for_select = {} # type: Dict[str, str]
for field in args:
if field in fields_for_select:
raise FieldError("Duplicate key {}".fo... |
Delete all objects in QuerySet. | def delete(self) -> "DeleteQuery":
"""
Delete all objects in QuerySet.
"""
return DeleteQuery(
db=self._db,
model=self.model,
q_objects=self._q_objects,
annotations=self._annotations,
custom_filters=self._custom_filters,
... |
Update all objects in QuerySet with given kwargs. | def update(self, **kwargs) -> "UpdateQuery":
"""
Update all objects in QuerySet with given kwargs.
"""
return UpdateQuery(
db=self._db,
model=self.model,
update_kwargs=kwargs,
q_objects=self._q_objects,
annotations=self._annotat... |
Return count of objects in queryset instead of objects. | def count(self) -> "CountQuery":
"""
Return count of objects in queryset instead of objects.
"""
return CountQuery(
db=self._db,
model=self.model,
q_objects=self._q_objects,
annotations=self._annotations,
custom_filters=self._cu... |
Limit queryset to one object and return one object instead of list. | def first(self) -> "QuerySet":
"""
Limit queryset to one object and return one object instead of list.
"""
queryset = self._clone()
queryset._limit = 1
queryset._single = True
return queryset |
Fetch exactly one object matching the parameters. | def get(self, *args, **kwargs) -> "QuerySet":
"""
Fetch exactly one object matching the parameters.
"""
queryset = self.filter(*args, **kwargs)
queryset._limit = 2
queryset._get = True
return queryset |
Like ``.fetch_related()`` on instance, but works on all objects in QuerySet. | def prefetch_related(self, *args: str) -> "QuerySet":
"""
Like ``.fetch_related()`` on instance, but works on all objects in QuerySet.
"""
queryset = self._clone()
queryset._prefetch_map = {}
for relation in args:
if isinstance(relation, Prefetch):
... |
Fetch and return information about the query execution plan.
This is done by executing an ``EXPLAIN`` query whose exact prefix depends
on the database backend, as documented below.
- PostgreSQL: ``EXPLAIN (FORMAT JSON, VERBOSE) ...``
- SQLite: ``EXPLAIN QUERY PLAN ...``
- MySQL... | async def explain(self) -> Any:
"""Fetch and return information about the query execution plan.
This is done by executing an ``EXPLAIN`` query whose exact prefix depends
on the database backend, as documented below.
- PostgreSQL: ``EXPLAIN (FORMAT JSON, VERBOSE) ...``
- SQLite:... |
Executes query in provided db client.
Useful for transactions workaround. | def using_db(self, _db: BaseDBAsyncClient) -> "QuerySet":
"""
Executes query in provided db client.
Useful for transactions workaround.
"""
queryset = self._clone()
queryset._db = _db
return queryset |
Check the value of "unique_together" option. | def _check_unique_together(cls):
"""Check the value of "unique_together" option."""
if cls._meta.unique_together is None:
return
if not isinstance(cls._meta.unique_together, (tuple, list)):
raise ConfigurationError(
"'{}.unique_together' must be a list or... |
Creates epub file with the content defined in EpubBook.
>>> ebooklib.write_epub('book.epub', book)
:Args:
- name: file name for the output file
- book: instance of EpubBook
- options: extra opions as dictionary (optional) | def write_epub(name, book, options=None):
"""
Creates epub file with the content defined in EpubBook.
>>> ebooklib.write_epub('book.epub', book)
:Args:
- name: file name for the output file
- book: instance of EpubBook
- options: extra opions as dictionary (optional)
"""
epub... |
Creates new instance of EpubBook with the content defined in the input file.
>>> book = ebooklib.read_epub('book.epub')
:Args:
- name: full path to the input file
- options: extra options as dictionary (optional)
:Returns:
Instance of EpubBook. | def read_epub(name, options=None):
"""
Creates new instance of EpubBook with the content defined in the input file.
>>> book = ebooklib.read_epub('book.epub')
:Args:
- name: full path to the input file
- options: extra options as dictionary (optional)
:Returns:
Instance of EpubB... |
Guess type according to the file extension. Might not be the best way how to do it, but it works for now.
Items can be of type:
- ITEM_UNKNOWN = 0
- ITEM_IMAGE = 1
- ITEM_STYLE = 2
- ITEM_SCRIPT = 3
- ITEM_NAVIGATION = 4
- ITEM_VECTOR = 5
- ... | def get_type(self):
"""
Guess type according to the file extension. Might not be the best way how to do it, but it works for now.
Items can be of type:
- ITEM_UNKNOWN = 0
- ITEM_IMAGE = 1
- ITEM_STYLE = 2
- ITEM_SCRIPT = 3
- ITEM_NAVIGATION = 4
... |
Add additional link to the document. Links will be embeded only inside of this document.
>>> add_link(href='styles.css', rel='stylesheet', type='text/css') | def add_link(self, **kwgs):
"""
Add additional link to the document. Links will be embeded only inside of this document.
>>> add_link(href='styles.css', rel='stylesheet', type='text/css')
"""
self.links.append(kwgs)
if kwgs.get('type') == 'text/javascript':
i... |
Returns list of additional links of specific type.
:Returns:
As tuple returns list of links. | def get_links_of_type(self, link_type):
"""
Returns list of additional links of specific type.
:Returns:
As tuple returns list of links.
"""
return (link for link in self.links if link.get('type', '') == link_type) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.