repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
ottogroup/palladium
palladium/server.py
stream_cmd
python
def stream_cmd(argv=sys.argv[1:]): # pragma: no cover docopt(stream_cmd.__doc__, argv=argv) initialize_config() stream = PredictStream() stream.listen(sys.stdin, sys.stdout, sys.stderr)
\ Start the streaming server, which listens to stdin, processes line by line, and returns predictions. The input should consist of a list of json objects, where each object will result in a prediction. Each line is processed in a batch. Example input (must be on a single line): [{"sepal length": 1.0, "sepal width...
train
https://github.com/ottogroup/palladium/blob/f3a4372fba809efbd8da7c979a8c6faff04684dd/palladium/server.py#L362-L391
[ "def initialize_config(**extra):\n if _config.initialized:\n raise RuntimeError(\"Configuration was already initialized\")\n return get_config(**extra)\n", "def listen(self, io_in, io_out, io_err):\n \"\"\"Listens to provided io stream and writes predictions\n to output. In case of errors, the ...
"""HTTP API implementation. """ import sys from docopt import docopt from flask import Flask from flask import make_response from flask import request import numpy as np import ujson from werkzeug.exceptions import BadRequest from . import __version__ from .fit import activate as activate_base from .fit import fit a...
ottogroup/palladium
palladium/server.py
PredictService.sample_from_data
python
def sample_from_data(self, model, data): values = [] for key, type_name in self.mapping: value_type = self.types[type_name] values.append(value_type(data[key])) if self.unwrap_sample: assert len(values) == 1 return np.array(values[0]) else:...
Convert incoming sample *data* into a numpy array. :param model: The :class:`~Model` instance to use for making predictions. :param data: A dict-like with the sample's data, typically retrieved from ``request.args`` or similar.
train
https://github.com/ottogroup/palladium/blob/f3a4372fba809efbd8da7c979a8c6faff04684dd/palladium/server.py#L135-L152
null
class PredictService: """A default :class:`palladium.interfaces.PredictService` implementation. Aims to work out of the box for the most standard use cases. Allows overriding of specific parts of its logic by using granular methods to compose the work. """ types = { 'float': float, ...
ottogroup/palladium
palladium/server.py
PredictService.params_from_data
python
def params_from_data(self, model, data): params = {} for key, type_name in self.params: value_type = self.types[type_name] if key in data: params[key] = value_type(data[key]) elif hasattr(model, key): params[key] = getattr(model, key) ...
Retrieve additional parameters (keyword arguments) for ``model.predict`` from request *data*. :param model: The :class:`~Model` instance to use for making predictions. :param data: A dict-like with the parameter data, typically retrieved from ``request.args`` or si...
train
https://github.com/ottogroup/palladium/blob/f3a4372fba809efbd8da7c979a8c6faff04684dd/palladium/server.py#L154-L171
null
class PredictService: """A default :class:`palladium.interfaces.PredictService` implementation. Aims to work out of the box for the most standard use cases. Allows overriding of specific parts of its logic by using granular methods to compose the work. """ types = { 'float': float, ...
ottogroup/palladium
palladium/server.py
PredictService.response_from_prediction
python
def response_from_prediction(self, y_pred, single=True): result = y_pred.tolist() if single: result = result[0] response = { 'metadata': get_metadata(), 'result': result, } return make_ujson_response(response, status_code=200)
Turns a model's prediction in *y_pred* into a JSON response.
train
https://github.com/ottogroup/palladium/blob/f3a4372fba809efbd8da7c979a8c6faff04684dd/palladium/server.py#L179-L190
[ "def make_ujson_response(obj, status_code=200):\n \"\"\"Encodes the given *obj* to json and wraps it in a response.\n\n :return:\n A Flask response.\n \"\"\"\n json_encoded = ujson.encode(obj, ensure_ascii=False, double_precision=-1)\n resp = make_response(json_encoded)\n resp.mimetype = 'app...
class PredictService: """A default :class:`palladium.interfaces.PredictService` implementation. Aims to work out of the box for the most standard use cases. Allows overriding of specific parts of its logic by using granular methods to compose the work. """ types = { 'float': float, ...
ottogroup/palladium
palladium/server.py
PredictStream.listen
python
def listen(self, io_in, io_out, io_err): for line in io_in: if line.strip().lower() == 'exit': break try: y_pred = self.process_line(line) except Exception as e: io_out.write('[]\n') io_err.write( ...
Listens to provided io stream and writes predictions to output. In case of errors, the error stream will be used.
train
https://github.com/ottogroup/palladium/blob/f3a4372fba809efbd8da7c979a8c6faff04684dd/palladium/server.py#L340-L359
[ "def process_line(self, line):\n predict_service = self.predict_service\n datas = ujson.loads(line)\n samples = [predict_service.sample_from_data(self.model, data)\n for data in datas]\n samples = np.array(samples)\n params = predict_service.params_from_data(self.model, datas[0])\n r...
class PredictStream: """A class that helps make predictions through stdin and stdout. """ def __init__(self): self.model = get_config()['model_persister'].read() self.predict_service = get_config()['predict_service'] def process_line(self, line): predict_service = self.predict_s...
ottogroup/palladium
palladium/eval.py
list_cmd
python
def list_cmd(argv=sys.argv[1:]): # pragma: no cover docopt(list_cmd.__doc__, argv=argv) initialize_config(__mode__='fit') list()
\ List information about available models. Uses the 'model_persister' from the configuration to display a list of models and their metadata. Usage: pld-list [options] Options: -h --help Show this screen.
train
https://github.com/ottogroup/palladium/blob/f3a4372fba809efbd8da7c979a8c6faff04684dd/palladium/eval.py#L82-L97
[ "def initialize_config(**extra):\n if _config.initialized:\n raise RuntimeError(\"Configuration was already initialized\")\n return get_config(**extra)\n" ]
"""Utilities for testing the performance of a trained model. """ from pprint import pprint import sys from docopt import docopt from sklearn.metrics import get_scorer from .util import args_from_config from .util import initialize_config from .util import logger from .util import timer @args_from_config def test(d...
ottogroup/palladium
palladium/fit.py
fit_cmd
python
def fit_cmd(argv=sys.argv[1:]): # pragma: no cover arguments = docopt(fit_cmd.__doc__, argv=argv) no_save = arguments['--no-save'] no_activate = arguments['--no-activate'] save_if_better_than = arguments['--save-if-better-than'] evaluate = arguments['--evaluate'] or bool(save_if_better_than) if...
\ Fit a model and save to database. Will use 'dataset_loader_train', 'model', and 'model_perister' from the configuration file, to load a dataset to train a model with, and persist it. Usage: pld-fit [options] Options: -n --no-save Don't persist the fitted model to disk. --no-activate ...
train
https://github.com/ottogroup/palladium/blob/f3a4372fba809efbd8da7c979a8c6faff04684dd/palladium/fit.py#L96-L133
[ "def initialize_config(**extra):\n if _config.initialized:\n raise RuntimeError(\"Configuration was already initialized\")\n return get_config(**extra)\n" ]
"""Utilities for fitting modles. """ from warnings import warn import sys from datetime import datetime from docopt import docopt import pandas from sklearn.externals.joblib import parallel_backend from sklearn.metrics import get_scorer from sklearn.model_selection import GridSearchCV from .interfaces import annotat...
ottogroup/palladium
palladium/fit.py
admin_cmd
python
def admin_cmd(argv=sys.argv[1:]): # pragma: no cover arguments = docopt(admin_cmd.__doc__, argv=argv) initialize_config(__mode__='fit') if arguments['activate']: activate(model_version=int(arguments['<version>'])) elif arguments['delete']: delete(model_version=int(arguments['<version>']...
\ Activate or delete models. Models are usually made active right after fitting (see command pld-fit). The 'activate' command allows you to explicitly set the currently active model. Use 'pld-list' to get an overview of all available models along with their version identifiers. Deleting a model will simply remove i...
train
https://github.com/ottogroup/palladium/blob/f3a4372fba809efbd8da7c979a8c6faff04684dd/palladium/fit.py#L148-L171
[ "def initialize_config(**extra):\n if _config.initialized:\n raise RuntimeError(\"Configuration was already initialized\")\n return get_config(**extra)\n" ]
"""Utilities for fitting modles. """ from warnings import warn import sys from datetime import datetime from docopt import docopt import pandas from sklearn.externals.joblib import parallel_backend from sklearn.metrics import get_scorer from sklearn.model_selection import GridSearchCV from .interfaces import annotat...
ottogroup/palladium
palladium/fit.py
grid_search_cmd
python
def grid_search_cmd(argv=sys.argv[1:]): # pragma: no cover arguments = docopt(grid_search_cmd.__doc__, argv=argv) initialize_config(__mode__='fit') grid_search( save_results=arguments['--save-results'], persist_best=arguments['--persist-best'], )
\ Grid search parameters for the model. Uses 'dataset_loader_train', 'model', and 'grid_search' from the configuration to load a training dataset, and run a grid search on the model using the grid of hyperparameters. Usage: pld-grid-search [options] Options: --save-results=<fname> Save results to CSV file --...
train
https://github.com/ottogroup/palladium/blob/f3a4372fba809efbd8da7c979a8c6faff04684dd/palladium/fit.py#L250-L271
[ "def initialize_config(**extra):\n if _config.initialized:\n raise RuntimeError(\"Configuration was already initialized\")\n return get_config(**extra)\n" ]
"""Utilities for fitting modles. """ from warnings import warn import sys from datetime import datetime from docopt import docopt import pandas from sklearn.externals.joblib import parallel_backend from sklearn.metrics import get_scorer from sklearn.model_selection import GridSearchCV from .interfaces import annotat...
prawn-cake/vk-requests
vk_requests/streaming.py
Stream.consumer
python
def consumer(self, fn): if self._consumer_fn is not None: raise ValueError('Consumer function is already defined for this ' 'Stream instance') if not any([asyncio.iscoroutine(fn), asyncio.iscoroutinefunction(fn)]): raise ValueError('Consumer function ...
Consumer decorator :param fn: coroutine consumer function Example: >>> api = StreamingAPI('my_service_key') >>> stream = api.get_stream() >>> @stream.consumer >>> @asyncio.coroutine >>> def handle_event(payload): >>> print(payload)
train
https://github.com/prawn-cake/vk-requests/blob/dde01c1ed06f13de912506163a35d8c7e06a8f62/vk_requests/streaming.py#L26-L47
null
class Stream(object): """Stream representation""" def __init__(self, conn_url): self._conn_url = conn_url self._consumer_fn = None def __repr__(self): return '%s(conn_url=%s)' % (self.__class__.__name__, self._conn_url) def consume(self, timeout=None, loop=None): """S...
prawn-cake/vk-requests
vk_requests/streaming.py
Stream.consume
python
def consume(self, timeout=None, loop=None): if self._consumer_fn is None: raise ValueError('Consumer function is not defined yet') logger.info('Start consuming the stream') @asyncio.coroutine def worker(conn_url): extra_headers = { 'Connection': ...
Start consuming the stream :param timeout: int: if it's given then it stops consumer after given number of seconds
train
https://github.com/prawn-cake/vk-requests/blob/dde01c1ed06f13de912506163a35d8c7e06a8f62/vk_requests/streaming.py#L49-L98
null
class Stream(object): """Stream representation""" def __init__(self, conn_url): self._conn_url = conn_url self._consumer_fn = None def __repr__(self): return '%s(conn_url=%s)' % (self.__class__.__name__, self._conn_url) def consumer(self, fn): """Consumer decorator ...
prawn-cake/vk-requests
vk_requests/streaming.py
StreamingAPI.add_rule
python
def add_rule(self, value, tag): resp = requests.post(url=self.REQUEST_URL.format(**self._params), json={'rule': {'value': value, 'tag': tag}}) return resp.json()
Add a new rule :param value: str :param tag: str :return: dict of a json response
train
https://github.com/prawn-cake/vk-requests/blob/dde01c1ed06f13de912506163a35d8c7e06a8f62/vk_requests/streaming.py#L117-L126
null
class StreamingAPI(object): """VK Streaming API implementation Docs: https://vk.com/dev/streaming_api_docs """ REQUEST_URL = 'https://{endpoint}/rules?key={key}' STREAM_URL = 'wss://{endpoint}/stream?key={key}' def __init__(self, service_token): if not service_token: raise ...
prawn-cake/vk-requests
vk_requests/streaming.py
StreamingAPI.remove_rule
python
def remove_rule(self, tag): resp = requests.delete(url=self.REQUEST_URL.format(**self._params), json={'tag': tag}) return resp.json()
Remove a rule by tag
train
https://github.com/prawn-cake/vk-requests/blob/dde01c1ed06f13de912506163a35d8c7e06a8f62/vk_requests/streaming.py#L132-L138
null
class StreamingAPI(object): """VK Streaming API implementation Docs: https://vk.com/dev/streaming_api_docs """ REQUEST_URL = 'https://{endpoint}/rules?key={key}' STREAM_URL = 'wss://{endpoint}/stream?key={key}' def __init__(self, service_token): if not service_token: raise ...
prawn-cake/vk-requests
vk_requests/utils.py
stringify_values
python
def stringify_values(data): if not isinstance(data, dict): raise ValueError('Data must be dict. %r is passed' % data) values_dict = {} for key, value in data.items(): items = [] if isinstance(value, six.string_types): items.append(value) elif isinstance(value, It...
Coerce iterable values to 'val1,val2,valN' Example: fields=['nickname', 'city', 'can_see_all_posts'] --> fields='nickname,city,can_see_all_posts' :param data: dict :return: converted values dict
train
https://github.com/prawn-cake/vk-requests/blob/dde01c1ed06f13de912506163a35d8c7e06a8f62/vk_requests/utils.py#L22-L52
null
# -*- coding: utf-8 -*- import logging from collections import Iterable import bs4 import requests import six from vk_requests.exceptions import VkParseError, VkPageWarningsError logger = logging.getLogger('vk-requests') try: # Python 2 from urllib import urlencode from urlparse import urlparse, parse_q...
prawn-cake/vk-requests
vk_requests/utils.py
parse_url_query_params
python
def parse_url_query_params(url, fragment=True): parsed_url = urlparse(url) if fragment: url_query = parse_qsl(parsed_url.fragment) else: url_query = parse_qsl(parsed_url.query) # login_response_url_query can have multiple key url_query = dict(url_query) return url_query
Parse url query params :param fragment: bool: flag is used for parsing oauth url :param url: str: url string :return: dict
train
https://github.com/prawn-cake/vk-requests/blob/dde01c1ed06f13de912506163a35d8c7e06a8f62/vk_requests/utils.py#L55-L69
null
# -*- coding: utf-8 -*- import logging from collections import Iterable import bs4 import requests import six from vk_requests.exceptions import VkParseError, VkPageWarningsError logger = logging.getLogger('vk-requests') try: # Python 2 from urllib import urlencode from urlparse import urlparse, parse_q...
prawn-cake/vk-requests
vk_requests/utils.py
parse_form_action_url
python
def parse_form_action_url(html, parser=None): if parser is None: parser = bs4.BeautifulSoup(html, 'html.parser') forms = parser.find_all('form') if not forms: raise VkParseError('Action form is not found in the html \n%s' % html) if len(forms) > 1: raise VkParseError('Find more ...
Parse <form action="(.+)"> url :param html: str: raw html text :param parser: bs4.BeautifulSoup: html parser :return: url str: for example: /login.php?act=security_check&to=&hash=12346
train
https://github.com/prawn-cake/vk-requests/blob/dde01c1ed06f13de912506163a35d8c7e06a8f62/vk_requests/utils.py#L72-L88
null
# -*- coding: utf-8 -*- import logging from collections import Iterable import bs4 import requests import six from vk_requests.exceptions import VkParseError, VkPageWarningsError logger = logging.getLogger('vk-requests') try: # Python 2 from urllib import urlencode from urlparse import urlparse, parse_q...
prawn-cake/vk-requests
vk_requests/utils.py
parse_masked_phone_number
python
def parse_masked_phone_number(html, parser=None): if parser is None: parser = bs4.BeautifulSoup(html, 'html.parser') fields = parser.find_all('span', {'class': 'field_prefix'}) if not fields: raise VkParseError( 'No <span class="field_prefix">...</span> in the \n%s' % html) ...
Get masked phone number from security check html :param html: str: raw html text :param parser: bs4.BeautifulSoup: html parser :return: tuple of phone prefix and suffix, for example: ('+1234', '89') :rtype : tuple
train
https://github.com/prawn-cake/vk-requests/blob/dde01c1ed06f13de912506163a35d8c7e06a8f62/vk_requests/utils.py#L99-L119
null
# -*- coding: utf-8 -*- import logging from collections import Iterable import bs4 import requests import six from vk_requests.exceptions import VkParseError, VkPageWarningsError logger = logging.getLogger('vk-requests') try: # Python 2 from urllib import urlencode from urlparse import urlparse, parse_q...
prawn-cake/vk-requests
vk_requests/utils.py
check_html_warnings
python
def check_html_warnings(html, parser=None): if parser is None: parser = bs4.BeautifulSoup(html, 'html.parser') # Check warnings warnings = parser.find_all('div', {'class': 'service_msg_warning'}) if warnings: raise VkPageWarningsError('; '.join([w.get_text() for w in warnings])) ret...
Check html warnings :param html: str: raw html text :param parser: bs4.BeautifulSoup: html parser :raise VkPageWarningsError: in case of found warnings
train
https://github.com/prawn-cake/vk-requests/blob/dde01c1ed06f13de912506163a35d8c7e06a8f62/vk_requests/utils.py#L122-L136
null
# -*- coding: utf-8 -*- import logging from collections import Iterable import bs4 import requests import six from vk_requests.exceptions import VkParseError, VkPageWarningsError logger = logging.getLogger('vk-requests') try: # Python 2 from urllib import urlencode from urlparse import urlparse, parse_q...
prawn-cake/vk-requests
vk_requests/session.py
VKSession.http_session
python
def http_session(self): if self._http_session is None: session = VerboseHTTPSession() session.headers.update(self.DEFAULT_HTTP_HEADERS) self._http_session = session return self._http_session
HTTP Session property :return: vk_requests.utils.VerboseHTTPSession instance
train
https://github.com/prawn-cake/vk-requests/blob/dde01c1ed06f13de912506163a35d8c7e06a8f62/vk_requests/session.py#L63-L72
null
class VKSession(object): API_URL = 'https://api.vk.com/method/' DEFAULT_HTTP_HEADERS = { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' } LOGIN_URL = 'https://m.vk.com' AUTHORIZE_URL = 'https://oauth.vk.com/authorize' DIRECT_AUTHORIZE_URL = 'ht...
prawn-cake/vk-requests
vk_requests/session.py
VKSession.do_login
python
def do_login(self, http_session): response = http_session.get(self.LOGIN_URL) action_url = parse_form_action_url(response.text) # Stop login it action url is not found if not action_url: logger.debug(response.text) raise VkParseError("Can't parse form action url...
Do vk login :param http_session: vk_requests.utils.VerboseHTTPSession: http session
train
https://github.com/prawn-cake/vk-requests/blob/dde01c1ed06f13de912506163a35d8c7e06a8f62/vk_requests/session.py#L85-L134
[ "def parse_url_query_params(url, fragment=True):\n \"\"\"Parse url query params\n\n :param fragment: bool: flag is used for parsing oauth url\n :param url: str: url string\n :return: dict\n \"\"\"\n parsed_url = urlparse(url)\n if fragment:\n url_query = parse_qsl(parsed_url.fragment)\n ...
class VKSession(object): API_URL = 'https://api.vk.com/method/' DEFAULT_HTTP_HEADERS = { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' } LOGIN_URL = 'https://m.vk.com' AUTHORIZE_URL = 'https://oauth.vk.com/authorize' DIRECT_AUTHORIZE_URL = 'ht...
prawn-cake/vk-requests
vk_requests/session.py
VKSession.do_implicit_flow_authorization
python
def do_implicit_flow_authorization(self, session): logger.info('Doing implicit flow authorization, app_id=%s', self.app_id) auth_data = { 'client_id': self.app_id, 'display': 'mobile', 'response_type': 'token', 'scope': self.scope, 'redirect_ur...
Standard OAuth2 authorization method. It's used for getting access token More info: https://vk.com/dev/implicit_flow_user
train
https://github.com/prawn-cake/vk-requests/blob/dde01c1ed06f13de912506163a35d8c7e06a8f62/vk_requests/session.py#L136-L177
[ "def parse_url_query_params(url, fragment=True):\n \"\"\"Parse url query params\n\n :param fragment: bool: flag is used for parsing oauth url\n :param url: str: url string\n :return: dict\n \"\"\"\n parsed_url = urlparse(url)\n if fragment:\n url_query = parse_qsl(parsed_url.fragment)\n ...
class VKSession(object): API_URL = 'https://api.vk.com/method/' DEFAULT_HTTP_HEADERS = { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' } LOGIN_URL = 'https://m.vk.com' AUTHORIZE_URL = 'https://oauth.vk.com/authorize' DIRECT_AUTHORIZE_URL = 'ht...
prawn-cake/vk-requests
vk_requests/session.py
VKSession.do_direct_authorization
python
def do_direct_authorization(self, session): logger.info('Doing direct authorization, app_id=%s', self.app_id) auth_data = { 'client_id': self.app_id, 'client_secret': self._client_secret, 'username': self._login, 'password': self._password, 'gr...
Direct Authorization, more info: https://vk.com/dev/auth_direct
train
https://github.com/prawn-cake/vk-requests/blob/dde01c1ed06f13de912506163a35d8c7e06a8f62/vk_requests/session.py#L179-L211
[ "def stringify_values(data):\n \"\"\"Coerce iterable values to 'val1,val2,valN'\n\n Example:\n fields=['nickname', 'city', 'can_see_all_posts']\n --> fields='nickname,city,can_see_all_posts'\n\n :param data: dict\n :return: converted values dict\n \"\"\"\n if not isinstance(data, dic...
class VKSession(object): API_URL = 'https://api.vk.com/method/' DEFAULT_HTTP_HEADERS = { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' } LOGIN_URL = 'https://m.vk.com' AUTHORIZE_URL = 'https://oauth.vk.com/authorize' DIRECT_AUTHORIZE_URL = 'ht...
prawn-cake/vk-requests
vk_requests/session.py
VKSession.require_auth_captcha
python
def require_auth_captcha(self, response, query_params, login_form_data, http_session): logger.info('Captcha is needed. Query params: %s', query_params) form_text = response.text action_url = parse_form_action_url(form_text) logger.debug('form action url: %s'...
Resolve auth captcha case :param response: http response :param query_params: dict: response query params, for example: {'s': '0', 'email': 'my@email', 'dif': '1', 'role': 'fast', 'sid': '1'} :param login_form_data: dict :param http_session: requests.Session :return: :r...
train
https://github.com/prawn-cake/vk-requests/blob/dde01c1ed06f13de912506163a35d8c7e06a8f62/vk_requests/session.py#L266-L294
[ "def parse_form_action_url(html, parser=None):\n \"\"\"Parse <form action=\"(.+)\"> url\n\n :param html: str: raw html text\n :param parser: bs4.BeautifulSoup: html parser\n :return: url str: for example: /login.php?act=security_check&to=&hash=12346\n \"\"\"\n if parser is None:\n parser = ...
class VKSession(object): API_URL = 'https://api.vk.com/method/' DEFAULT_HTTP_HEADERS = { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' } LOGIN_URL = 'https://m.vk.com' AUTHORIZE_URL = 'https://oauth.vk.com/authorize' DIRECT_AUTHORIZE_URL = 'ht...
prawn-cake/vk-requests
vk_requests/session.py
VKSession._get_access_token
python
def _get_access_token(self): if self._service_token: logger.info('Use service token: %s', 5 * '*' + self._service_token[50:]) return self._service_token if not all([self.app_id, self._login, self._password]): raise ValueError( ...
Get access token using app_id, login and password OR service token (service token docs: https://vk.com/dev/service_token
train
https://github.com/prawn-cake/vk-requests/blob/dde01c1ed06f13de912506163a35d8c7e06a8f62/vk_requests/session.py#L348-L377
null
class VKSession(object): API_URL = 'https://api.vk.com/method/' DEFAULT_HTTP_HEADERS = { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' } LOGIN_URL = 'https://m.vk.com' AUTHORIZE_URL = 'https://oauth.vk.com/authorize' DIRECT_AUTHORIZE_URL = 'ht...
prawn-cake/vk-requests
vk_requests/session.py
VKSession.get_captcha_key
python
def get_captcha_key(self, captcha_image_url): if self.interactive: print('Open CAPTCHA image url in your browser and enter it below: ', captcha_image_url) captcha_key = raw_input('Enter CAPTCHA key: ') return captcha_key else: raise VkAu...
Read CAPTCHA key from user input
train
https://github.com/prawn-cake/vk-requests/blob/dde01c1ed06f13de912506163a35d8c7e06a8f62/vk_requests/session.py#L379-L390
null
class VKSession(object): API_URL = 'https://api.vk.com/method/' DEFAULT_HTTP_HEADERS = { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' } LOGIN_URL = 'https://m.vk.com' AUTHORIZE_URL = 'https://oauth.vk.com/authorize' DIRECT_AUTHORIZE_URL = 'ht...
prawn-cake/vk-requests
vk_requests/session.py
VKSession.make_request
python
def make_request(self, request, captcha_response=None): logger.debug('Prepare API Method request %r', request) response = self._send_api_request(request=request, captcha_response=captcha_response) response.raise_for_status() response_or_error = j...
Make api request helper function :param request: vk_requests.api.Request instance :param captcha_response: None or dict, e.g {'sid': <sid>, 'key': <key>} :return: dict: json decoded http response
train
https://github.com/prawn-cake/vk-requests/blob/dde01c1ed06f13de912506163a35d8c7e06a8f62/vk_requests/session.py#L398-L442
[ "def is_captcha_needed(self):\n return self.code == CAPTCHA_IS_NEEDED\n", "def get_captcha_key(self, captcha_image_url):\n \"\"\"Read CAPTCHA key from user input\"\"\"\n\n if self.interactive:\n print('Open CAPTCHA image url in your browser and enter it below: ',\n captcha_image_url)\...
class VKSession(object): API_URL = 'https://api.vk.com/method/' DEFAULT_HTTP_HEADERS = { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' } LOGIN_URL = 'https://m.vk.com' AUTHORIZE_URL = 'https://oauth.vk.com/authorize' DIRECT_AUTHORIZE_URL = 'ht...
prawn-cake/vk-requests
vk_requests/session.py
VKSession._send_api_request
python
def _send_api_request(self, request, captcha_response=None): url = self.API_URL + request.method_name # Prepare request arguments method_kwargs = {'v': self.api_version} # Shape up the request data for values in (request.method_args,): method_kwargs.update(stringify...
Prepare and send HTTP API request :param request: vk_requests.api.Request instance :param captcha_response: None or dict :return: HTTP response
train
https://github.com/prawn-cake/vk-requests/blob/dde01c1ed06f13de912506163a35d8c7e06a8f62/vk_requests/session.py#L444-L473
[ "def stringify_values(data):\n \"\"\"Coerce iterable values to 'val1,val2,valN'\n\n Example:\n fields=['nickname', 'city', 'can_see_all_posts']\n --> fields='nickname,city,can_see_all_posts'\n\n :param data: dict\n :return: converted values dict\n \"\"\"\n if not isinstance(data, dic...
class VKSession(object): API_URL = 'https://api.vk.com/method/' DEFAULT_HTTP_HEADERS = { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' } LOGIN_URL = 'https://m.vk.com' AUTHORIZE_URL = 'https://oauth.vk.com/authorize' DIRECT_AUTHORIZE_URL = 'ht...
prawn-cake/vk-requests
vk_requests/__init__.py
create_api
python
def create_api(app_id=None, login=None, password=None, phone_number=None, scope='offline', api_version='5.92', http_params=None, interactive=False, service_token=None, client_secret=None, two_fa_supported=False, two_fa_force_sms=False): session = VKSession(app_id=app_id,...
Factory method to explicitly create API with app_id, login, password and phone_number parameters. If the app_id, login, password are not passed, then token-free session will be created automatically :param app_id: int: vk application id, more info: https://vk.com/dev/main :param login: str: vk log...
train
https://github.com/prawn-cake/vk-requests/blob/dde01c1ed06f13de912506163a35d8c7e06a8f62/vk_requests/__init__.py#L21-L61
null
# -*- coding: utf-8 -*- import sys from vk_requests.session import VKSession from vk_requests.api import API __version__ = '1.2.0' PY_VERSION = sys.version_info.major, sys.version_info.minor if PY_VERSION < (3, 4): import warnings warnings.simplefilter('default') warnings.warn('Support of all python v...
samuelcolvin/arq
arq/cli.py
cli
python
def cli(*, worker_settings, burst, check, watch, verbose): sys.path.append(os.getcwd()) worker_settings = import_string(worker_settings) logging.config.dictConfig(default_log_config(verbose)) if check: exit(check_health(worker_settings)) else: kwargs = {} if burst is None else {'bur...
Job queues in python with asyncio and redis. CLI to run the arq worker.
train
https://github.com/samuelcolvin/arq/blob/1434646b48c45bd27e392f0162976404e4d8021d/arq/cli.py#L27-L45
[ "def check_health(settings_cls) -> int:\n \"\"\"\n Run a health check on the worker and return the appropriate exit code.\n :return: 0 if successful, 1 if not\n \"\"\"\n cls_kwargs = get_kwargs(settings_cls)\n loop = asyncio.get_event_loop()\n return loop.run_until_complete(async_check_health(c...
import asyncio import logging.config import os import sys from signal import Signals import click from pydantic.utils import import_string from .logs import default_log_config from .version import VERSION from .worker import check_health, create_worker, run_worker burst_help = 'Batch mode: exit once no jobs are foun...
samuelcolvin/arq
arq/cron.py
next_cron
python
def next_cron( previous_dt: datetime, *, month: Union[None, set, int] = None, day: Union[None, set, int] = None, weekday: Union[None, set, int, str] = None, hour: Union[None, set, int] = None, minute: Union[None, set, int] = None, second: Union[None, set, int] = 0, microsecond: int =...
Find the next datetime matching the given parameters.
train
https://github.com/samuelcolvin/arq/blob/1434646b48c45bd27e392f0162976404e4d8021d/arq/cron.py#L65-L91
[ "def _get_next_dt(dt_, options): # noqa: C901\n for field in dt_fields:\n v = options[field]\n if v is None:\n continue\n if field == D.weekday:\n next_v = dt_.weekday()\n else:\n next_v = getattr(dt_, field)\n if isinstance(v, int):\n ...
import asyncio from dataclasses import dataclass from datetime import datetime, timedelta from enum import Enum from typing import Callable, Optional, Union from pydantic.utils import import_string from arq.utils import SecondsTimedelta, to_seconds class D(str, Enum): month = 'month' day = 'day' weekday...
samuelcolvin/arq
arq/cron.py
cron
python
def cron( coroutine: Union[str, Callable], *, name: Optional[str] = None, month: Union[None, set, int] = None, day: Union[None, set, int] = None, weekday: Union[None, set, int, str] = None, hour: Union[None, set, int] = None, minute: Union[None, set, int] = None, second: Union[None, ...
Create a cron job, eg. it should be executed at specific times. Workers will enqueue this job at or just after the set times. If ``unique`` is true (the default) the job will only be run once even if multiple workers are running. :param coroutine: coroutine function to run :param name: name of the job...
train
https://github.com/samuelcolvin/arq/blob/1434646b48c45bd27e392f0162976404e4d8021d/arq/cron.py#L128-L191
[ "def to_seconds(td: Optional[SecondsTimedelta]) -> Optional[float]:\n if td is None:\n return td\n elif isinstance(td, timedelta):\n return td.total_seconds()\n return td\n" ]
import asyncio from dataclasses import dataclass from datetime import datetime, timedelta from enum import Enum from typing import Callable, Optional, Union from pydantic.utils import import_string from arq.utils import SecondsTimedelta, to_seconds class D(str, Enum): month = 'month' day = 'day' weekday...
samuelcolvin/arq
arq/utils.py
to_unix_ms
python
def to_unix_ms(dt: datetime) -> int: utcoffset = dt.utcoffset() ep = epoch if utcoffset is None else epoch_tz return as_int((dt - ep).total_seconds() * 1000)
convert a datetime to number of milliseconds since 1970 and calculate timezone offset
train
https://github.com/samuelcolvin/arq/blob/1434646b48c45bd27e392f0162976404e4d8021d/arq/utils.py#L23-L29
[ "def as_int(f: float) -> int:\n return int(round(f))\n" ]
import asyncio import logging from datetime import datetime, timedelta, timezone from time import time from typing import Optional, Union logger = logging.getLogger('arq.utils') epoch = datetime(1970, 1, 1) epoch_tz = epoch.replace(tzinfo=timezone.utc) SecondsTimedelta = Union[int, float, timedelta] def as_int(f: ...
samuelcolvin/arq
arq/utils.py
truncate
python
def truncate(s: str, length: int = DEFAULT_CURTAIL) -> str: if len(s) > length: s = s[: length - 1] + '…' return s
Truncate a string and add an ellipsis (three dots) to the end if it was too long :param s: string to possibly truncate :param length: length to truncate the string to
train
https://github.com/samuelcolvin/arq/blob/1434646b48c45bd27e392f0162976404e4d8021d/arq/utils.py#L66-L75
null
import asyncio import logging from datetime import datetime, timedelta, timezone from time import time from typing import Optional, Union logger = logging.getLogger('arq.utils') epoch = datetime(1970, 1, 1) epoch_tz = epoch.replace(tzinfo=timezone.utc) SecondsTimedelta = Union[int, float, timedelta] def as_int(f: ...
samuelcolvin/arq
arq/connections.py
create_pool
python
async def create_pool(settings: RedisSettings = None, *, _retry: int = 0) -> ArqRedis: settings = settings or RedisSettings() addr = settings.host, settings.port try: pool = await aioredis.create_redis_pool( addr, db=settings.database, password=settings.password, ...
Create a new redis pool, retrying up to ``conn_retries`` times if the connection fails. Similar to ``aioredis.create_redis_pool`` except it returns a :class:`arq.connections.ArqRedis` instance, thus allowing job enqueuing.
train
https://github.com/samuelcolvin/arq/blob/1434646b48c45bd27e392f0162976404e4d8021d/arq/connections.py#L125-L163
[ "async def create_pool(settings: RedisSettings = None, *, _retry: int = 0) -> ArqRedis:\n \"\"\"\n Create a new redis pool, retrying up to ``conn_retries`` times if the connection fails.\n\n Similar to ``aioredis.create_redis_pool`` except it returns a :class:`arq.connections.ArqRedis` instance,\n thus ...
import asyncio import logging from dataclasses import dataclass from datetime import datetime, timedelta from operator import attrgetter from typing import Any, List, Optional, Union from uuid import uuid4 import aioredis from aioredis import MultiExecError, Redis from .constants import job_key_prefix, queue_name, re...
samuelcolvin/arq
arq/connections.py
ArqRedis.enqueue_job
python
async def enqueue_job( self, function: str, *args: Any, _job_id: Optional[str] = None, _defer_until: Optional[datetime] = None, _defer_by: Union[None, int, float, timedelta] = None, _expires: Union[None, int, float, timedelta] = None, _job_try: Optional[in...
Enqueue a job. :param function: Name of the function to call :param args: args to pass to the function :param _job_id: ID of the job, can be used to enforce job uniqueness :param _defer_until: datetime at which to run the job :param _defer_by: duration to wait before running the...
train
https://github.com/samuelcolvin/arq/blob/1434646b48c45bd27e392f0162976404e4d8021d/arq/connections.py#L48-L107
[ "def to_ms(td: Optional[SecondsTimedelta]) -> Optional[int]:\n if td is None:\n return td\n elif isinstance(td, timedelta):\n td = td.total_seconds()\n return as_int(td * 1000)\n" ]
class ArqRedis(Redis): """ Thin subclass of ``aioredis.Redis`` which adds :func:`arq.connections.enqueue_job`. """ async def _get_job_result(self, key): job_id = key[len(result_key_prefix) :] job = Job(job_id, self) r = await job.result_info() r.job_id = job_id ...
samuelcolvin/arq
arq/connections.py
ArqRedis.all_job_results
python
async def all_job_results(self) -> List[JobResult]: keys = await self.keys(result_key_prefix + '*') results = await asyncio.gather(*[self._get_job_result(k) for k in keys]) return sorted(results, key=attrgetter('enqueue_time'))
Get results for all jobs in redis.
train
https://github.com/samuelcolvin/arq/blob/1434646b48c45bd27e392f0162976404e4d8021d/arq/connections.py#L116-L122
null
class ArqRedis(Redis): """ Thin subclass of ``aioredis.Redis`` which adds :func:`arq.connections.enqueue_job`. """ async def enqueue_job( self, function: str, *args: Any, _job_id: Optional[str] = None, _defer_until: Optional[datetime] = None, _defer_by: U...
samuelcolvin/arq
docs/examples/job_ids.py
main
python
async def main(): redis = await create_pool(RedisSettings()) # no id, random id will be generated job1 = await redis.enqueue_job('the_task') print(job1) # random id again, again the job will be enqueued and a job will be returned job2 = await redis.enqueue_job('the_task') print(job2) "...
> <arq job 99edfef86ccf4145b2f64ee160fa3297>
train
https://github.com/samuelcolvin/arq/blob/1434646b48c45bd27e392f0162976404e4d8021d/docs/examples/job_ids.py#L9-L38
[ "async def create_pool(settings: RedisSettings = None, *, _retry: int = 0) -> ArqRedis:\n \"\"\"\n Create a new redis pool, retrying up to ``conn_retries`` times if the connection fails.\n\n Similar to ``aioredis.create_redis_pool`` except it returns a :class:`arq.connections.ArqRedis` instance,\n thus ...
import asyncio from arq import create_pool from arq.connections import RedisSettings async def the_task(ctx): print('running the task with id', ctx['job_id']) class WorkerSettings: functions = [the_task] if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main())
samuelcolvin/arq
arq/worker.py
func
python
def func( coroutine: Union[str, Function, Callable], *, name: Optional[str] = None, keep_result: Optional[SecondsTimedelta] = None, timeout: Optional[SecondsTimedelta] = None, max_tries: Optional[int] = None, ) -> Function: if isinstance(coroutine, Function): return coroutine if...
Wrapper for a job function which lets you configure more settings. :param coroutine: coroutine function to call, can be a string to import :param name: name for function, if None, ``coroutine.__qualname__`` is used :param keep_result: duration to keep the result for, if 0 the result is not kept :param ...
train
https://github.com/samuelcolvin/arq/blob/1434646b48c45bd27e392f0162976404e4d8021d/arq/worker.py#L53-L81
null
import asyncio import inspect import logging import signal from dataclasses import dataclass from datetime import datetime from functools import partial from signal import Signals from time import time from typing import Awaitable, Callable, Dict, List, Optional, Sequence, Union import async_timeout from aioredis impo...
samuelcolvin/arq
arq/worker.py
check_health
python
def check_health(settings_cls) -> int: cls_kwargs = get_kwargs(settings_cls) loop = asyncio.get_event_loop() return loop.run_until_complete(async_check_health(cls_kwargs.get('redis_settings')))
Run a health check on the worker and return the appropriate exit code. :return: 0 if successful, 1 if not
train
https://github.com/samuelcolvin/arq/blob/1434646b48c45bd27e392f0162976404e4d8021d/arq/worker.py#L518-L525
[ "def get_kwargs(settings_cls):\n worker_args = set(inspect.signature(Worker).parameters.keys())\n d = settings_cls if isinstance(settings_cls, dict) else settings_cls.__dict__\n return {k: v for k, v in d.items() if k in worker_args}\n", "async def async_check_health(redis_settings: Optional[RedisSetting...
import asyncio import inspect import logging import signal from dataclasses import dataclass from datetime import datetime from functools import partial from signal import Signals from time import time from typing import Awaitable, Callable, Dict, List, Optional, Sequence, Union import async_timeout from aioredis impo...
samuelcolvin/arq
arq/worker.py
Worker.run
python
def run(self) -> None: self.main_task = self.loop.create_task(self.main()) try: self.loop.run_until_complete(self.main_task) except asyncio.CancelledError: # happens on shutdown, fine pass finally: self.loop.run_until_complete(self.close())
Sync function to run the worker, finally closes worker connections.
train
https://github.com/samuelcolvin/arq/blob/1434646b48c45bd27e392f0162976404e4d8021d/arq/worker.py#L193-L204
[ "async def main(self):\n if self.pool is None:\n self.pool = await create_pool(self.redis_settings)\n\n logger.info('Starting worker for %d functions: %s', len(self.functions), ', '.join(self.functions))\n await log_redis_info(self.pool, logger.info)\n self.ctx['redis'] = self.pool\n if self.o...
class Worker: """ Main class for running jobs. :param functions: list of functions to register, can either be raw coroutine functions or the result of :func:`arq.worker.func`. :param cron_jobs: list of cron jobs to run, use :func:`arq.cron.cron` to create them :param redis_settings: settings...
samuelcolvin/arq
arq/worker.py
Worker.async_run
python
async def async_run(self) -> None: self.main_task = self.loop.create_task(self.main()) await self.main_task
Asynchronously run the worker, does not close connections. Useful when testing.
train
https://github.com/samuelcolvin/arq/blob/1434646b48c45bd27e392f0162976404e4d8021d/arq/worker.py#L206-L211
[ "async def main(self):\n if self.pool is None:\n self.pool = await create_pool(self.redis_settings)\n\n logger.info('Starting worker for %d functions: %s', len(self.functions), ', '.join(self.functions))\n await log_redis_info(self.pool, logger.info)\n self.ctx['redis'] = self.pool\n if self.o...
class Worker: """ Main class for running jobs. :param functions: list of functions to register, can either be raw coroutine functions or the result of :func:`arq.worker.func`. :param cron_jobs: list of cron jobs to run, use :func:`arq.cron.cron` to create them :param redis_settings: settings...
samuelcolvin/arq
arq/worker.py
Worker.run_check
python
async def run_check(self) -> int: await self.async_run() if self.jobs_failed: failed_job_results = [r for r in await self.pool.all_job_results() if not r.success] raise FailedJobs(self.jobs_failed, failed_job_results) else: return self.jobs_complete
Run :func:`arq.worker.Worker.async_run`, check for failed jobs and raise :class:`arq.worker.FailedJobs` if any jobs have failed. :return: number of completed jobs
train
https://github.com/samuelcolvin/arq/blob/1434646b48c45bd27e392f0162976404e4d8021d/arq/worker.py#L213-L225
[ "async def async_run(self) -> None:\n \"\"\"\n Asynchronously run the worker, does not close connections. Useful when testing.\n \"\"\"\n self.main_task = self.loop.create_task(self.main())\n await self.main_task\n" ]
class Worker: """ Main class for running jobs. :param functions: list of functions to register, can either be raw coroutine functions or the result of :func:`arq.worker.func`. :param cron_jobs: list of cron jobs to run, use :func:`arq.cron.cron` to create them :param redis_settings: settings...
samuelcolvin/arq
docs/examples/job_results.py
main
python
async def main(): redis = await create_pool(RedisSettings()) job = await redis.enqueue_job('the_task') # get the job's id print(job.job_id) # get information about the job, will include results if the job has finished, but # doesn't await the job's result debug(await job.info()) """ ...
> 68362958a244465b9be909db4b7b5ab4 (or whatever)
train
https://github.com/samuelcolvin/arq/blob/1434646b48c45bd27e392f0162976404e4d8021d/docs/examples/job_results.py#L12-L50
[ "async def create_pool(settings: RedisSettings = None, *, _retry: int = 0) -> ArqRedis:\n \"\"\"\n Create a new redis pool, retrying up to ``conn_retries`` times if the connection fails.\n\n Similar to ``aioredis.create_redis_pool`` except it returns a :class:`arq.connections.ArqRedis` instance,\n thus ...
import asyncio from arq import create_pool from arq.connections import RedisSettings # requires `pip install devtools`, used for pretty printing of job info from devtools import debug async def the_task(ctx): print('running the task') return 42 class WorkerSettings: functions = [the_task] if __name__ =...
samuelcolvin/arq
arq/jobs.py
Job.result
python
async def result(self, timeout: Optional[float] = None, *, pole_delay: float = 0.5) -> Any: async for delay in poll(pole_delay): info = await self.result_info() if info: result = info.result if info.success: return result ...
Get the result of the job, including waiting if it's not yet available. If the job raised an exception, it will be raised here. :param timeout: maximum time to wait for the job result before raising ``TimeoutError``, will wait forever :param pole_delay: how often to poll redis for the job resul...
train
https://github.com/samuelcolvin/arq/blob/1434646b48c45bd27e392f0162976404e4d8021d/arq/jobs.py#L62-L79
[ "async def poll(step: float = 0.5):\n loop = asyncio.get_event_loop()\n start = loop.time()\n while True:\n before = loop.time()\n yield before - start\n after = loop.time()\n wait = max([0, step - after + before])\n await asyncio.sleep(wait)\n", "async def result_info(...
class Job: """ Holds data a reference to a job. """ __slots__ = 'job_id', '_redis' def __init__(self, job_id: str, redis): self.job_id = job_id self._redis = redis async def info(self) -> Optional[JobDef]: """ All information on a job, including its result if ...
samuelcolvin/arq
arq/jobs.py
Job.info
python
async def info(self) -> Optional[JobDef]: info = await self.result_info() if not info: v = await self._redis.get(job_key_prefix + self.job_id, encoding=None) if v: info = unpickle_job(v) if info: info.score = await self._redis.zscore(queue_name...
All information on a job, including its result if it's available, does not wait for the result.
train
https://github.com/samuelcolvin/arq/blob/1434646b48c45bd27e392f0162976404e4d8021d/arq/jobs.py#L81-L92
[ "async def result_info(self) -> Optional[JobResult]:\n \"\"\"\n Information about the job result if available, does not wait for the result. Does not raise an exception\n even if the job raised one.\n \"\"\"\n v = await self._redis.get(result_key_prefix + self.job_id, encoding=None)\n if v:\n ...
class Job: """ Holds data a reference to a job. """ __slots__ = 'job_id', '_redis' def __init__(self, job_id: str, redis): self.job_id = job_id self._redis = redis async def result(self, timeout: Optional[float] = None, *, pole_delay: float = 0.5) -> Any: """ G...
samuelcolvin/arq
arq/jobs.py
Job.result_info
python
async def result_info(self) -> Optional[JobResult]: v = await self._redis.get(result_key_prefix + self.job_id, encoding=None) if v: return unpickle_result(v)
Information about the job result if available, does not wait for the result. Does not raise an exception even if the job raised one.
train
https://github.com/samuelcolvin/arq/blob/1434646b48c45bd27e392f0162976404e4d8021d/arq/jobs.py#L94-L101
null
class Job: """ Holds data a reference to a job. """ __slots__ = 'job_id', '_redis' def __init__(self, job_id: str, redis): self.job_id = job_id self._redis = redis async def result(self, timeout: Optional[float] = None, *, pole_delay: float = 0.5) -> Any: """ G...
samuelcolvin/arq
arq/jobs.py
Job.status
python
async def status(self) -> JobStatus: if await self._redis.exists(result_key_prefix + self.job_id): return JobStatus.complete elif await self._redis.exists(in_progress_key_prefix + self.job_id): return JobStatus.in_progress else: score = await self._redis.zscor...
Status of the job.
train
https://github.com/samuelcolvin/arq/blob/1434646b48c45bd27e392f0162976404e4d8021d/arq/jobs.py#L103-L115
null
class Job: """ Holds data a reference to a job. """ __slots__ = 'job_id', '_redis' def __init__(self, job_id: str, redis): self.job_id = job_id self._redis = redis async def result(self, timeout: Optional[float] = None, *, pole_delay: float = 0.5) -> Any: """ G...
iancmcc/ouimeaux
ouimeaux/pysignals/inspect.py
get_func_full_args
python
def get_func_full_args(func): if six.PY2: argspec = inspect.getargspec(func) args = argspec.args[1:] # ignore 'self' defaults = argspec.defaults or [] # Split args into two lists depending on whether they have default value no_default = args[:len(args) - len(defaults)] ...
Return a list of (argument name, default value) tuples. If the argument does not have a default value, omit it in the tuple. Arguments such as *args and **kwargs are also included.
train
https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/pysignals/inspect.py#L46-L81
null
from __future__ import absolute_import import inspect import six def getargspec(func): if six.PY2: return inspect.getargspec(func) sig = inspect.signature(func) args = [ p.name for p in sig.parameters.values() if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD ] vararg...
iancmcc/ouimeaux
ouimeaux/pysignals/inspect.py
func_accepts_var_args
python
def func_accepts_var_args(func): if six.PY2: return inspect.getargspec(func)[1] is not None return any( p for p in inspect.signature(func).parameters.values() if p.kind == p.VAR_POSITIONAL )
Return True if function 'func' accepts positional arguments *args.
train
https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/pysignals/inspect.py#L105-L115
null
from __future__ import absolute_import import inspect import six def getargspec(func): if six.PY2: return inspect.getargspec(func) sig = inspect.signature(func) args = [ p.name for p in sig.parameters.values() if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD ] vararg...
iancmcc/ouimeaux
ouimeaux/environment.py
Environment.start
python
def start(self): if self._with_discovery: # Start the server to listen to new devices self.upnp.server.set_spawn(2) self.upnp.server.start() if self._with_subscribers: # Start the server to listen to events self.registry.server.set_spawn(2) ...
Start the server(s) necessary to receive information from devices.
train
https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/environment.py#L75-L86
null
class Environment(object): def __init__(self, switch_callback=_NOOP, motion_callback=_NOOP, bridge_callback=_NOOP, maker_callback=_NOOP, with_discovery=True, with_subscribers=True, with_cache=_MARKER, bind=None, config_filename=None): """ Create a WeMo environment....
iancmcc/ouimeaux
ouimeaux/environment.py
Environment.wait
python
def wait(self, timeout=None): try: if timeout: gevent.sleep(timeout) else: while True: gevent.sleep(1000) except (KeyboardInterrupt, SystemExit, Exception): pass
Wait for events.
train
https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/environment.py#L88-L99
null
class Environment(object): def __init__(self, switch_callback=_NOOP, motion_callback=_NOOP, bridge_callback=_NOOP, maker_callback=_NOOP, with_discovery=True, with_subscribers=True, with_cache=_MARKER, bind=None, config_filename=None): """ Create a WeMo environment....
iancmcc/ouimeaux
ouimeaux/environment.py
Environment.discover
python
def discover(self, seconds=2): log.info("Discovering devices") with gevent.Timeout(seconds, StopBroadcasting) as timeout: try: try: while True: self.upnp.broadcast() gevent.sleep(1) except Exc...
Discover devices in the environment. @param seconds: Number of seconds to broadcast requests. @type seconds: int
train
https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/environment.py#L101-L118
[ "def broadcast(self):\n \"\"\"\n Send a multicast M-SEARCH request asking for devices to report in.\n \"\"\"\n log.debug(\"Broadcasting M-SEARCH to %s:%s\", self.mcast_ip, self.mcast_port)\n request = '\\r\\n'.join((\"M-SEARCH * HTTP/1.1\",\n \"HOST:{mcast_ip}:{mcast_port}\"...
class Environment(object): def __init__(self, switch_callback=_NOOP, motion_callback=_NOOP, bridge_callback=_NOOP, maker_callback=_NOOP, with_discovery=True, with_subscribers=True, with_cache=_MARKER, bind=None, config_filename=None): """ Create a WeMo environment....
iancmcc/ouimeaux
ouimeaux/device/__init__.py
Device.get_state
python
def get_state(self, force_update=False): if force_update or self._state is None: return int(self.basicevent.GetBinaryState()['BinaryState']) return self._state
Returns 0 if off and 1 if on.
train
https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/device/__init__.py#L36-L42
null
class Device(object): def __init__(self, url): self._state = None base_url = url.rsplit('/', 1)[0] self.host = urlsplit(url).hostname #self.port = urlsplit(url).port xml = requests_get(url) self._config = deviceParser.parseString(xml.content).device sl = self....
iancmcc/ouimeaux
ouimeaux/pysignals/dispatcher.py
receiver
python
def receiver(signal, **kwargs): def _decorator(func): if isinstance(signal, (list, tuple)): for s in signal: s.connect(func, **kwargs) else: signal.connect(func, **kwargs) return func return _decorator
A decorator for connecting receivers to signals. Used by passing in the signal (or list of signals) and keyword arguments to connect:: @receiver(post_save, sender=MyModel) def signal_receiver(sender, **kwargs): ... @receiver([post_save, post_delete], sender=MyModel) def...
train
https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/pysignals/dispatcher.py#L365-L385
null
from __future__ import absolute_import import sys import threading import weakref import logging from future.builtins import range import six from .inspect import func_accepts_kwargs if six.PY2: from .weakref_backports import WeakMethod else: from weakref import WeakMethod pysignals_debug = False def se...
iancmcc/ouimeaux
ouimeaux/pysignals/dispatcher.py
Signal.send
python
def send(self, sender, **named): responses = [] if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS: return responses for receiver in self._live_receivers(sender): response = receiver(signal=self, sender=sender, **named) responses...
Send signal from sender to all connected receivers. If any receiver raises an error, the error propagates back through send, terminating the dispatch loop. So it's possible that all receivers won't be called if an error is raised. Arguments: sender The send...
train
https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/pysignals/dispatcher.py#L178-L203
null
class Signal(object): """ Base class for all signals Internal attributes: receivers { receiverkey (id) : weakref(receiver) } """ def __init__(self, providing_args=None, use_caching=False): """ Create a new signal. providing_args A list of th...
iancmcc/ouimeaux
ouimeaux/pysignals/dispatcher.py
Signal.send_robust
python
def send_robust(self, sender, **named): responses = [] if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS: return responses # Call each receiver with whatever arguments it can accept. # Return a list of tuple pairs [(receiver, response), ... ]. ...
Send signal from sender to all connected receivers catching errors. Arguments: sender The sender of the signal. Can be any python object (normally one registered with a connect if you actually want something to occur). named ...
train
https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/pysignals/dispatcher.py#L205-L244
null
class Signal(object): """ Base class for all signals Internal attributes: receivers { receiverkey (id) : weakref(receiver) } """ def __init__(self, providing_args=None, use_caching=False): """ Create a new signal. providing_args A list of th...
iancmcc/ouimeaux
ouimeaux/pysignals/dispatcher.py
Signal._live_receivers
python
def _live_receivers(self, sender): receivers = None if self.use_caching and not self._dead_receivers: receivers = self.sender_receivers_cache.get(sender) # We could end up here with NO_RECEIVERS even if we do check this case in # .send() prior to calling _live_receive...
Filter sequence of receivers to get resolved, live receivers. This checks for weak references and resolves them, then returning only live receivers.
train
https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/pysignals/dispatcher.py#L257-L294
[ "def _make_id(target):\n if hasattr(target, '__func__'):\n return (id(target.__self__), id(target.__func__))\n return id(target)\n", "def _clear_dead_receivers(self):\n # Note: caller is assumed to hold self.lock.\n if self._dead_receivers:\n self._dead_receivers = False\n new_rec...
class Signal(object): """ Base class for all signals Internal attributes: receivers { receiverkey (id) : weakref(receiver) } """ def __init__(self, providing_args=None, use_caching=False): """ Create a new signal. providing_args A list of th...
iancmcc/ouimeaux
ouimeaux/pysignals/dispatcher.py
Signal.receive
python
def receive(self, **kwargs): def _decorator(func): self.connect(func, **kwargs) return func return _decorator
A decorator for connecting receivers to this signal. Used by passing in the keyword arguments to connect:: @post_save.receive(sender=MyModel) def signal_receiver(sender, **kwargs): ...
train
https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/pysignals/dispatcher.py#L305-L318
null
class Signal(object): """ Base class for all signals Internal attributes: receivers { receiverkey (id) : weakref(receiver) } """ def __init__(self, providing_args=None, use_caching=False): """ Create a new signal. providing_args A list of th...
iancmcc/ouimeaux
ouimeaux/pysignals/dispatcher.py
StateChange.send
python
def send(self, sender, **named): responses = [] if not self.receivers: return responses sender_id = _make_id(sender) if sender_id not in self.sender_status: self.sender_status[sender_id] = {} if self.sender_status[sender_id] == named: return ...
Send signal from sender to all connected receivers *only if* the signal's contents has changed. If any receiver raises an error, the error propagates back through send, terminating the dispatch loop, so it is quite possible to not have all receivers called if a raises an error. ...
train
https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/pysignals/dispatcher.py#L327-L362
[ "def _make_id(target):\n if hasattr(target, '__func__'):\n return (id(target.__self__), id(target.__func__))\n return id(target)\n", "def _live_receivers(self, sender):\n \"\"\"\n Filter sequence of receivers to get resolved, live receivers.\n\n This checks for weak references and resolves t...
class StateChange( Signal ): def __init__(self, providing_args=None): super(StateChange, self).__init__(providing_args) self.sender_status = {}
iancmcc/ouimeaux
ouimeaux/device/switch.py
Switch.set_state
python
def set_state(self, state): self.basicevent.SetBinaryState(BinaryState=int(state)) self._state = int(state)
Set the state of this device to on or off.
train
https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/device/switch.py#L8-L13
null
class Switch(Device): def off(self): """ Turn this device off. If already off, will return "Error". """ return self.set_state(0) def on(self): """ Turn this device on. If already on, will return "Error". """ return self.set_state(1) def tog...
iancmcc/ouimeaux
ouimeaux/device/switch.py
Switch.blink
python
def blink(self, delay=1): self.toggle() gevent.spawn_later(delay, self.toggle)
Toggle the switch once, then again after a delay (in seconds).
train
https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/device/switch.py#L33-L38
[ "def toggle(self):\n \"\"\"\n Toggle the switch's state.\n \"\"\"\n return self.set_state(not self.get_state())\n" ]
class Switch(Device): def set_state(self, state): """ Set the state of this device to on or off. """ self.basicevent.SetBinaryState(BinaryState=int(state)) self._state = int(state) def off(self): """ Turn this device off. If already off, will return "Err...
iancmcc/ouimeaux
ouimeaux/subscribe.py
SubscriptionRegistry.server
python
def server(self): server = getattr(self, "_server", None) if server is None: server = WSGIServer(('', self.port), self._handle, log=None) self._server = server return server
UDP server to listen for responses.
train
https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/subscribe.py#L95-L103
null
class SubscriptionRegistry(object): def __init__(self): self._devices = {} self._callbacks = defaultdict(list) self.port = randint(8300, 8990) def register(self, device): if not device: log.error("Received an invalid device: %r", device) return l...
iancmcc/ouimeaux
ouimeaux/device/maker.py
Maker.get_state
python
def get_state(self, force_update=False): # The base implementation using GetBinaryState doesn't work for Maker (always returns 0). # So pull the switch state from the atrributes instead if force_update or self._state is None: return(int(self.maker_attribs.get('switchstate',0))) ...
Returns 0 if off and 1 if on.
train
https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/device/maker.py#L11-L19
null
class Maker(Device): def __repr__(self): return '<WeMo Maker "{name}">'.format(name=self.name) def set_state(self, state): """ Set the state of this device to on or off. """ self.basicevent.SetBinaryState(BinaryState=int(state)) self._state = int(state) de...
iancmcc/ouimeaux
ouimeaux/discovery.py
UPnP.server
python
def server(self): server = getattr(self, "_server", None) if server is None: log.debug("Binding datagram server to %s", self.bind) server = DatagramServer(self.bind, self._response_received) self._server = server return server
UDP server to listen for responses.
train
https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/discovery.py#L59-L68
null
class UPnP(object): """ Makes M-SEARCH requests, filters out non-WeMo responses, and dispatches signals with the results. """ def __init__(self, mcast_ip='239.255.255.250', mcast_port=1900, bind=None): if bind is None: host = get_ip_address() if host.startswith('127.'...
iancmcc/ouimeaux
ouimeaux/discovery.py
UPnP.broadcast
python
def broadcast(self): log.debug("Broadcasting M-SEARCH to %s:%s", self.mcast_ip, self.mcast_port) request = '\r\n'.join(("M-SEARCH * HTTP/1.1", "HOST:{mcast_ip}:{mcast_port}", "ST:upnp:rootdevice", "MX:2", ...
Send a multicast M-SEARCH request asking for devices to report in.
train
https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/discovery.py#L70-L81
null
class UPnP(object): """ Makes M-SEARCH requests, filters out non-WeMo responses, and dispatches signals with the results. """ def __init__(self, mcast_ip='239.255.255.250', mcast_port=1900, bind=None): if bind is None: host = get_ip_address() if host.startswith('127.'...
iancmcc/ouimeaux
ouimeaux/utils.py
retry_with_delay
python
def retry_with_delay(f, delay=60): @wraps(f) def inner(*args, **kwargs): kwargs['timeout'] = 5 remaining = get_retries() + 1 while remaining: remaining -= 1 try: return f(*args, **kwargs) except (requests.ConnectionError, requests.Timeo...
Retry the wrapped requests.request function in case of ConnectionError. Optionally limit the number of retries or set the delay between retries.
train
https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/utils.py#L68-L85
null
from functools import wraps import re import socket import struct import time import gevent import requests def tz_hours(): delta = time.localtime().tm_hour - time.gmtime().tm_hour sign = '-' if delta < 0 else '' return "%s%02d.00" % (sign, abs(delta)) def is_dst(): return 1 if time.localtime().tm_...
r4fek/django-cassandra-engine
django_cassandra_engine/base/introspection.py
CassandraDatabaseIntrospection._discover_models
python
def _discover_models(self): apps = get_installed_apps() connection = self.connection.connection.alias keyspace = self.connection.connection.keyspace for app in apps: self._cql_models[app.__name__] = get_cql_models( app, connection=connection, keyspace=keyspa...
Return a dict containing a list of cassandra.cqlengine.Model classes within installed App.
train
https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/base/introspection.py#L20-L32
null
class CassandraDatabaseIntrospection(BaseDatabaseIntrospection): def __init__(self, *args, **kwargs): super(CassandraDatabaseIntrospection, self).__init__(*args, **kwargs) self._cql_models = {} self._models_discovered = False @property def cql_models(self): if not self._m...
r4fek/django-cassandra-engine
django_cassandra_engine/base/introspection.py
CassandraDatabaseIntrospection.django_table_names
python
def django_table_names(self, only_existing=False, **kwargs): all_models = list(chain.from_iterable(self.cql_models.values())) tables = [model.column_family_name(include_keyspace=False) for model in all_models] return tables
Returns a list of all table names that have associated cqlengine models and are present in settings.INSTALLED_APPS.
train
https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/base/introspection.py#L41-L51
null
class CassandraDatabaseIntrospection(BaseDatabaseIntrospection): def __init__(self, *args, **kwargs): super(CassandraDatabaseIntrospection, self).__init__(*args, **kwargs) self._cql_models = {} self._models_discovered = False def _discover_models(self): """ Return a di...
r4fek/django-cassandra-engine
django_cassandra_engine/base/introspection.py
CassandraDatabaseIntrospection.table_names
python
def table_names(self, cursor=None, **kwargs): # Avoid migration code being executed if cursor: return [] connection = self.connection.connection keyspace_name = connection.keyspace if not connection.cluster.schema_metadata_enabled and \ keyspace_name ...
Returns all table names in current keyspace
train
https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/base/introspection.py#L53-L68
null
class CassandraDatabaseIntrospection(BaseDatabaseIntrospection): def __init__(self, *args, **kwargs): super(CassandraDatabaseIntrospection, self).__init__(*args, **kwargs) self._cql_models = {} self._models_discovered = False def _discover_models(self): """ Return a di...
r4fek/django-cassandra-engine
django_cassandra_engine/base/creation.py
CassandraDatabaseCreation.set_models_keyspace
python
def set_models_keyspace(self, keyspace): for models in self.connection.introspection.cql_models.values(): for model in models: model.__keyspace__ = keyspace
Set keyspace for all connection models
train
https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/base/creation.py#L90-L95
null
class CassandraDatabaseCreation(BaseDatabaseCreation): def create_test_db(self, verbosity=1, autoclobber=False, **kwargs): """ Creates a test database, prompting the user for confirmation if the database already exists. Returns the name of the test database created. """ # Do...
r4fek/django-cassandra-engine
django_cassandra_engine/sessions/backends/db.py
SessionStore.create_model_instance
python
def create_model_instance(self, data): return self.model( session_key=self._get_or_create_session_key(), session_data=self.encode(data), expire_date=self.get_expiry_date(), )
Return a new instance of the session model object, which represents the current session state. Intended to be used for saving the session data to the database. :param data:
train
https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/sessions/backends/db.py#L31-L42
null
class SessionStore(DjangoSessionStore): @classmethod def get_model_class(cls): """ Avoid circular import """ from django_cassandra_engine.sessions.models import Session return Session @cached_property def model(self): return self.get_model_class() ...
r4fek/django-cassandra-engine
django_cassandra_engine/sessions/backends/db.py
SessionStore.save
python
def save(self, must_create=False): if self.session_key is None: return self.create() data = self._get_session(no_load=must_create) obj = self.create_model_instance(data) obj.save()
Saves the current session data to the database. If 'must_create' is True, a database error will be raised if the saving operation doesn't create a *new* entry (as opposed to possibly updating an existing entry). :param must_create:
train
https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/sessions/backends/db.py#L66-L79
null
class SessionStore(DjangoSessionStore): @classmethod def get_model_class(cls): """ Avoid circular import """ from django_cassandra_engine.sessions.models import Session return Session @cached_property def model(self): return self.get_model_class() d...
r4fek/django-cassandra-engine
django_cassandra_engine/rest/serializers.py
DjangoCassandraModelSerializer.get_field_kwargs
python
def get_field_kwargs(self, field_name, model_field): kwargs = {} validator_kwarg = list(model_field.validators) # The following will only be used by ModelField classes. # Gets removed for everything else. kwargs['model_field'] = model_field if model_field.verbose_name a...
Creates a default instance of a basic non-relational field.
train
https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/rest/serializers.py#L42-L215
null
class DjangoCassandraModelSerializer(serializers.ModelSerializer): serializer_field_mapping = { columns.Text: serializers.CharField, columns.UUID: serializers.CharField, columns.Integer: serializers.IntegerField, columns.TinyInt: serializers.IntegerField, columns.SmallInt: se...
r4fek/django-cassandra-engine
django_cassandra_engine/management/commands/sync_cassandra.py
Command._import_management
python
def _import_management(): from importlib import import_module for app_name in settings.INSTALLED_APPS: try: import_module('.management', app_name) except SystemError: # We get SystemError if INSTALLED_APPS contains the # name of a...
Import the 'management' module within each installed app, to register dispatcher events.
train
https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/management/commands/sync_cassandra.py#L23-L51
null
class Command(BaseCommand): help = 'Sync Cassandra database(s)' def add_arguments(self, parser): parser.add_argument( '--database', action='store', dest='database', default=None, help='Nominates a database to synchronize.', ) @sta...
r4fek/django-cassandra-engine
django_cassandra_engine/utils.py
get_installed_apps
python
def get_installed_apps(): if django.VERSION >= (1, 7): from django.apps import apps return [a.models_module for a in apps.get_app_configs() if a.models_module is not None] else: from django.db import models return models.get_apps()
Return list of all installed apps
train
https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/utils.py#L57-L67
null
import inspect import django from django.conf import settings from django.db import DEFAULT_DB_ALIAS from .compat import cqlengine class CursorWrapper(object): """ Simple CursorWrapper implementation based on django.db.utils.CursorWrapper """ def __init__(self, cursor, db): self.cursor = cu...
r4fek/django-cassandra-engine
django_cassandra_engine/utils.py
get_cql_models
python
def get_cql_models(app, connection=None, keyspace=None): from .models import DjangoCassandraModel models = [] single_cassandra_connection = len(list(get_cassandra_connections())) == 1 is_default_connection = connection == DEFAULT_DB_ALIAS or \ single_cassandra_connection for name, obj in in...
:param app: django models module :param connection: connection name :param keyspace: keyspace :return: list of all cassandra.cqlengine.Model within app that should be synced to keyspace.
train
https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/utils.py#L70-L98
[ "def get_cassandra_connections():\n \"\"\"\n :return: List of tuples (db_alias, connection) for all cassandra\n connections in DATABASES dict.\n \"\"\"\n\n from django.db import connections\n for alias in connections:\n engine = connections[alias].settings_dict.get('ENGINE', '')\n if...
import inspect import django from django.conf import settings from django.db import DEFAULT_DB_ALIAS from .compat import cqlengine class CursorWrapper(object): """ Simple CursorWrapper implementation based on django.db.utils.CursorWrapper """ def __init__(self, cursor, db): self.cursor = cu...
r4fek/django-cassandra-engine
django_cassandra_engine/utils.py
get_cassandra_connections
python
def get_cassandra_connections(): from django.db import connections for alias in connections: engine = connections[alias].settings_dict.get('ENGINE', '') if engine == 'django_cassandra_engine': yield alias, connections[alias]
:return: List of tuples (db_alias, connection) for all cassandra connections in DATABASES dict.
train
https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/utils.py#L101-L111
null
import inspect import django from django.conf import settings from django.db import DEFAULT_DB_ALIAS from .compat import cqlengine class CursorWrapper(object): """ Simple CursorWrapper implementation based on django.db.utils.CursorWrapper """ def __init__(self, cursor, db): self.cursor = cu...
r4fek/django-cassandra-engine
django_cassandra_engine/utils.py
get_default_cassandra_connection
python
def get_default_cassandra_connection(): for alias, conn in get_cassandra_connections(): if conn.connection.default: return alias, conn return list(get_cassandra_connections())[0]
Return first default cassandra connection :return:
train
https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/utils.py#L114-L123
[ "def get_cassandra_connections():\n \"\"\"\n :return: List of tuples (db_alias, connection) for all cassandra\n connections in DATABASES dict.\n \"\"\"\n\n from django.db import connections\n for alias in connections:\n engine = connections[alias].settings_dict.get('ENGINE', '')\n if...
import inspect import django from django.conf import settings from django.db import DEFAULT_DB_ALIAS from .compat import cqlengine class CursorWrapper(object): """ Simple CursorWrapper implementation based on django.db.utils.CursorWrapper """ def __init__(self, cursor, db): self.cursor = cu...
r4fek/django-cassandra-engine
django_cassandra_engine/utils.py
get_cassandra_connection
python
def get_cassandra_connection(alias=None, name=None): for _alias, connection in get_cassandra_connections(): if alias is not None: if alias == _alias: return connection elif name is not None: if name == connection.settings_dict['NAME']: return ...
:return: cassandra connection matching alias or name or just first found.
train
https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/utils.py#L126-L139
[ "def get_cassandra_connections():\n \"\"\"\n :return: List of tuples (db_alias, connection) for all cassandra\n connections in DATABASES dict.\n \"\"\"\n\n from django.db import connections\n for alias in connections:\n engine = connections[alias].settings_dict.get('ENGINE', '')\n if...
import inspect import django from django.conf import settings from django.db import DEFAULT_DB_ALIAS from .compat import cqlengine class CursorWrapper(object): """ Simple CursorWrapper implementation based on django.db.utils.CursorWrapper """ def __init__(self, cursor, db): self.cursor = cu...
r4fek/django-cassandra-engine
django_cassandra_engine/management/commands/makemigrations.py
Command.handle
python
def handle(self, *args, **options): self._change_cassandra_engine_name('django.db.backends.dummy') try: super(Command, self).handle(*args, **options) finally: self._change_cassandra_engine_name('django_cassandra_engine')
Pretend django_cassandra_engine to be dummy database backend with no support for migrations.
train
https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/management/commands/makemigrations.py#L15-L24
null
class Command(MakeMigrationsCommand): @staticmethod def _change_cassandra_engine_name(name): for alias, _ in get_cassandra_connections(): connections[alias].settings_dict['ENGINE'] = name
r4fek/django-cassandra-engine
django_cassandra_engine/base/operations.py
CassandraDatabaseOperations.sql_flush
python
def sql_flush(self, style, tables, sequences, allow_cascade=False): for table in tables: qs = "TRUNCATE {}".format(table) self.connection.connection.execute(qs) return []
Truncate all existing tables in current keyspace. :returns: an empty list
train
https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/base/operations.py#L36-L47
null
class CassandraDatabaseOperations(BaseDatabaseOperations): def pk_default_value(self): """ Returns None, to be interpreted by back-ends as a request to generate a new key for an "inserted" object. """ return None def quote_name(self, name): """ Does not ...
r4fek/django-cassandra-engine
django_cassandra_engine/models/__init__.py
convert_pk_field_names_to_real
python
def convert_pk_field_names_to_real(model, field_names): pk_field_names = tuple(f.name for f in model._get_primary_key_columns()) def append_field(field_name): if field_name not in real_field_names: real_field_names.append(field_name) real_field_names = [] for name in field_names: ...
Convert field names including 'pk' to the real field names: >>> convert_pk_field_names_to_real(['pk', 'another_field']) ['real_pk_field', 'another_field']
train
https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/models/__init__.py#L519-L542
[ "def append_field(field_name):\n if field_name not in real_field_names:\n real_field_names.append(field_name)\n" ]
import logging import inspect import copy import warnings from operator import attrgetter import collections from functools import partial from itertools import chain import six from django.conf import settings from django.apps import apps from django.core import validators from django.db.models.base import ModelBase ...
r4fek/django-cassandra-engine
django_cassandra_engine/models/__init__.py
DjangoCassandraOptions.add_field
python
def add_field(self, field, **kwargs): getattr(self, self._private_fields_name).append(field) self._expire_cache(reverse=True) self._expire_cache(reverse=False)
Add each field as a private field.
train
https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/models/__init__.py#L80-L84
null
class DjangoCassandraOptions(options.Options): default_field_error_messages = { 'invalid_choice': _('Value %(value)r is not a valid choice.'), 'null': _('This field cannot be null.'), 'blank': _('This field cannot be blank.'), 'unique': _('%(model_name)s with this %(field_label)s ' ...
r4fek/django-cassandra-engine
django_cassandra_engine/models/__init__.py
DjangoCassandraOptions._give_columns_django_field_attributes
python
def _give_columns_django_field_attributes(self): methods_to_add = ( django_field_methods.value_from_object, django_field_methods.value_to_string, django_field_methods.get_attname, django_field_methods.get_cache_name, django_field_methods.pre_save, ...
Add Django Field attributes to each cqlengine.Column instance. So that the Django Options class may interact with it as if it were a Django Field.
train
https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/models/__init__.py#L130-L179
[ "def _set_column_django_attributes(self, cql_column, name):\n allow_null = (\n (not cql_column.required and\n not cql_column.is_primary_key and\n not cql_column.partition_key) or cql_column.has_default and not cql_column.required\n )\n cql_column.error_messages = self.default_field_e...
class DjangoCassandraOptions(options.Options): default_field_error_messages = { 'invalid_choice': _('Value %(value)r is not a valid choice.'), 'null': _('This field cannot be null.'), 'blank': _('This field cannot be blank.'), 'unique': _('%(model_name)s with this %(field_label)s ' ...
r4fek/django-cassandra-engine
django_cassandra_engine/models/__init__.py
DjangoCassandraModel._get_column
python
def _get_column(cls, name): if name == 'pk': return cls._meta.get_field(cls._meta.pk.name) return cls._columns[name]
Based on cqlengine.models.BaseModel._get_column. But to work with 'pk'
train
https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/models/__init__.py#L833-L841
null
class DjangoCassandraModel( six.with_metaclass(DjangoCassandraModelMetaClass, BaseModel) ): __queryset__ = DjangoCassandraQuerySet __abstract__ = True __table_name__ = None __table_name_case_sensitive__ = False __keyspace__ = None __options__ = None __discriminator_value__ = None __...
fabric/fabric
fabric/transfer.py
Transfer.get
python
def get(self, remote, local=None, preserve_mode=True): # TODO: how does this API change if we want to implement # remote-to-remote file transfer? (Is that even realistic?) # TODO: handle v1's string interpolation bits, especially the default # one, or at least think about how that would ...
Download a file from the current connection to the local filesystem. :param str remote: Remote file to download. May be absolute, or relative to the remote working directory. .. note:: Most SFTP servers set the remote working directory to the ...
train
https://github.com/fabric/fabric/blob/e9939d68b734935f0c98d98817912ad7c698238f/fabric/transfer.py#L41-L145
null
class Transfer(object): """ `.Connection`-wrapping class responsible for managing file upload/download. .. versionadded:: 2.0 """ # TODO: SFTP clear default, but how to do SCP? subclass? init kwarg? def __init__(self, connection): self.connection = connection @property def sf...
fabric/fabric
fabric/transfer.py
Transfer.put
python
def put(self, local, remote=None, preserve_mode=True): if not local: raise ValueError("Local path must not be empty!") is_file_like = hasattr(local, "write") and callable(local.write) # Massage remote path orig_remote = remote if is_file_like: local_base...
Upload a file from the local filesystem to the current connection. :param local: Local path of file to upload, or a file-like object. **If a string is given**, it should be a path to a local (regular) file (not a directory). .. note:: When deali...
train
https://github.com/fabric/fabric/blob/e9939d68b734935f0c98d98817912ad7c698238f/fabric/transfer.py#L147-L283
null
class Transfer(object): """ `.Connection`-wrapping class responsible for managing file upload/download. .. versionadded:: 2.0 """ # TODO: SFTP clear default, but how to do SCP? subclass? init kwarg? def __init__(self, connection): self.connection = connection @property def sf...
fabric/fabric
fabric/config.py
Config.load_ssh_config
python
def load_ssh_config(self): # Update the runtime SSH config path (assumes enough regular config # levels have been loaded that anyone wanting to transmit this info # from a 'vanilla' Invoke config, has gotten it set.) if self.ssh_config_path: self._runtime_ssh_path = self.ssh_...
Load SSH config file(s) from disk. Also (beforehand) ensures that Invoke-level config re: runtime SSH config file paths, is accounted for. .. versionadded:: 2.0
train
https://github.com/fabric/fabric/blob/e9939d68b734935f0c98d98817912ad7c698238f/fabric/config.py#L110-L127
null
class Config(InvokeConfig): """ An `invoke.config.Config` subclass with extra Fabric-related behavior. This class behaves like `invoke.config.Config` in every way, with the following exceptions: - its `global_defaults` staticmethod has been extended to add/modify some default settings (see i...
fabric/fabric
fabric/config.py
Config._load_ssh_files
python
def _load_ssh_files(self): # TODO: does this want to more closely ape the behavior of # InvokeConfig.load_files? re: having a _found attribute for each that # determines whether to load or skip if self._runtime_ssh_path is not None: path = self._runtime_ssh_path #...
Trigger loading of configured SSH config file paths. Expects that ``base_ssh_config`` has already been set to an `~paramiko.config.SSHConfig` object. :returns: ``None``.
train
https://github.com/fabric/fabric/blob/e9939d68b734935f0c98d98817912ad7c698238f/fabric/config.py#L168-L189
null
class Config(InvokeConfig): """ An `invoke.config.Config` subclass with extra Fabric-related behavior. This class behaves like `invoke.config.Config` in every way, with the following exceptions: - its `global_defaults` staticmethod has been extended to add/modify some default settings (see i...
fabric/fabric
fabric/config.py
Config._load_ssh_file
python
def _load_ssh_file(self, path): if os.path.isfile(path): old_rules = len(self.base_ssh_config._config) with open(path) as fd: self.base_ssh_config.parse(fd) new_rules = len(self.base_ssh_config._config) msg = "Loaded {} new ssh_config rules from {!...
Attempt to open and parse an SSH config file at ``path``. Does nothing if ``path`` is not a path to a valid file. :returns: ``None``.
train
https://github.com/fabric/fabric/blob/e9939d68b734935f0c98d98817912ad7c698238f/fabric/config.py#L191-L207
null
class Config(InvokeConfig): """ An `invoke.config.Config` subclass with extra Fabric-related behavior. This class behaves like `invoke.config.Config` in every way, with the following exceptions: - its `global_defaults` staticmethod has been extended to add/modify some default settings (see i...
fabric/fabric
fabric/config.py
Config.global_defaults
python
def global_defaults(): # TODO: hrm should the run-related things actually be derived from the # runner_class? E.g. Local defines local stuff, Remote defines remote # stuff? Doesn't help with the final config tree tho... # TODO: as to that, this is a core problem, Fabric wants split ...
Default configuration values and behavior toggles. Fabric only extends this method in order to make minor adjustments and additions to Invoke's `~invoke.config.Config.global_defaults`; see its documentation for the base values, such as the config subtrees controlling behavior of ``run``...
train
https://github.com/fabric/fabric/blob/e9939d68b734935f0c98d98817912ad7c698238f/fabric/config.py#L210-L253
[ "def get_local_user():\n \"\"\"\n Return the local executing username, or ``None`` if one can't be found.\n\n .. versionadded:: 2.0\n \"\"\"\n # TODO: I don't understand why these lines were added outside the\n # try/except, since presumably it means the attempt at catching ImportError\n # woul...
class Config(InvokeConfig): """ An `invoke.config.Config` subclass with extra Fabric-related behavior. This class behaves like `invoke.config.Config` in every way, with the following exceptions: - its `global_defaults` staticmethod has been extended to add/modify some default settings (see i...
fabric/fabric
fabric/tunnels.py
Tunnel.read_and_write
python
def read_and_write(self, reader, writer, chunk_size): data = reader.recv(chunk_size) if len(data) == 0: return True writer.sendall(data)
Read ``chunk_size`` from ``reader``, writing result to ``writer``. Returns ``None`` if successful, or ``True`` if the read was empty. .. versionadded:: 2.0
train
https://github.com/fabric/fabric/blob/e9939d68b734935f0c98d98817912ad7c698238f/fabric/tunnels.py#L146-L157
null
class Tunnel(ExceptionHandlingThread): """ Bidirectionally forward data between an SSH channel and local socket. .. versionadded:: 2.0 """ def __init__(self, channel, sock, finished): self.channel = channel self.sock = sock self.finished = finished self.socket_chunk...
fabric/fabric
fabric/util.py
get_local_user
python
def get_local_user(): # TODO: I don't understand why these lines were added outside the # try/except, since presumably it means the attempt at catching ImportError # wouldn't work. However, that's how the contributing user committed it. # Need an older Windows box to test it out, most likely. import...
Return the local executing username, or ``None`` if one can't be found. .. versionadded:: 2.0
train
https://github.com/fabric/fabric/blob/e9939d68b734935f0c98d98817912ad7c698238f/fabric/util.py#L16-L45
null
import logging import sys # Ape the half-assed logging junk from Invoke, but ensuring the logger reflects # our name, not theirs. (Assume most contexts will rely on Invoke itself to # literally enable/disable logging, for now.) log = logging.getLogger("fabric") for x in ("debug",): globals()[x] = getattr(log, x) ...
fabric/fabric
fabric/executor.py
FabExecutor.parameterize
python
def parameterize(self, call, host): debug("Parameterizing {!r} for host {!r}".format(call, host)) # Generate a custom ConnectionCall that knows how to yield a Connection # in its make_context(), specifically one to the host requested here. clone = call.clone(into=ConnectionCall) ...
Parameterize a Call with its Context set to a per-host Config.
train
https://github.com/fabric/fabric/blob/e9939d68b734935f0c98d98817912ad7c698238f/fabric/executor.py#L58-L68
null
class FabExecutor(Executor): def expand_calls(self, calls, apply_hosts=True): # Generate new call list with per-host variants & Connections inserted ret = [] # TODO: mesh well with Invoke list-type args helper (inv #132) hosts = [] host_str = self.core[0].args.hosts.value ...
fabric/fabric
integration/connection.py
Connection_.mixed_use_of_local_and_run
python
def mixed_use_of_local_and_run(self): cxn = Connection("localhost") result = cxn.local("echo foo", hide=True) assert result.stdout == "foo\n" assert not cxn.is_connected # meh way of proving it didn't use SSH yet result = cxn.run("echo foo", hide=True) assert cxn.is_conn...
Run command truly locally, and over SSH via localhost
train
https://github.com/fabric/fabric/blob/e9939d68b734935f0c98d98817912ad7c698238f/integration/connection.py#L67-L77
null
class Connection_: class ssh_connections: def open_method_generates_real_connection(self): c = Connection("localhost") c.open() assert c.client.get_transport().active is True assert c.is_connected is True return c def close_method_closes_c...
fabric/fabric
fabric/connection.py
Connection.open
python
def open(self): # Short-circuit if self.is_connected: return err = "Refusing to be ambiguous: connect() kwarg '{}' was given both via regular arg and via connect_kwargs!" # noqa # These may not be given, period for key in """ hostname port ...
Initiate an SSH connection to the host/port this object is bound to. This may include activating the configured gateway connection, if one is set. Also saves a handle to the now-set Transport object for easier access. Various connect-time settings (and/or their corresponding :ref:`SSH...
train
https://github.com/fabric/fabric/blob/e9939d68b734935f0c98d98817912ad7c698238f/fabric/connection.py#L475-L525
null
class Connection(Context): """ A connection to an SSH daemon, with methods for commands and file transfer. **Basics** This class inherits from Invoke's `~invoke.context.Context`, as it is a context within which commands, tasks etc can operate. It also encapsulates a Paramiko `~paramiko.client....
fabric/fabric
fabric/connection.py
Connection.open_gateway
python
def open_gateway(self): # ProxyCommand is faster to set up, so do it first. if isinstance(self.gateway, string_types): # Leverage a dummy SSHConfig to ensure %h/%p/etc are parsed. # TODO: use real SSH config once loading one properly is # implemented. ssh_...
Obtain a socket-like object from `gateway`. :returns: A ``direct-tcpip`` `paramiko.channel.Channel`, if `gateway` was a `.Connection`; or a `~paramiko.proxy.ProxyCommand`, if `gateway` was a string. .. versionadded:: 2.0
train
https://github.com/fabric/fabric/blob/e9939d68b734935f0c98d98817912ad7c698238f/fabric/connection.py#L527-L565
null
class Connection(Context): """ A connection to an SSH daemon, with methods for commands and file transfer. **Basics** This class inherits from Invoke's `~invoke.context.Context`, as it is a context within which commands, tasks etc can operate. It also encapsulates a Paramiko `~paramiko.client....
fabric/fabric
fabric/connection.py
Connection.close
python
def close(self): if self.is_connected: self.client.close() if self.forward_agent and self._agent_handler is not None: self._agent_handler.close()
Terminate the network connection to the remote end, if open. If no connection is open, this method does nothing. .. versionadded:: 2.0
train
https://github.com/fabric/fabric/blob/e9939d68b734935f0c98d98817912ad7c698238f/fabric/connection.py#L567-L578
null
class Connection(Context): """ A connection to an SSH daemon, with methods for commands and file transfer. **Basics** This class inherits from Invoke's `~invoke.context.Context`, as it is a context within which commands, tasks etc can operate. It also encapsulates a Paramiko `~paramiko.client....
fabric/fabric
fabric/connection.py
Connection.run
python
def run(self, command, **kwargs): runner = self.config.runners.remote(self) return self._run(runner, command, **kwargs)
Execute a shell command on the remote end of this connection. This method wraps an SSH-capable implementation of `invoke.runners.Runner.run`; see its documentation for details. .. warning:: There are a few spots where Fabric departs from Invoke's default settings/behavi...
train
https://github.com/fabric/fabric/blob/e9939d68b734935f0c98d98817912ad7c698238f/fabric/connection.py#L594-L609
null
class Connection(Context): """ A connection to an SSH daemon, with methods for commands and file transfer. **Basics** This class inherits from Invoke's `~invoke.context.Context`, as it is a context within which commands, tasks etc can operate. It also encapsulates a Paramiko `~paramiko.client....
fabric/fabric
fabric/connection.py
Connection.sudo
python
def sudo(self, command, **kwargs): runner = self.config.runners.remote(self) return self._sudo(runner, command, **kwargs)
Execute a shell command, via ``sudo``, on the remote end. This method is identical to `invoke.context.Context.sudo` in every way, except in that -- like `run` -- it honors per-host/per-connection configuration overrides in addition to the generic/global ones. Thus, for example, per-host...
train
https://github.com/fabric/fabric/blob/e9939d68b734935f0c98d98817912ad7c698238f/fabric/connection.py#L612-L624
null
class Connection(Context): """ A connection to an SSH daemon, with methods for commands and file transfer. **Basics** This class inherits from Invoke's `~invoke.context.Context`, as it is a context within which commands, tasks etc can operate. It also encapsulates a Paramiko `~paramiko.client....