text stringlengths 81 112k |
|---|
Initialise the Shopify session with the Shopify App's API credentials.
def initialise_shopify_session():
"""
Initialise the Shopify session with the Shopify App's API credentials.
"""
if not settings.SHOPIFY_APP_API_KEY or not settings.SHOPIFY_APP_API_SECRET:
raise ImproperlyConfigured("SHOPIFY... |
Decorator requiring the current user to be anonymous (not logged in).
def anonymous_required(function=None, redirect_url=None):
"""
Decorator requiring the current user to be anonymous (not logged in).
"""
if not redirect_url:
redirect_url = settings.LOGIN_REDIRECT_URL
actual_decorator = u... |
Decorator that wraps django.contrib.auth.decorators.login_required, but supports extracting Shopify's authentication
query parameters (`shop`, `timestamp`, `signature` and `hmac`) and passing them on to the login URL (instead of just
wrapping them up and encoding them in to the `next` parameter).
This is u... |
Creates and saves a ShopUser with the given domain and password.
def create_user(self, myshopify_domain, password=None):
"""
Creates and saves a ShopUser with the given domain and password.
"""
if not myshopify_domain:
raise ValueError('ShopUsers must have a myshopify domain... |
Merge a dictionary of query parameters into the given URL.
Ensures all parameters are sorted in dictionary order when returning the URL.
def add_query_parameters_to_url(url, query_parameters):
"""
Merge a dictionary of query parameters into the given URL.
Ensures all parameters are sorted in dictionary... |
Bind an event to a callback
:param event_name: The name of the event to bind to.
:type event_name: str
:param callback: The callback to notify of this event.
def bind(self, event_name, callback, *args, **kwargs):
"""Bind an event to a callback
:param event_name: The name of t... |
Send an event to the Pusher server.
:param str event_name:
:param Any data:
:param str channel_name:
def send_event(self, event_name, data, channel_name=None):
"""Send an event to the Pusher server.
:param str event_name:
:param Any data:
:param str channel_nam... |
Trigger an event on this channel. Only available for private or
presence channels
:param event_name: The name of the event. Must begin with 'client-''
:type event_name: str
:param data: The data to send with the event.
def trigger(self, event_name, data):
"""Trigger an event... |
Subscribe to a channel.
:param str channel_name: The name of the channel to subscribe to.
:param str auth: The token to use if authenticated externally.
:rtype: pysher.Channel
def subscribe(self, channel_name, auth=None):
"""Subscribe to a channel.
:param str channel_name: The... |
Unsubscribe from a channel
:param str channel_name: The name of the channel to unsubscribe from.
def unsubscribe(self, channel_name):
"""Unsubscribe from a channel
:param str channel_name: The name of the channel to unsubscribe from.
"""
if channel_name in self.channels:
... |
Handle incoming data.
:param str event_name: Name of the event.
:param Any data: Data received.
:param str channel_name: Name of the channel this event and data belongs to.
def _connection_handler(self, event_name, data, channel_name):
"""Handle incoming data.
:param str event... |
Handle a reconnect.
def _reconnect_handler(self):
"""Handle a reconnect."""
for channel_name, channel in self.channels.items():
data = {'channel': channel_name}
if channel.auth:
data['auth'] = channel.auth
self.connection.send_event('pusher:subscrib... |
Generate a token for authentication with the given channel.
:param str channel_name: Name of the channel to generate a signature for.
:rtype: str
def _generate_auth_token(self, channel_name):
"""Generate a token for authentication with the given channel.
:param str channel_name: Name ... |
Generate a presence token.
:param str channel_name: Name of the channel to generate a signature for.
:rtype: str
def _generate_presence_token(self, channel_name):
"""Generate a presence token.
:param str channel_name: Name of the channel to generate a signature for.
:rtype: st... |
Tries to decide about the part of speech.
def pos(self, element = None):
''' Tries to decide about the part of speech. '''
tags = []
if element:
if element.startswith(('de ', 'het ', 'het/de', 'de/het')) and not re.search('\[[\w|\s][\w|\s]+\]', element.split('\r\n')[0], re.U):
tags.append('NN')
if re.... |
Tries to scrape the correct articles for singular and plural from uitmuntend.nl.
def articles(self):
''' Tries to scrape the correct articles for singular and plural from uitmuntend.nl. '''
result = [None, None]
element = self._first('NN')
if element:
element = element.split('\r\n')[0]
if ' | ' in eleme... |
Tries to scrape the plural version from uitmuntend.nl.
def plural(self):
''' Tries to scrape the plural version from uitmuntend.nl. '''
element = self._first('NN')
if element:
element = element.split('\r\n')[0]
if ' | ' in element:
# This means there is a plural
singular, plural = element.split(' ... |
Downloads a file via HTTP.
def download(url, filename, overwrite = False):
''' Downloads a file via HTTP. '''
from requests import get
from os.path import exists
debug('Downloading ' + unicode(url) + '...')
data = get(url)
if data.status_code == 200:
if not exists(filename) or overwrite:
f = open(filename... |
Prints a message if warning mode is enabled.
def warning(message):
''' Prints a message if warning mode is enabled. '''
import lltk.config as config
if config['warnings']:
try:
from termcolor import colored
except ImportError:
def colored(message, color):
return message
print colored('@LLTK-WARNI... |
Decorator used to trace function calls for debugging purposes.
def trace(f, *args, **kwargs):
''' Decorator used to trace function calls for debugging purposes. '''
print 'Calling %s() with args %s, %s ' % (f.__name__, args, kwargs)
return f(*args,**kwargs) |
Tries to scrape the correct articles for singular and plural from vandale.nl.
def articles(self):
''' Tries to scrape the correct articles for singular and plural from vandale.nl. '''
result = [None, None]
element = self._first('NN')
if element:
if re.search('(de|het/?de|het);', element, re.U):
result[... |
Tries to scrape the plural version from vandale.nl.
def plural(self):
''' Tries to scrape the plural version from vandale.nl. '''
element = self._first('NN')
if element:
if re.search('meervoud: ([\w|\s|\'|\-|,]+)', element, re.U):
results = re.search('meervoud: ([\w|\s|\'|\-|,]+)', element, re.U).groups(... |
Tries to scrape the miniaturized version from vandale.nl.
def miniaturize(self):
''' Tries to scrape the miniaturized version from vandale.nl. '''
element = self._first('NN')
if element:
if re.search('verkleinwoord: (\w+)', element, re.U):
return re.findall('verkleinwoord: (\w+)', element, re.U)
else:... |
Returns a sanitized string.
def _normalize(self, string):
''' Returns a sanitized string. '''
string = super(VerbixDe, self)._normalize(string)
string = string.replace('sie; Sie', 'sie')
string = string.strip()
return string |
Tries to decide about the part of speech.
def pos(self):
''' Tries to decide about the part of speech. '''
tags = []
if self.tree.xpath('//div[@class="grad733100"]/h2[@class="inline"]//text()'):
info = self.tree.xpath('//div[@class="grad733100"]/h2[@class="inline"]')[0].text_content()
info = info.strip('I... |
Returns a sanitized string.
def _normalize(self, string):
''' Returns a sanitized string. '''
string = super(VerbixFr, self)._normalize(string)
string = string.replace('il; elle', 'il/elle')
string = string.replace('ils; elles', 'ils/elles')
string = string.strip()
return string |
Tries to decide about the part of speech.
def pos(self, element = None):
''' Tries to decide about the part of speech. '''
tags = []
if element:
if re.search('[\w|\s]+ [m|f]\.', element, re.U):
tags.append('NN')
if '[VERB]' in element:
tags.append('VB')
if 'adj.' in element and re.search('([\w|... |
Tries to scrape the gender for a given noun from leo.org.
def gender(self):
''' Tries to scrape the gender for a given noun from leo.org. '''
element = self._first('NN')
if element:
if re.search('([m|f|n)])\.', element, re.U):
genus = re.findall('([m|f|n)])\.', element, re.U)[0]
return genus |
Finds out if a scraping result should be considered empty.
def isempty(result):
''' Finds out if a scraping result should be considered empty. '''
if isinstance(result, list):
for element in result:
if isinstance(element, list):
if not isempty(element):
return False
else:
if element is not None... |
Returns a list of valid POS-tags for a given method.
def method2pos(method):
''' Returns a list of valid POS-tags for a given method. '''
if method in ('articles', 'plural', 'miniaturize', 'gender'):
pos = ['NN']
elif method in ('conjugate',):
pos = ['VB']
elif method in ('comparative, superlative'):
pos = ... |
Registers a scraper to make it available for the generic scraping interface.
def register(scraper):
''' Registers a scraper to make it available for the generic scraping interface. '''
global scrapers
language = scraper('').language
if not language:
raise Exception('No language specified for your scraper.')
if... |
Discovers all registered scrapers to be used for the generic scraping interface.
def discover(language):
''' Discovers all registered scrapers to be used for the generic scraping interface. '''
debug('Discovering scrapers for \'%s\'...' % (language,))
global scrapers, discovered
for language in scrapers.iterkeys(... |
Uses custom scrapers and calls provided method.
def scrape(language, method, word, *args, **kwargs):
''' Uses custom scrapers and calls provided method. '''
scraper = Scrape(language, word)
if hasattr(scraper, method):
function = getattr(scraper, method)
if callable(function):
return function(*args, **kwarg... |
Iterates over all available scrapers.
def iterscrapers(self, method, mode = None):
''' Iterates over all available scrapers. '''
global discovered
if discovered.has_key(self.language) and discovered[self.language].has_key(method):
for Scraper in discovered[self.language][method]:
yield Scraper |
Merges all scraping results to a list sorted by frequency of occurrence.
def merge(self, elements):
''' Merges all scraping results to a list sorted by frequency of occurrence. '''
from collections import Counter
from lltk.utils import list2tuple, tuple2list
# The list2tuple conversion is necessary because mu... |
Removes empty or incomplete answers.
def clean(self, elements):
''' Removes empty or incomplete answers. '''
cleanelements = []
for i in xrange(len(elements)):
if isempty(elements[i]):
return []
next = elements[i]
if isinstance(elements[i], (list, tuple)):
next = self.clean(elements[i])
if n... |
Decorator used to make sure that the downloading happens prior to running the task.
def _needs_download(self, f):
''' Decorator used to make sure that the downloading happens prior to running the task. '''
@wraps(f)
def wrapper(self, *args, **kwargs):
if not self.isdownloaded():
self.download()
return... |
Downloads HTML from url.
def download(self):
''' Downloads HTML from url. '''
self.page = requests.get(self.url)
self.tree = html.fromstring(self.page.text) |
Decorator used to make sure that there are elements prior to running the task.
def _needs_elements(self, f):
''' Decorator used to make sure that there are elements prior to running the task. '''
@wraps(f)
def wrapper(self, *args, **kwargs):
if self.elements == None:
self.getelements()
return f(self, ... |
Returns the first element with required POS-tag.
def _first(self, tag):
''' Returns the first element with required POS-tag. '''
self.getelements()
for element in self.elements:
if tag in self.pos(element):
return element
return None |
Returns a sanitized string.
def _normalize(self, string):
''' Returns a sanitized string. '''
string = string.replace(u'\xb7', '')
string = string.replace(u'\u0331', '')
string = string.replace(u'\u0323', '')
string = string.strip(' \n\rI.')
return string |
Tries to decide about the part of speech.
def pos(self, element = None):
''' Tries to decide about the part of speech. '''
tags = []
if element:
if element.startswith(('der', 'die', 'das')):
tags.append('NN')
if ' VERB' in element:
tags.append('VB')
if ' ADJ' in element:
tags.append('JJ')
... |
Tries to scrape the correct articles for singular and plural from de.pons.eu.
def articles(self):
''' Tries to scrape the correct articles for singular and plural from de.pons.eu. '''
result = [None, None]
element = self._first('NN')
if element:
result[0] = [element.split(' ')[0].replace('(die)', '').strip... |
Tries to scrape the plural version from pons.eu.
def plural(self):
''' Tries to scrape the plural version from pons.eu. '''
element = self._first('NN')
if element:
if 'kein Plur' in element:
# There is no plural
return ['']
if re.search(', ([\w|\s|/]+)>', element, re.U):
# Plural form is provi... |
Returns the articles (singular and plural) combined with singular and plural for a given noun.
def reference(language, word):
''' Returns the articles (singular and plural) combined with singular and plural for a given noun. '''
sg, pl, art = word, '/'.join(plural(language, word) or ['-']), [[''], ['']]
art[0], a... |
Translates a word using Google Translate.
def translate(src, dest, word):
''' Translates a word using Google Translate. '''
results = []
try:
from textblob import TextBlob
results.append(TextBlob(word).translate(from_lang = src, to = dest).string)
except ImportError:
pass
if not results:
return [None]
... |
Returns a list of URLs to suitable audiosamples for a given word.
def audiosamples(language, word, key = ''):
''' Returns a list of URLs to suitable audiosamples for a given word. '''
from lltk.audiosamples import forvo, google
urls = []
urls += forvo(language, word, key)
urls += google(language, word)
return ... |
Returns a list of URLs to suitable images for a given word.
def images(language, word, n = 20, *args, **kwargs):
''' Returns a list of URLs to suitable images for a given word.'''
from lltk.images import google
return google(language, word, n, *args, **kwargs) |
Returns the articles (singular and plural) for a given noun.
def articles(word):
''' Returns the articles (singular and plural) for a given noun. '''
from pattern.it import article
result = [[None], [None]]
genus = gender(word) or 'f'
result[0] = [article(word, function = 'definite', gender = genus)]
result[1]... |
Downloads suitable images for a given word from Google Images.
def google(language, word, n = 8, *args, **kwargs):
''' Downloads suitable images for a given word from Google Images. '''
if not kwargs.has_key('start'):
kwargs['start'] = 0
if not kwargs.has_key('itype'):
kwargs['itype'] = 'photo|clipart|lineart'... |
Returns a sanitized string.
def _normalize(self, string):
''' Returns a sanitized string. '''
string = string.replace(u'\xa0', '')
string = string.strip()
return string |
Extracts data from conjugation table.
def _extract(self, identifier):
''' Extracts data from conjugation table. '''
conjugation = []
if self.tree.xpath('//p/b[normalize-space(text()) = "' + identifier.decode('utf-8') + '"]'):
p = self.tree.xpath('//p/b[normalize-space(text()) = "' + identifier.decode('utf-8'... |
Tries to conjugate a given verb using verbix.com.
def conjugate(self, tense = 'present'):
''' Tries to conjugate a given verb using verbix.com.'''
if self.tenses.has_key(tense):
return self._extract(self.tenses[tense])
elif self.tenses.has_key(tense.title()):
return self._extract(self.tenses[tense.title()... |
Loads a configuration file (JSON).
def load(self, filename, replace = False):
''' Loads a configuration file (JSON). '''
import os, json, re
if os.path.exists(filename):
f = open(filename, 'r')
content = f.read()
content = re.sub('[\t ]*?[#].*?\n', '', content)
try:
settings = json.loads(content... |
Saves the current configuration to file 'filename' (JSON).
def save(self, filename):
''' Saves the current configuration to file 'filename' (JSON). '''
import json
f = open(filename, 'w')
json.dump(self.settings, f, indent = 4)
f.close() |
Returns a list of suitable audiosamples for a given word from Forvo.com.
def forvo(language, word, key):
''' Returns a list of suitable audiosamples for a given word from Forvo.com. '''
from requests import get
url = 'http://apifree.forvo.com/action/word-pronunciations/format/json/word/%s/language/%s/key/%s/' % (... |
Returns a sanitized string.
def _normalize(self, string):
''' Returns a sanitized string. '''
string = string.replace(u'\xb7', '')
string = string.replace(u'\xa0', ' ')
string = string.replace('selten: ', '')
string = string.replace('Alte Rechtschreibung', '')
string = string.strip()
return string |
Tries to decide about the part of speech.
def pos(self):
''' Tries to decide about the part of speech. '''
tags = []
if self.tree.xpath('//div[@id="mw-content-text"]//a[@title="Hilfe:Wortart"]/text()'):
info = self.tree.xpath('//div[@id="mw-content-text"]//a[@title="Hilfe:Wortart"]/text()')[0]
if info == ... |
Registers a cache.
def register(cache):
''' Registers a cache. '''
global caches
name = cache().name
if not caches.has_key(name):
caches[name] = cache |
Enables a specific cache for the current session. Remember that is has to be registered.
def enable(identifier = None, *args, **kwargs):
''' Enables a specific cache for the current session. Remember that is has to be registered. '''
global cache
if not identifier:
for item in (config['default-caches'] + ['NoCac... |
Decorator used for caching.
def cached(key = None, extradata = {}):
''' Decorator used for caching. '''
def decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
uid = key
if not uid:
from hashlib import md5
arguments = list(args) + [(a, kwargs[a]) for a in sorted(kwargs.keys())]
uid = md5(s... |
Decorator used to make sure that the connection has been established.
def needsconnection(self, f):
''' Decorator used to make sure that the connection has been established. '''
@wraps(f)
def wrapper(self, *args, **kwargs):
if not self.connection:
self.connect()
return f(self, *args, **kwargs)
retur... |
Use this as a decorator (implicitly or explicitly).
def language(l):
''' Use this as a decorator (implicitly or explicitly). '''
# Usage: @language('en') or function = language('en')(function)
def decorator(f):
''' Decorator used to prepend the language as an argument. '''
@wraps(f)
def wrapper(*args, **kw... |
Decorator used to load a custom method for a given language.
def _load_language_or_die(f):
''' Decorator used to load a custom method for a given language. '''
# This decorator checks if there's a custom method for a given language.
# If so, prefer the custom method, otherwise raise exception NotImplementedError.
... |
Returns a list of suitable textsamples for a given word using Tatoeba.org.
def tatoeba(language, word, minlength = 10, maxlength = 100):
''' Returns a list of suitable textsamples for a given word using Tatoeba.org. '''
word, sentences = unicode(word), []
page = requests.get('http://tatoeba.org/deu/sentences/searc... |
Tries to scrape the correct gender for a given word from wordreference.com
def gender(self):
''' Tries to scrape the correct gender for a given word from wordreference.com '''
elements = self.tree.xpath('//table[@class="WRD"]')
if len(elements):
elements = self.tree.xpath('//table[@class="WRD"]')[0]
if le... |
Converts ISO639 language identifier to the corresponding (human readable) language name.
def humanize(iso639):
''' Converts ISO639 language identifier to the corresponding (human readable) language name. '''
for i, element in enumerate(LANGUAGES):
if element[1] == iso639 or element[2] == iso639:
return element... |
Adds a new host to the cluster. This is only really useful for
unittests as normally hosts are added through the constructor and
changes after the cluster has been used for the first time are
unlikely to make sense.
def add_host(self, host_id=None, host='localhost', port=6379,
... |
Removes a host from the client. This only really useful for
unittests.
def remove_host(self, host_id):
"""Removes a host from the client. This only really useful for
unittests.
"""
with self._lock:
rv = self._hosts.pop(host_id, None) is not None
pool = ... |
Disconnects all connections from the internal pools.
def disconnect_pools(self):
"""Disconnects all connections from the internal pools."""
with self._lock:
for pool in self._pools.itervalues():
pool.disconnect()
self._pools.clear() |
Returns the router for the cluster. If the cluster reconfigures
the router will be recreated. Usually you do not need to interface
with the router yourself as the cluster's routing client does that
automatically.
This returns an instance of :class:`BaseRouter`.
def get_router(self):
... |
Returns the connection pool for the given host.
This connection pool is used by the redis clients to make sure
that it does not have to reconnect constantly. If you want to use
a custom redis client you can pass this in as connection pool
manually.
def get_pool_for_host(self, host_id)... |
Shortcut context manager for getting a routing client, beginning
a map operation and joining over the result. `max_concurrency`
defines how many outstanding parallel queries can exist before an
implicit join takes place.
In the context manager the client available is a
:class:`... |
Shortcut context manager for getting a routing client, beginning
a fanout operation and joining over the result.
In the context manager the client available is a
:class:`FanoutClient`. Example usage::
with cluster.fanout(hosts='all') as client:
client.flushdb()
de... |
Fanout to all hosts. Works otherwise exactly like :meth:`fanout`.
Example::
with cluster.all() as client:
client.flushdb()
def all(self, timeout=None, max_concurrency=64, auto_batch=True):
"""Fanout to all hosts. Works otherwise exactly like :meth:`fanout`.
Exam... |
Concurrently executes a sequence of commands on a Redis cluster that
are associated with a routing key, returning a new mapping where
values are a list of results that correspond to the command in the same
position. For example::
>>> cluster.execute_commands({
... 'foo... |
Given a pipeline of commands this attempts to merge the commands
into more efficient ones if that is possible.
def auto_batch_commands(commands):
"""Given a pipeline of commands this attempts to merge the commands
into more efficient ones if that is possible.
"""
pending_batch = None
for comma... |
Enqueue a new command into this pipeline.
def enqueue_command(self, command_name, args, options):
"""Enqueue a new command into this pipeline."""
assert_open(self)
promise = Promise()
self.commands.append((command_name, args, options, promise))
return promise |
Utility function that sends the buffer into the provided socket.
The buffer itself will slowly clear out and is modified in place.
def send_buffer(self):
"""Utility function that sends the buffer into the provided socket.
The buffer itself will slowly clear out and is modified in place.
... |
Sends all pending requests into the connection. The default is
to only send pending data that fits into the socket without blocking.
This returns `True` if all data was sent or `False` if pending data
is left over.
def send_pending_requests(self):
"""Sends all pending requests into the... |
Waits for all responses to come back and resolves the
eventual results.
def wait_for_responses(self, client):
"""Waits for all responses to come back and resolves the
eventual results.
"""
assert_open(self)
if self.has_pending_requests:
raise RuntimeError('C... |
Returns the command buffer for the given command and arguments.
def _get_command_buffer(self, host_id, command_name):
"""Returns the command buffer for the given command and arguments."""
buf = self._cb_poll.get(host_id)
if buf is not None:
return buf
if self._max_concurren... |
This is called by the command buffer when it closes.
def _release_command_buffer(self, command_buffer):
"""This is called by the command buffer when it closes."""
if command_buffer.closed:
return
self._cb_poll.unregister(command_buffer.host_id)
self.connection_pool.release(... |
Waits for all outstanding responses to come back or the timeout
to be hit.
def join(self, timeout=None):
"""Waits for all outstanding responses to come back or the timeout
to be hit.
"""
remaining = timeout
while self._cb_poll and (remaining is None or remaining > 0):
... |
Temporarily retarget the client for one call. This is useful
when having to deal with a subset of hosts for one call.
def target(self, hosts):
"""Temporarily retarget the client for one call. This is useful
when having to deal with a subset of hosts for one call.
"""
if self._... |
Temporarily retarget the client for one call to route
specifically to the one host that the given key routes to. In
that case the result on the promise is just the one host's value
instead of a dictionary.
.. versionadded:: 1.3
def target_key(self, key):
"""Temporarily retarge... |
Returns a thread unsafe mapping client. This client works
similar to a redis pipeline and returns eventual result objects.
It needs to be joined on to work properly. Instead of using this
directly you shold use the :meth:`map` context manager which
automatically joins.
Returns... |
Returns a thread unsafe fanout client.
Returns an instance of :class:`FanoutClient`.
def get_fanout_client(self, hosts, max_concurrency=64,
auto_batch=None):
"""Returns a thread unsafe fanout client.
Returns an instance of :class:`FanoutClient`.
"""
i... |
Returns a context manager for a map operation. This runs
multiple queries in parallel and then joins in the end to collect
all results.
In the context manager the client available is a
:class:`MappingClient`. Example usage::
results = {}
with cluster.map() as ... |
Returns a context manager for a map operation that fans out to
manually specified hosts instead of using the routing system. This
can for instance be used to empty the database on all hosts. The
context manager returns a :class:`FanoutClient`. Example usage::
with cluster.fanout(... |
Creates a promise object resolved with a certain value.
def resolved(value):
"""Creates a promise object resolved with a certain value."""
p = Promise()
p._state = 'resolved'
p.value = value
return p |
Creates a promise object rejected with a certain value.
def rejected(reason):
"""Creates a promise object rejected with a certain value."""
p = Promise()
p._state = 'rejected'
p.reason = reason
return p |
Resolves the promise with the given value.
def resolve(self, value):
"""Resolves the promise with the given value."""
if self is value:
raise TypeError('Cannot resolve promise with itself.')
if isinstance(value, Promise):
value.done(self.resolve, self.reject)
... |
Rejects the promise with the given reason.
def reject(self, reason):
"""Rejects the promise with the given reason."""
if self._state != 'pending':
raise RuntimeError('Promise is no longer pending.')
self.reason = reason
self._state = 'rejected'
errbacks = self._errb... |
Attaches some callbacks to the promise and returns the promise.
def done(self, on_success=None, on_failure=None):
"""Attaches some callbacks to the promise and returns the promise."""
if on_success is not None:
if self._state == 'pending':
self._callbacks.append(on_success)
... |
A utility method to add success and/or failure callback to the
promise which will also return another promise in the process.
def then(self, success=None, failure=None):
"""A utility method to add success and/or failure callback to the
promise which will also return another promise in the proce... |
Returns the key a command operates on.
def get_key(self, command, args):
"""Returns the key a command operates on."""
spec = COMMANDS.get(command.upper())
if spec is None:
raise UnroutableCommand('The command "%r" is unknown to the '
'router and ... |
Returns the host this command should be executed against.
def get_host_for_command(self, command, args):
"""Returns the host this command should be executed against."""
return self.get_host_for_key(self.get_key(command, args)) |
Updates the hash ring.
def _rebuild_circle(self):
"""Updates the hash ring."""
self._hashring = {}
self._sorted_keys = []
total_weight = 0
for node in self._nodes:
total_weight += self._weights.get(node, 1)
for node in self._nodes:
weight = self.... |
Return node position(integer) for a given key or None.
def _get_node_pos(self, key):
"""Return node position(integer) for a given key or None."""
if not self._hashring:
return
k = md5_bytes(key)
key = (k[3] << 24) | (k[2] << 16) | (k[1] << 8) | k[0]
nodes = self._s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.