signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def set_value(self, name, obj, value, context=None): | raise NotImplemented()<EOL> | Set given value of field `name` to object `obj`.
:params str name: Field name.
:params obj: Object to get field value from.
:params value: Field value to set. | f1425:c17:m2 |
def load(self, name, data, context=None): | return self.field_type.load(data.get(name, MISSING), context=context)<EOL> | Deserialize data from primitive types. Raises
:exc:`~lollipop.errors.ValidationError` if data is invalid.
:param str name: Name of attribute to deserialize.
:param data: Raw data to get value to deserialize from.
:param kwargs: Same keyword arguments as for :meth:`Type.load`.
:r... | f1425:c17:m3 |
def load_into(self, obj, name, data, inplace=True, context=None): | if obj is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>value = data.get(name, MISSING)<EOL>if value is MISSING:<EOL><INDENT>return<EOL><DEDENT>target = self.get_value(name, obj, context=context)<EOL>if target is not None and target is not MISSINGand hasattr(self.field_type, '<STR_LIT>'):<EOL><INDENT>retu... | Deserialize data from primitive types updating existing object.
Raises :exc:`~lollipop.errors.ValidationError` if data is invalid.
:param obj: Object to update with deserialized data.
:param str name: Name of attribute to deserialize.
:param data: Raw data to get value to deserialize fr... | f1425:c17:m4 |
def dump(self, name, obj, context=None): | value = self.get_value(name, obj, context=context)<EOL>return self.field_type.dump(value, context=context)<EOL> | Serialize data to primitive types. Raises
:exc:`~lollipop.errors.ValidationError` if data is invalid.
:param str name: Name of attribute to serialize.
:param obj: Application object to extract serialized value from.
:returns: Serialized data.
:raises: :exc:`~lollipop.errors.Vali... | f1425:c17:m5 |
def load_into(self, obj, data, inplace=True, *args, **kwargs): | if obj is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if data is MISSING:<EOL><INDENT>return<EOL><DEDENT>if data is None:<EOL><INDENT>self._fail('<STR_LIT>')<EOL><DEDENT>if not is_mapping(data):<EOL><INDENT>self._fail('<STR_LIT>', data=data)<EOL><DEDENT>errors_builder = ValidationErrorBuilder()<EOL>data... | Load data and update existing object.
:param obj: Object to update with deserialized data.
:param data: Raw data to get value to deserialize from.
:param bool inplace: If True update data inplace;
otherwise - create new data.
:param kwargs: Same keyword arguments as for :met... | f1425:c22:m5 |
def validate_for(self, obj, data, *args, **kwargs): | try:<EOL><INDENT>self.load_into(obj, data, inplace=False, *args, **kwargs)<EOL>return None<EOL><DEDENT>except ValidationError as ve:<EOL><INDENT>return ve.messages<EOL><DEDENT> | Takes target object and serialized data, tries to update that object
with data and validate result. Returns validation errors or None.
Object is not updated.
:param obj: Object to check data validity against. In case the data is
partial object is used to get the rest of data from.
... | f1425:c22:m6 |
def identity(value): | return value<EOL> | Function that returns its argument. | f1427:m0 |
def constant(value): | def func(*args, **kwargs):<EOL><INDENT>return value<EOL><DEDENT>return func<EOL> | Returns function that takes any arguments and always returns given value. | f1427:m1 |
def is_sequence(value): | return isinstance(value, collections.Sequence)<EOL> | Returns True if value supports list interface; False - otherwise | f1427:m2 |
def is_mapping(value): | return isinstance(value, collections.Mapping)<EOL> | Returns True if value supports dict interface; False - otherwise | f1427:m3 |
def make_context_aware(func, numargs): | try:<EOL><INDENT>if inspect.ismethod(func):<EOL><INDENT>arg_count = len(inspect.getargspec(func).args) - <NUM_LIT:1><EOL><DEDENT>elif inspect.isfunction(func):<EOL><INDENT>arg_count = len(inspect.getargspec(func).args)<EOL><DEDENT>elif inspect.isclass(func):<EOL><INDENT>arg_count = len(inspect.getargspec(func.__init__)... | Check if given function has no more arguments than given. If so, wrap it
into another function that takes extra argument and drops it.
Used to support user providing callback functions that are not context aware. | f1427:m4 |
def call_with_context(func, context, *args): | return make_context_aware(func, len(args))(*args + (context,))<EOL> | Check if given function has more arguments than given. Call it with context
as last argument or without it. | f1427:m5 |
def to_snake_case(s): | return re.sub('<STR_LIT>', lambda m: m.group(<NUM_LIT:1>) + '<STR_LIT:_>' + m.group(<NUM_LIT:2>).lower(), s)<EOL> | Converts camel-case identifiers to snake-case. | f1427:m6 |
def to_camel_case(s): | return re.sub('<STR_LIT>', lambda m: m.group(<NUM_LIT:1>).upper(), s)<EOL> | Converts snake-case identifiers to camel-case. | f1427:m7 |
def fit(self, X, y, verbosity=<NUM_LIT:0>): | self.classes = list(set(y))<EOL>n_points = len(y)<EOL>if len(X) != n_points:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>if not self._state_machine:<EOL><INDENT>self._state_machine = DefaultStateMachine(self.classes)<EOL><DEDENT>self.parameters = self._initialize_parameters(self._state_machine, X[<NUM_LIT:0>].... | Fit the model according to the given training data.
Parameters
----------
X : List of ndarrays, one for each training example.
Each training example's shape is (string1_len, string2_len, n_features), where
string1_len and string2_len are the length of the two training st... | f1432:c0:m1 |
def predict_proba(self, X): | parameters = np.ascontiguousarray(self.parameters.T)<EOL>predictions = [_Model(self._state_machine, x).predict(parameters, self.viterbi)<EOL>for x in X]<EOL>predictions = np.array([[probability<EOL>for _, probability<EOL>in sorted(prediction.items())]<EOL>for prediction in predictions])<EOL>return predictions<EOL> | Probability estimates.
The returned estimates for all classes are ordered by the
label of classes.
Parameters
----------
X : List of ndarrays, one for each training example.
Each training example's shape is (string1_len, string2_len, n_features, where
st... | f1432:c0:m2 |
def predict(self, X): | return [self.classes[prediction.argmax()] for prediction in self.predict_proba(X)]<EOL> | Predict the class for X.
The predicted class for each sample in X is returned.
Parameters
----------
X : List of ndarrays, one for each training example.
Each training example's shape is (string1_len,
string2_len, n_features), where string1_len and
s... | f1432:c0:m3 |
@staticmethod<EOL><INDENT>def _initialize_parameters(state_machine, n_features):<DEDENT> | return np.zeros((state_machine.n_states <EOL>+ state_machine.n_transitions,<EOL>n_features))<EOL> | Helper to create initial parameter vector with the correct shape. | f1432:c0:m4 |
def get_params(self, deep=True): | return {'<STR_LIT>': self.l2_regularization,<EOL>'<STR_LIT>': self._optimizer,<EOL>'<STR_LIT>': self._optimizer_kwargs}<EOL> | Get parameters for this estimator.
Parameters
----------
deep: boolean, optional
If True, will return the parameters for this estimator and
contained subobjects that are estimators.
Returns
-------
params : mapping of string to any
Pa... | f1432:c0:m5 |
def set_params(self, l2_regularization=<NUM_LIT:0.0>, optimizer=None, optimizer_kwargs=None): | self.l2_regularization = l2_regularization<EOL>self._optimizer = optimizer<EOL>self._optimizer_kwargs = optimizer_kwargs<EOL>return self<EOL> | Set the parameters of this estimator.
Returns
-------
self | f1432:c0:m6 |
def forward_backward(self, parameters): | <EOL>if isinstance(self.sparse_x, str) and self.sparse_x == '<STR_LIT>':<EOL><INDENT>if (self.x == <NUM_LIT:0>).sum() * <NUM_LIT:1.0> / self.x.size > <NUM_LIT>:<EOL><INDENT>self.sparse_x = self._construct_sparse_features(self.x)<EOL><DEDENT>else:<EOL><INDENT>self.sparse_x = '<STR_LIT>'<EOL><DEDENT><DEDENT>I, J, K = sel... | Run the forward backward algorithm with the given parameters. | f1432:c1:m1 |
def predict(self, parameters, viterbi): | x_dot_parameters = np.einsum('<STR_LIT>', self.x, parameters)<EOL>if not viterbi:<EOL><INDENT>alpha = forward_predict(self._lattice, x_dot_parameters,<EOL>self.state_machine.n_states)<EOL><DEDENT>else:<EOL><INDENT>alpha = forward_max_predict(self._lattice, x_dot_parameters,<EOL>self.state_machine.n_states)<EOL><DEDENT>... | Run forward algorithm to find the predicted distribution over classes. | f1432:c1:m2 |
def _forward(self, x_dot_parameters): | return forward(self._lattice, x_dot_parameters, <EOL>self.state_machine.n_states)<EOL> | Helper to calculate the forward weights. | f1432:c1:m3 |
def _backward(self, x_dot_parameters): | I, J, _ = self.x.shape<EOL>return backward(self._lattice, x_dot_parameters, I, J,<EOL>self.state_machine.n_states)<EOL> | Helper to calculate the backward weights. | f1432:c1:m4 |
def _construct_sparse_features(self, x): | I, J, K = x.shape<EOL>new_array_height = (x != <NUM_LIT:0>).sum(axis=<NUM_LIT:2>).max()<EOL>index_array = -np.ones((I, J, new_array_height), dtype='<STR_LIT>')<EOL>value_array = -np.ones((I, J, new_array_height), dtype='<STR_LIT>')<EOL>populate_sparse_features(x, index_array, value_array, I, J, K)<EOL>return index_arra... | Helper to construct a sparse representation of the features. | f1432:c1:m5 |
def build_lattice(self, x): | I, J, _ = x.shape<EOL>start_states, transitions = self._start_states, self._transitions<EOL>lattice = []<EOL>transitions_d = defaultdict(list)<EOL>for transition_index, (s0, s1, delta) in enumerate(transitions):<EOL><INDENT>transitions_d[s0].append((s1, delta, transition_index))<EOL><DEDENT>unvisited_nodes = deque([(<N... | Construct the list of nodes and edges for input features. | f1436:c0:m1 |
def _independent_lattice(self, shape, lattice=None): | I, J = shape<EOL>if lattice is not None:<EOL><INDENT>end_I = min(I, max(lattice[..., <NUM_LIT:3>])) - <NUM_LIT:1><EOL>end_J = min(J, max(lattice[..., <NUM_LIT:4>])) - <NUM_LIT:1><EOL>unvisited_nodes = deque([(i, j, s)<EOL>for i in range(end_I)<EOL>for j in range(end_J)<EOL>for s in self._start_states])<EOL>lattice = la... | Helper to construct the list of nodes and edges. | f1436:c1:m2 |
def build_lattice(self, x): | I, J, _ = x.shape<EOL>lattice = self._subset_independent_lattice((I, J))<EOL>return lattice<EOL> | Construct the list of nodes and edges for input features. | f1436:c1:m3 |
def fit_transform(self, raw_X, y=None): | return self.transform(raw_X)<EOL> | Like transform. Transform sequence pairs to feature arrays that can be used as input to `Hacrf` models.
Parameters
----------
raw_X : List of (sequence1_n, sequence2_n) pairs, one for each training example n.
y : (ignored)
Returns
-------
X : List of numpy ndar... | f1438:c0:m1 |
def transform(self, raw_X, y=None): | return [self._extract_features(sequence1, sequence2) for sequence1, sequence2 in raw_X]<EOL> | Transform sequence pairs to feature arrays that can be used as input to `Hacrf` models.
Parameters
----------
raw_X : List of (sequence1_n, sequence2_n) pairs, one for each training example n.
y : (ignored)
Returns
-------
X : List of numpy ndarrays, each with ... | f1438:c0:m2 |
def _extract_features(self, sequence1, sequence2): | array1 = np.array(tuple(sequence1), ndmin=<NUM_LIT:2>).T<EOL>array2 = np.array(tuple(sequence2), ndmin=<NUM_LIT:2>)<EOL>K = (len(self._binary_features) <EOL>+ sum(num_feats for _, num_feats in self._sparse_features))<EOL>feature_array = np.zeros((array1.size, array2.size, K), dtype='<STR_LIT>')<EOL>for k, feature_funct... | Helper to extract features for one data point. | f1438:c0:m3 |
@register.filter<EOL>def json(a): | json_str = json_dumps(a)<EOL>escapes = ['<STR_LIT:<>', '<STR_LIT:>>', '<STR_LIT:&>']<EOL>for c in escapes:<EOL><INDENT>json_str = json_str.replace(c, r'<STR_LIT>' % ord(c))<EOL><DEDENT>return mark_safe(json_str)<EOL> | Output the json encoding of its argument.
This will escape all the HTML/XML special characters with their unicode
escapes, so it is safe to be output anywhere except for inside a tag
attribute.
If the output needs to be put in an attribute, entitize the output of this
filter. | f1444:m0 |
def render_to_response(self, obj, **response_kwargs): | return HttpResponse(self.serialize(obj), content_type='<STR_LIT:application/json>', **response_kwargs)<EOL> | Returns an ``HttpResponse`` object instance with Content-Type:
application/json.
The response body will be the return value of ``self.serialize(obj)`` | f1445:c0:m0 |
def serialize(self, obj): | return dumps(obj)<EOL> | Returns a json serialized string object encoded using
`argonauts.serializers.JSONArgonautsEncoder`. | f1445:c0:m1 |
def http_method_not_allowed(self, *args, **kwargs): | resp = super(JsonResponseMixin, self).http_method_not_allowed(*args, **kwargs)<EOL>resp['<STR_LIT:Content-Type>'] = '<STR_LIT:application/json>'<EOL>return resp<EOL> | Returns super after setting the Content-Type header to
``application/json`` | f1445:c0:m2 |
def data(self): | if self.request.method == '<STR_LIT:GET>':<EOL><INDENT>return self.request.GET<EOL><DEDENT>else:<EOL><INDENT>assert self.request.META['<STR_LIT>'].startswith('<STR_LIT:application/json>')<EOL>charset = self.request.encoding or settings.DEFAULT_CHARSET<EOL>return json.loads(self.request.body.decode(charset))<EOL><DEDENT... | Helper class for parsing JSON POST data into a Python object. | f1445:c1:m0 |
def auth(self, *args, **kwargs): | raise NotImplementedError("<STR_LIT>")<EOL> | Hook for implementing custom authentication.
Raises ``NotImplementedError`` by default. Subclasses must overwrite
this. | f1445:c2:m0 |
def dispatch(self, *args, **kwargs): | try:<EOL><INDENT>self.auth(*args, **kwargs)<EOL>return super(RestView, self).dispatch(*args, **kwargs)<EOL><DEDENT>except ValidationError as e:<EOL><INDENT>return self.render_to_response(e.message_dict, status=<NUM_LIT>)<EOL><DEDENT>except Http404 as e:<EOL><INDENT>return self.render_to_response(str(e), status=<NUM_LIT... | Authenticates the request and dispatches to the correct HTTP method
function (GET, POST, PUT,...).
Translates exceptions into proper JSON serialized HTTP responses:
- ValidationError: HTTP 409
- Http404: HTTP 404
- PermissionDenied: HTTP 403
- ValueError: HTTP 400 | f1445:c2:m1 |
def options(self, request, *args, **kwargs): | allow = []<EOL>for method in self.http_method_names:<EOL><INDENT>if hasattr(self, method):<EOL><INDENT>allow.append(method.upper())<EOL><DEDENT><DEDENT>r = self.render_to_response(None)<EOL>r['<STR_LIT>'] = '<STR_LIT:U+002C>'.join(allow)<EOL>return r<EOL> | Implements a OPTIONS HTTP method function returning all allowed HTTP
methods. | f1445:c2:m2 |
def dumps(*args, **kwargs): | import json<EOL>from django.conf import settings<EOL>from argonauts.serializers import JSONArgonautsEncoder<EOL>kwargs.setdefault('<STR_LIT>', JSONArgonautsEncoder)<EOL>if settings.DEBUG:<EOL><INDENT>kwargs.setdefault('<STR_LIT>', <NUM_LIT:4>)<EOL>kwargs.setdefault('<STR_LIT>', ('<STR_LIT:U+002C>', '<STR_LIT>'))<EOL><D... | Wrapper for json.dumps that uses the JSONArgonautsEncoder. | f1446:m1 |
def roughpage(request, url): | if settings.APPEND_SLASH and not url.endswith('<STR_LIT:/>'):<EOL><INDENT>return redirect(url + '<STR_LIT:/>', permanent=True)<EOL><DEDENT>filename = url_to_filename(url)<EOL>template_filenames = get_backend().prepare_filenames(filename,<EOL>request=request)<EOL>root = settings.ROUGHPAGES_TEMPLATE_DIR<EOL>template_file... | Public interface to the rough page view. | f1458:m0 |
@csrf_protect<EOL>def render_roughpage(request, t): | import django<EOL>if django.VERSION >= (<NUM_LIT:1>, <NUM_LIT:8>):<EOL><INDENT>c = {}<EOL>response = HttpResponse(t.render(c, request))<EOL><DEDENT>else:<EOL><INDENT>c = RequestContext(request)<EOL>response = HttpResponse(t.render(c))<EOL><DEDENT>return response<EOL> | Internal interface to the rough page view. | f1458:m1 |
def prepare_filenames(self, normalized_url, request): | raise NotImplementedError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL> | Prepare template filename list
Args:
normalized_url (str): A normalized url
request (instance): An instance of HttpRequest
Returns:
list
Raises:
NotImplementedError | f1462:c0:m0 |
@prepare_filename_decorator<EOL><INDENT>def prepare_filenames(self, normalized_url, request):<DEDENT> | filenames = [normalized_url]<EOL>if request.user.is_authenticated():<EOL><INDENT>filenames.insert(<NUM_LIT:0>, normalized_url + "<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>filenames.insert(<NUM_LIT:0>, normalized_url + "<STR_LIT>")<EOL><DEDENT>return filenames<EOL> | Prepare template filename list based on the user authenticated state
If user is authenticated user, it use '_authenticated' as a suffix.
Otherwise it use '_anonymous' as a suffix to produce the template
filename list. The list include original filename at the end of the
list.
Args:
normalized_url (str): A normali... | f1463:c0:m0 |
def get_backend(backend_class=None): | cache_name = '<STR_LIT>'<EOL>if not hasattr(get_backend, cache_name):<EOL><INDENT>backend_class = backend_class or settings.ROUGHPAGES_BACKEND<EOL>if isinstance(backend_class, basestring):<EOL><INDENT>module_path, class_name = backend_class.rsplit("<STR_LIT:.>", <NUM_LIT:1>)<EOL>module = import_module(module_path)<EOL>... | Get backend instance
If no `backend_class` is specified, the backend class is determined from
the value of `settings.ROUGHPAGES_BACKEND`.
`backend_class` can be a class object or dots separated python import path
Returns:
backend instance | f1464:m0 |
@prepare_filename_decorator<EOL><INDENT>def prepare_filenames(self, normalized_url, request):<DEDENT> | return [normalized_url]<EOL> | Prepare template filename list
Args:
normalized_url (str): A normalized url
request (instance): An instance of HttpRequest
Returns:
list
Examples:
>>> from mock import MagicMock
>>> request = MagicMock()
>>> backend = PlainTemplateFilenameBackend()
>>> filenames = backend.prepare_filename... | f1465:c0:m0 |
def prepare_filename_decorator(fn): | @wraps(fn)<EOL>def inner(self, normalized_url, request):<EOL><INDENT>ext = settings.ROUGHPAGES_TEMPLATE_FILE_EXT<EOL>if not normalized_url:<EOL><INDENT>normalized_url = settings.ROUGHPAGES_INDEX_FILENAME<EOL><DEDENT>filenames = fn(self, normalized_url, request)<EOL>filenames = [x + ext for x in filenames if x]<EOL>retu... | A decorator of `prepare_filename` method
1. It automatically assign `settings.ROUGHPAGES_INDEX_FILENAME` if the
`normalized_url` is ''.
2. It automatically assign file extensions to the output list. | f1466:m0 |
def url_to_filename(url): | <EOL>if url.startswith('<STR_LIT:/>'):<EOL><INDENT>url = url[<NUM_LIT:1>:]<EOL><DEDENT>if url.endswith('<STR_LIT:/>'):<EOL><INDENT>url = url[:-<NUM_LIT:1>]<EOL><DEDENT>url = remove_pardir_symbols(url)<EOL>url = replace_dots_to_underscores_at_last(url)<EOL>return url<EOL> | Safely translate url to relative filename
Args:
url (str): A target url string
Returns:
str | f1467:m0 |
def remove_pardir_symbols(path, sep=os.sep, pardir=os.pardir): | bits = path.split(sep)<EOL>bits = (x for x in bits if x != pardir)<EOL>return sep.join(bits)<EOL> | Remove relative path symobls such as '..'
Args:
path (str): A target path string
sep (str): A strint to refer path delimiter (Default: `os.sep`)
pardir (str): A string to refer parent directory (Default: `os.pardir`)
Returns:
str | f1467:m1 |
def replace_dots_to_underscores_at_last(path): | if path == '<STR_LIT>':<EOL><INDENT>return path<EOL><DEDENT>bits = path.split('<STR_LIT:/>')<EOL>bits[-<NUM_LIT:1>] = bits[-<NUM_LIT:1>].replace('<STR_LIT:.>', '<STR_LIT:_>')<EOL>return '<STR_LIT:/>'.join(bits)<EOL> | Remove dot ('.') while a dot is treated as a special character in backends
Args:
path (str): A target path string
Returns:
str | f1467:m2 |
def random_string(size): | return '<STR_LIT>'.join(random.choice(string.ascii_letters + string.digits) for _ in range(size))<EOL> | Generate a random string of *size* length consisting of both letters
and numbers. This function is not meant for cryptographic purposes
and should not be used to generate security tokens.
:param int size: The length of the string to return.
:return: A string consisting of random characters.
:rtype: str | f1473:m4 |
def resolve_ssl_protocol_version(version=None): | if version is None:<EOL><INDENT>protocol_preference = ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>for protocol in protocol_preference:<EOL><INDENT>if hasattr(ssl, '<STR_LIT>' + protocol):<EOL><INDENT>return getattr(ssl, '<STR_LIT>' + protocol)<EOL><DEDENT><DEDENT>raise RuntimeErro... | Look up an SSL protocol version by name. If *version* is not specified, then
the strongest protocol available will be returned.
:param str version: The name of the version to look up.
:return: A protocol constant from the :py:mod:`ssl` module.
:rtype: int | f1473:m5 |
def build_server_from_argparser(description=None, server_klass=None, handler_klass=None): | import argparse<EOL>def _argp_dir_type(arg):<EOL><INDENT>if not os.path.isdir(arg):<EOL><INDENT>raise argparse.ArgumentTypeError("<STR_LIT>".format(repr(arg)))<EOL><DEDENT>return arg<EOL><DEDENT>def _argp_port_type(arg):<EOL><INDENT>if not arg.isdigit():<EOL><INDENT>raise argparse.ArgumentTypeError("<STR_LIT>".format(r... | Build a server from command line arguments. If a ServerClass or
HandlerClass is specified, then the object must inherit from the
corresponding AdvancedHTTPServer base class.
:param str description: Description string to be passed to the argument parser.
:param server_klass: Alternative server class to use.
:type serve... | f1473:m6 |
def build_server_from_config(config, section_name, server_klass=None, handler_klass=None): | server_klass = (server_klass or AdvancedHTTPServer)<EOL>handler_klass = (handler_klass or RequestHandler)<EOL>port = config.getint(section_name, '<STR_LIT:port>')<EOL>web_root = None<EOL>if config.has_option(section_name, '<STR_LIT>'):<EOL><INDENT>web_root = config.get(section_name, '<STR_LIT>')<EOL><DEDENT>if config.h... | Build a server from a provided :py:class:`configparser.ConfigParser`
instance. If a ServerClass or HandlerClass is specified, then the
object must inherit from the corresponding AdvancedHTTPServer base
class.
:param config: Configuration to retrieve settings from.
:type config: :py:class:`configparser.ConfigParser`
:p... | f1473:m7 |
def __init__(self, path, handler=None, is_rpc=False): | self.path = path<EOL>self.is_rpc = is_rpc<EOL>if handler is None or isinstance(handler, str):<EOL><INDENT>self.handler = handler<EOL><DEDENT>elif hasattr(handler, '<STR_LIT>'):<EOL><INDENT>self.handler = handler.__name__<EOL><DEDENT>elif hasattr(handler, '<STR_LIT>'):<EOL><INDENT>self.handler = handler.__class__.__name... | :param str path: The path regex to register the function to.
:param str handler: A specific :py:class:`.RequestHandler` class to register the handler with.
:param bool is_rpc: Whether the handler is an RPC handler or not. | f1473:c1:m0 |
@property<EOL><INDENT>def is_remote_exception(self):<DEDENT> | return bool(self.remote_exception is not None)<EOL> | This is true if the represented error resulted from an exception on the
remote server.
:type: bool | f1473:c2:m3 |
def __init__(self, address, use_ssl=False, username=None, password=None, uri_base='<STR_LIT:/>', ssl_context=None): | self.host = str(address[<NUM_LIT:0>])<EOL>self.port = int(address[<NUM_LIT:1>])<EOL>if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>self.logger = logging.getLogger('<STR_LIT>')<EOL><DEDENT>self.headers = None<EOL>"""<STR_LIT>"""<EOL>self.use_ssl = bool(use_ssl)<EOL>self.ssl_context = ssl_context<EOL>self.uri_base = str(... | :param tuple address: The address of the server to connect to as (host, port).
:param bool use_ssl: Whether to connect with SSL or not.
:param str username: The username to authenticate with.
:param str password: The password to authenticate with.
:param str uri_base: An optional prefix for all methods.
:param ssl_cont... | f1473:c4:m0 |
def set_serializer(self, serializer_name, compression=None): | self.serializer = Serializer(serializer_name, charset='<STR_LIT>', compression=compression)<EOL>self.logger.debug('<STR_LIT>' + serializer_name)<EOL> | Configure the serializer to use for communication with the server.
The serializer specified must be valid and in the
:py:data:`.g_serializer_drivers` map.
:param str serializer_name: The name of the serializer to use.
:param str compression: The name of a compression library to use. | f1473:c4:m3 |
def encode(self, data): | return self.serializer.dumps(data)<EOL> | Encode data with the configured serializer. | f1473:c4:m5 |
def decode(self, data): | return self.serializer.loads(data)<EOL> | Decode data with the configured serializer. | f1473:c4:m6 |
def reconnect(self): | self.lock.acquire()<EOL>if self.use_ssl:<EOL><INDENT>self.client = http.client.HTTPSConnection(self.host, self.port, context=self.ssl_context)<EOL><DEDENT>else:<EOL><INDENT>self.client = http.client.HTTPConnection(self.host, self.port)<EOL><DEDENT>self.lock.release()<EOL> | Reconnect to the remote server. | f1473:c4:m7 |
def call(self, method, *args, **kwargs): | if kwargs:<EOL><INDENT>options = self.encode(dict(args=args, kwargs=kwargs))<EOL><DEDENT>else:<EOL><INDENT>options = self.encode(args)<EOL><DEDENT>headers = {}<EOL>if self.headers:<EOL><INDENT>headers.update(self.headers)<EOL><DEDENT>headers['<STR_LIT:Content-Type>'] = self.serializer.content_type<EOL>headers['<STR_LIT... | Issue a call to the remote end point to execute the specified
procedure.
:param str method: The name of the remote procedure to execute.
:return: The return value from the remote function. | f1473:c4:m8 |
def cache_call(self, method, *options): | options_hash = self.encode(options)<EOL>if len(options_hash) > <NUM_LIT:20>:<EOL><INDENT>options_hash = hashlib.new('<STR_LIT>', options_hash).digest()<EOL><DEDENT>options_hash = sqlite3.Binary(options_hash)<EOL>with self.cache_lock:<EOL><INDENT>cursor = self.cache_db.cursor()<EOL>cursor.execute('<STR_LIT>', (method, o... | Call a remote method and store the result locally. Subsequent
calls to the same method with the same arguments will return the
cached result without invoking the remote procedure. Cached results are
kept indefinitely and must be manually refreshed with a call to
:py:meth:`.cache_call_refresh`.
:param str method: The n... | f1473:c5:m1 |
def cache_call_refresh(self, method, *options): | options_hash = self.encode(options)<EOL>if len(options_hash) > <NUM_LIT:20>:<EOL><INDENT>options_hash = hashlib.new('<STR_LIT>', options).digest()<EOL><DEDENT>options_hash = sqlite3.Binary(options_hash)<EOL>with self.cache_lock:<EOL><INDENT>cursor = self.cache_db.cursor()<EOL>cursor.execute('<STR_LIT>', (method, option... | Call a remote method and update the local cache with the result
if it already existed.
:param str method: The name of the remote procedure to execute.
:return: The return value from the remote function. | f1473:c5:m2 |
def cache_clear(self): | with self.cache_lock:<EOL><INDENT>cursor = self.cache_db.cursor()<EOL>cursor.execute('<STR_LIT>')<EOL>self.cache_db.commit()<EOL><DEDENT>self.logger.info('<STR_LIT>')<EOL>return<EOL> | Purge the local store of all cached function information. | f1473:c5:m3 |
def on_init(self): | pass<EOL> | This method is meant to be over ridden by custom classes. It is
called as part of the __init__ method and provides an opportunity
for the handler maps to be populated with entries or the config to be
customized. | f1473:c8:m2 |
def respond_file(self, file_path, attachment=False, query=None): | del query<EOL>file_path = os.path.abspath(file_path)<EOL>try:<EOL><INDENT>file_obj = open(file_path, '<STR_LIT:rb>')<EOL><DEDENT>except IOError:<EOL><INDENT>self.respond_not_found()<EOL>return<EOL><DEDENT>self.send_response(<NUM_LIT:200>)<EOL>self.send_header('<STR_LIT:Content-Type>', self.guess_mime_type(file_path))<E... | Respond to the client by serving a file, either directly or as
an attachment.
:param str file_path: The path to the file to serve, this does not need to be in the web root.
:param bool attachment: Whether to serve the file as a download by setting the Content-Disposition header. | f1473:c8:m5 |
def respond_list_directory(self, dir_path, query=None): | del query<EOL>try:<EOL><INDENT>dir_contents = os.listdir(dir_path)<EOL><DEDENT>except os.error:<EOL><INDENT>self.respond_not_found()<EOL>return<EOL><DEDENT>if os.path.normpath(dir_path) != self.__config['<STR_LIT>']:<EOL><INDENT>dir_contents.append('<STR_LIT:..>')<EOL><DEDENT>dir_contents.sort(key=lambda a: a.lower())<... | Respond to the client with an HTML page listing the contents of
the specified directory.
:param str dir_path: The path of the directory to list the contents of. | f1473:c8:m6 |
def respond_not_found(self): | self.send_response_full(b'<STR_LIT>', status=<NUM_LIT>)<EOL>return<EOL> | Respond to the client with a default 404 message. | f1473:c8:m7 |
def respond_redirect(self, location='<STR_LIT:/>'): | self.send_response(<NUM_LIT>)<EOL>self.send_header('<STR_LIT>', <NUM_LIT:0>)<EOL>self.send_header('<STR_LIT>', location)<EOL>self.end_headers()<EOL>return<EOL> | Respond to the client with a 301 message and redirect them with
a Location header.
:param str location: The new location to redirect the client to. | f1473:c8:m8 |
def respond_server_error(self, status=None, status_line=None, message=None): | (ex_type, ex_value, ex_traceback) = sys.exc_info()<EOL>if ex_type:<EOL><INDENT>(ex_file_name, ex_line, _, _) = traceback.extract_tb(ex_traceback)[-<NUM_LIT:1>]<EOL>line_info = "<STR_LIT>".format(ex_file_name, ex_line)<EOL>log_msg = "<STR_LIT>".format(repr(ex_value), line_info)<EOL>self.server.logger.error(log_msg, exc_... | Handle an internal server error, logging a traceback if executed
within an exception handler.
:param int status: The status code to respond to the client with.
:param str status_line: The status message to respond to the client with.
:param str message: The body of the response that is sent to the client. | f1473:c8:m9 |
def respond_unauthorized(self, request_authentication=False): | headers = {}<EOL>if request_authentication:<EOL><INDENT>headers['<STR_LIT>'] = '<STR_LIT>' + self.__config['<STR_LIT>'] + '<STR_LIT:">'<EOL><DEDENT>self.send_response_full(b'<STR_LIT>', status=<NUM_LIT>, headers=headers)<EOL>return<EOL> | Respond to the client that the request is unauthorized.
:param bool request_authentication: Whether to request basic authentication information by sending a WWW-Authenticate header. | f1473:c8:m10 |
def dispatch_handler(self, query=None): | query = (query or {})<EOL>self.path = self.path.split('<STR_LIT:?>', <NUM_LIT:1>)[<NUM_LIT:0>]<EOL>self.path = self.path.split('<STR_LIT:#>', <NUM_LIT:1>)[<NUM_LIT:0>]<EOL>original_path = urllib.parse.unquote(self.path)<EOL>self.path = posixpath.normpath(original_path)<EOL>words = self.path.split('<STR_LIT:/>')<EOL>wor... | Dispatch functions based on the established handler_map. It is
generally not necessary to override this function and doing so
will prevent any handlers from being executed. This function is
executed automatically when requests of either GET, HEAD, or POST
are received.
:param dict query: Parsed query parameters from t... | f1473:c8:m11 |
def guess_mime_type(self, path): | _, ext = posixpath.splitext(path)<EOL>if ext in self.extensions_map:<EOL><INDENT>return self.extensions_map[ext]<EOL><DEDENT>ext = ext.lower()<EOL>return self.extensions_map[ext if ext in self.extensions_map else '<STR_LIT>']<EOL> | Guess an appropriate MIME type based on the extension of the
provided path.
:param str path: The of the file to analyze.
:return: The guessed MIME type of the default if non are found.
:rtype: str | f1473:c8:m15 |
def stock_handler_respond_unauthorized(self, query): | del query<EOL>self.respond_unauthorized()<EOL>return<EOL> | This method provides a handler suitable to be used in the handler_map. | f1473:c8:m16 |
def stock_handler_respond_not_found(self, query): | del query<EOL>self.respond_not_found()<EOL>return<EOL> | This method provides a handler suitable to be used in the handler_map. | f1473:c8:m17 |
def check_authorization(self): | try:<EOL><INDENT>store = self.__config.get('<STR_LIT>')<EOL>if store is None:<EOL><INDENT>return True<EOL><DEDENT>auth_info = self.headers.get('<STR_LIT>')<EOL>if not auth_info:<EOL><INDENT>return False<EOL><DEDENT>auth_info = auth_info.split()<EOL>if len(auth_info) != <NUM_LIT:2> or auth_info[<NUM_LIT:0>] != '<STR_LIT... | Check for the presence of a basic auth Authorization header and
if the credentials contained within in are valid.
:return: Whether or not the credentials are valid.
:rtype: bool | f1473:c8:m18 |
def cookie_get(self, name): | if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>return None<EOL><DEDENT>if self.cookies.get(name):<EOL><INDENT>return self.cookies.get(name).value<EOL><DEDENT>return None<EOL> | Check for a cookie value by name.
:param str name: Name of the cookie value to retreive.
:return: Returns the cookie value if it's set or None if it's not found. | f1473:c8:m19 |
def cookie_set(self, name, value): | if not self.headers_active:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>cookie = "<STR_LIT>".format(name, value)<EOL>self.send_header('<STR_LIT>', cookie)<EOL> | Set the value of a client cookie. This can only be called while
headers can be sent.
:param str name: The name of the cookie value to set.
:param str value: The value of the cookie to set. | f1473:c8:m20 |
def get_query(self, name, default=None): | return self.query_data.get(name, [default])[<NUM_LIT:0>]<EOL> | Get a value from the query data that was sent to the server.
:param str name: The name of the query value to retrieve.
:param default: The value to return if *name* is not specified.
:return: The value if it exists, otherwise *default* will be returned.
:rtype: str | f1473:c8:m27 |
def get_content_type_charset(self, default='<STR_LIT>'): | encoding = default<EOL>header = self.headers.get('<STR_LIT:Content-Type>', '<STR_LIT>')<EOL>idx = header.find('<STR_LIT>')<EOL>if idx > <NUM_LIT:0>:<EOL><INDENT>encoding = (header[idx + <NUM_LIT:8>:].split('<STR_LIT:U+0020>', <NUM_LIT:1>)[<NUM_LIT:0>] or encoding)<EOL><DEDENT>return encoding<EOL> | Inspect the Content-Type header to retrieve the charset that the client
has specified.
:param str default: The default charset to return if none exists.
:return: The charset of the request.
:rtype: str | f1473:c8:m28 |
def __init__(self, handler): | self.handler = handler<EOL>if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>self.logger = logging.getLogger('<STR_LIT>')<EOL><DEDENT>headers = self.handler.headers<EOL>client_extensions = headers.get('<STR_LIT>', '<STR_LIT>')<EOL>self.client_extensions = [extension.strip() for extension in client_extensions.split('<STR_L... | :param handler: The :py:class:`RequestHandler` instance that is handling the request. | f1473:c10:m0 |
def close(self): | if not self.connected:<EOL><INDENT>return<EOL><DEDENT>self.connected = False<EOL>if self.handler.wfile.closed:<EOL><INDENT>return<EOL><DEDENT>if select.select([], [self.handler.wfile], [], <NUM_LIT:0>)[<NUM_LIT:1>]:<EOL><INDENT>with self.lock:<EOL><INDENT>self.handler.wfile.write(b'<STR_LIT>')<EOL><DEDENT><DEDENT>self.... | Close the web socket connection and stop processing results. If the
connection is still open, a WebSocket close message will be sent to the
peer. | f1473:c10:m3 |
def send_message(self, opcode, message): | if not isinstance(message, bytes):<EOL><INDENT>message = message.encode('<STR_LIT:utf-8>')<EOL><DEDENT>length = len(message)<EOL>if not select.select([], [self.handler.wfile], [], <NUM_LIT:0>)[<NUM_LIT:1>]:<EOL><INDENT>self.logger.error('<STR_LIT>')<EOL>self.close()<EOL>return<EOL><DEDENT>buffer = b'<STR_LIT>'<EOL>buff... | Send a message to the peer over the socket.
:param int opcode: The opcode for the message to send.
:param bytes message: The message data to send. | f1473:c10:m4 |
def on_closed(self): | pass<EOL> | A method that can be over ridden and is called after the web socket is
closed. | f1473:c10:m8 |
def on_connected(self): | pass<EOL> | A method that can be over ridden and is called after the web socket is
connected. | f1473:c10:m9 |
def on_message(self, opcode, message): | self.logger.debug("<STR_LIT>".format(self._opcode_names.get(opcode, '<STR_LIT>'), opcode))<EOL>if opcode == self._opcode_close:<EOL><INDENT>self.close()<EOL><DEDENT>elif opcode == self._opcode_ping:<EOL><INDENT>if len(message) > <NUM_LIT>:<EOL><INDENT>self.close()<EOL>return<EOL><DEDENT>self.send_message(self._opcode_p... | The primary dispatch function to handle incoming WebSocket messages.
:param int opcode: The opcode of the message that was received.
:param bytes message: The data contained within the message. | f1473:c10:m10 |
def on_message_binary(self, message): | pass<EOL> | A method that can be over ridden and is called when a binary message is
received from the peer.
:param bytes message: The message data. | f1473:c10:m11 |
def on_message_text(self, message): | pass<EOL> | A method that can be over ridden and is called when a text message is
received from the peer.
:param str message: The message data. | f1473:c10:m12 |
def __init__(self, name, charset='<STR_LIT>', compression=None): | if not name in g_serializer_drivers:<EOL><INDENT>raise ValueError("<STR_LIT>".format(name))<EOL><DEDENT>self.name = name<EOL>self._charset = charset<EOL>self._compression = compression<EOL>self.content_type = "<STR_LIT>".format(self.name, self._charset)<EOL>if self._compression:<EOL><INDENT>self.content_type += '<STR_L... | :param str name: The name of the serializer to use.
:param str charset: The name of the encoding to use.
:param str compression: The compression library to use. | f1473:c11:m0 |
@classmethod<EOL><INDENT>def from_content_type(cls, content_type):<DEDENT> | name = content_type<EOL>options = {}<EOL>if '<STR_LIT:;>' in content_type:<EOL><INDENT>name, options_str = content_type.split('<STR_LIT:;>', <NUM_LIT:1>)<EOL>for part in options_str.split('<STR_LIT:;>'):<EOL><INDENT>part = part.strip()<EOL>if '<STR_LIT:=>' in part:<EOL><INDENT>key, value = part.split('<STR_LIT:=>')<EOL... | Build a serializer object from a MIME Content-Type string.
:param str content_type: The Content-Type string to parse.
:return: A new serializer instance.
:rtype: :py:class:`.Serializer` | f1473:c11:m1 |
def dumps(self, data): | data = g_serializer_drivers[self.name]['<STR_LIT>'](data)<EOL>if sys.version_info[<NUM_LIT:0>] == <NUM_LIT:3> and isinstance(data, str):<EOL><INDENT>data = data.encode(self._charset)<EOL><DEDENT>if self._compression == '<STR_LIT>':<EOL><INDENT>data = zlib.compress(data)<EOL><DEDENT>assert isinstance(data, bytes)<EOL>re... | Serialize a python data type for transmission or storage.
:param data: The python object to serialize.
:return: The serialized representation of the object.
:rtype: bytes | f1473:c11:m2 |
def loads(self, data): | if not isinstance(data, bytes):<EOL><INDENT>raise TypeError("<STR_LIT>".format(type(data).__name__))<EOL><DEDENT>if self._compression == '<STR_LIT>':<EOL><INDENT>data = zlib.decompress(data)<EOL><DEDENT>if sys.version_info[<NUM_LIT:0>] == <NUM_LIT:3> and self.name.startswith('<STR_LIT>'):<EOL><INDENT>data = data.decode... | Deserialize the data into it's original python object.
:param bytes data: The serialized object to load.
:return: The original python object. | f1473:c11:m3 |
def __init__(self, handler_klass, address=None, addresses=None, use_threads=True, ssl_certfile=None, ssl_keyfile=None, ssl_version=None): | if addresses is None:<EOL><INDENT>addresses = []<EOL><DEDENT>if address is None and not addresses:<EOL><INDENT>if ssl_certfile is not None:<EOL><INDENT>if os.getuid():<EOL><INDENT>addresses.insert(<NUM_LIT:0>, ('<STR_LIT>', <NUM_LIT>, True))<EOL><DEDENT>else:<EOL><INDENT>addresses.insert(<NUM_LIT:0>, ('<STR_LIT>', <NUM... | :param handler_klass: The request handler class to use.
:type handler_klass: :py:class:`.RequestHandler`
:param tuple address: The address to bind to in the format (host, port).
:param tuple addresses: The addresses to bind to in the format (host, port, ssl).
:param bool use_threads: Whether to enable the use of a thre... | f1473:c12:m0 |
def add_sni_cert(self, hostname, ssl_certfile=None, ssl_keyfile=None, ssl_version=None): | if not g_ssl_has_server_sni:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>if self._ssl_sni_entries is None:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>if ssl_certfile:<EOL><INDENT>ssl_certfile = os.path.abspath(ssl_certfile)<EOL><DEDENT>if ssl_keyfile:<EOL><INDENT>ssl_keyfile = os.path.abspath(s... | Add an SSL certificate for a specific hostname as supported by SSL's
Server Name Indicator (SNI) extension. See :rfc:`3546` for more details
on SSL extensions. In order to use this method, the server instance must
have been initialized with at least one address configured for SSL.
.. warning::
This method wil... | f1473:c12:m2 |
def remove_sni_cert(self, hostname): | if not g_ssl_has_server_sni:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>if self._ssl_sni_entries is None:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>sni_entry = self._ssl_sni_entries.pop(hostname, None)<EOL>if sni_entry is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT> | Remove the SSL Server Name Indicator (SNI) certificate configuration for
the specified *hostname*.
.. warning::
This method will raise a :py:exc:`RuntimeError` if either the SNI
extension is not available in the :py:mod:`ssl` module or if SSL was
not enabled at initialization time through the ... | f1473:c12:m3 |
@property<EOL><INDENT>def sni_certs(self):<DEDENT> | if not g_ssl_has_server_sni or self._ssl_sni_entries is None:<EOL><INDENT>return tuple()<EOL><DEDENT>return tuple(entry.certificate for entry in self._ssl_sni_entries.values())<EOL> | .. versionadded:: 2.2.0
:return: Return a tuple of :py:class:`~.SSLSNICertificate` instances for each of the certificates that are configured.
:rtype: tuple | f1473:c12:m4 |
def serve_forever(self, fork=False): | if fork:<EOL><INDENT>if not hasattr(os, '<STR_LIT>'):<EOL><INDENT>raise OSError('<STR_LIT>')<EOL><DEDENT>child_pid = os.fork()<EOL>if child_pid != <NUM_LIT:0>:<EOL><INDENT>self.logger.info('<STR_LIT>' + str(child_pid))<EOL>return child_pid<EOL><DEDENT><DEDENT>self.__server_thread = threading.current_thread()<EOL>self._... | Start handling requests. This method must be called and does not
return unless the :py:meth:`.shutdown` method is called from
another thread.
:param bool fork: Whether to fork or not before serving content.
:return: The child processes PID if *fork* is set to True.
:rtype: int | f1473:c12:m7 |
def shutdown(self): | self.__should_stop.set()<EOL>if self.__server_thread == threading.current_thread():<EOL><INDENT>self.__is_shutdown.set()<EOL>self.__is_running.clear()<EOL><DEDENT>else:<EOL><INDENT>if self.__wakeup_fd is not None:<EOL><INDENT>os.write(self.__wakeup_fd.write_fd, b'<STR_LIT:\x00>')<EOL><DEDENT>self.__is_shutdown.wait()<E... | Shutdown the server and stop responding to requests. | f1473:c12:m8 |
@property<EOL><INDENT>def serve_files(self):<DEDENT> | return self.__config['<STR_LIT>']<EOL> | Whether to enable serving files or not.
:type: bool | f1473:c12:m9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.