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`.
:returns: Loaded data.
:raises: :exc:`~lollipop.errors.ValidationError` | 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>return self.field_type.load_into(target, value, inplace=inplace,<EOL>context=context)<EOL><DEDENT>else:<EOL><INDENT>return self.field_type.load(value, context=context)<EOL><DEDENT> | 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 from.
:param bool inplace: If True update data inplace;
otherwise - create new data.
:param kwargs: Same keyword arguments as for :meth:`load`.
:returns: Loaded data.
:raises: :exc:`~lollipop.errors.ValidationError` | 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.ValidationError` | 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>data1 = {}<EOL>for name, field in iteritems(self.fields):<EOL><INDENT>try:<EOL><INDENT>if name in data:<EOL><INDENT>value = field.load_into(obj, name, data,<EOL>inplace=not self.immutable and inplace,<EOL>*args, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>value = field.load(name, {<EOL>name: field.dump(name, obj, *args, **kwargs)<EOL>})<EOL><DEDENT>if value is not MISSING:<EOL><INDENT>data1[name] = value<EOL><DEDENT><DEDENT>except ValidationError as ve:<EOL><INDENT>errors_builder.add_error(name, ve.messages)<EOL><DEDENT><DEDENT>if self.allow_extra_fields is False:<EOL><INDENT>field_names = [name for name, _ in iteritems(self.fields)]<EOL>for name in data:<EOL><INDENT>if name not in field_names:<EOL><INDENT>errors_builder.add_error(name, self._error_messages['<STR_LIT>'])<EOL><DEDENT><DEDENT><DEDENT>elif isinstance(self.allow_extra_fields, Field):<EOL><INDENT>field_names = [name for name, _ in iteritems(self.fields)]<EOL>for name in data:<EOL><INDENT>if name not in field_names:<EOL><INDENT>try:<EOL><INDENT>loaded = self.allow_extra_fields.load_into(<EOL>obj, name, data,<EOL>inplace=not self.immutable and inplace,<EOL>*args, **kwargs<EOL>)<EOL>if loaded != MISSING:<EOL><INDENT>data1[name] = loaded<EOL><DEDENT><DEDENT>except ValidationError as ve:<EOL><INDENT>errors_builder.add_error(name, ve.messages)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>errors_builder.raise_errors()<EOL>data2 = super(Object, self).load(data1, *args, **kwargs)<EOL>if self.immutable or not inplace:<EOL><INDENT>result = data2<EOL>if self.constructor:<EOL><INDENT>result = self.constructor(**result)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for name, value in iteritems(data2):<EOL><INDENT>field = self.fields.get(name, self.allow_extra_fields)<EOL>if not isinstance(field, Field):<EOL><INDENT>continue<EOL><DEDENT>field.set_value(name, obj, value, *args, **kwargs)<EOL><DEDENT>result = obj<EOL><DEDENT>return result<EOL> | 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 :meth:`Type.load`.
:returns: Updated object.
:raises: :exc:`~lollipop.errors.ValidationError` | 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.
:param data: Data to validate. Can be partial (not all schema field data
is present).
:param kwargs: Same keyword arguments as for :meth:`Type.load`.
:returns: validation errors or None | 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__).args) - <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>arg_count = len(inspect.getargspec(func.__call__).args) - <NUM_LIT:1><EOL><DEDENT><DEDENT>except TypeError:<EOL><INDENT>arg_count = numargs<EOL><DEDENT>if arg_count <= numargs:<EOL><INDENT>def normalized(*args):<EOL><INDENT>return func(*args[:-<NUM_LIT:1>])<EOL><DEDENT>return normalized<EOL><DEDENT>return func<EOL> | 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>].shape[<NUM_LIT:2>])<EOL>models = [_Model(self._state_machine, x, ty) for x, ty in zip(X, y)]<EOL>self._evaluation_count = <NUM_LIT:0><EOL>def _objective(parameters):<EOL><INDENT>gradient = np.zeros(self.parameters.shape)<EOL>ll = <NUM_LIT:0.0> <EOL>for model in models:<EOL><INDENT>dll, dgradient = model.forward_backward(parameters.reshape(self.parameters.shape))<EOL>ll += dll<EOL>gradient += dgradient<EOL><DEDENT>parameters_without_bias = np.array(parameters, dtype='<STR_LIT>') <EOL>parameters_without_bias[<NUM_LIT:0>] = <NUM_LIT:0><EOL>ll -= self.l2_regularization * np.dot(parameters_without_bias.T, parameters_without_bias)<EOL>gradient = gradient.flatten() - <NUM_LIT> * self.l2_regularization * parameters_without_bias<EOL>if verbosity > <NUM_LIT:0>:<EOL><INDENT>if self._evaluation_count == <NUM_LIT:0>:<EOL><INDENT>print('<STR_LIT>'.format('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'))<EOL><DEDENT>if self._evaluation_count % verbosity == <NUM_LIT:0>:<EOL><INDENT>print('<STR_LIT>'.format(self._evaluation_count, ll, (abs(gradient).sum())))<EOL><DEDENT><DEDENT>self._evaluation_count += <NUM_LIT:1><EOL>return -ll, -gradient<EOL><DEDENT>def _objective_copy_gradient(paramers, g):<EOL><INDENT>nll, ngradient = _objective(paramers)<EOL>g[:] = ngradient<EOL>return nll<EOL><DEDENT>if self._optimizer:<EOL><INDENT>self.optimizer_result = self._optimizer(_objective, self.parameters.flatten(), **self._optimizer_kwargs)<EOL>self.parameters = self.optimizer_result[<NUM_LIT:0>].reshape(self.parameters.shape)<EOL><DEDENT>else:<EOL><INDENT>optimizer = lbfgs.LBFGS()<EOL>final_betas = optimizer.minimize(_objective_copy_gradient,<EOL>x0=self.parameters.flatten(),<EOL>progress=None)<EOL>self.optimizer_result = final_betas<EOL>self.parameters = final_betas.reshape(self.parameters.shape)<EOL><DEDENT>return self<EOL> | 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 strings and n_features the
number of features.
y : array-like, shape (n_samples,)
Target vector relative to X.
Returns
-------
self : object
Returns self. | 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
string1_len and string2_len are the length of the two training strings and n_features the
number of features.
Returns
-------
T : array-like, shape = [n_samples, n_classes]
Returns the probability of the sample for each class in the model,
where classes are ordered as they are in ``self.classes_``. | 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
string2_len are the length of the two training strings and
n_features the number of features.
Returns
-------
y : iterable of shape = [n_samples]
The predicted classes. | 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
Parameter names mapped to their values. | 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 = self.x.shape<EOL>if not isinstance(self.sparse_x, str):<EOL><INDENT>C = self.sparse_x[<NUM_LIT:0>].shape[<NUM_LIT:2>]<EOL>S, _ = parameters.shape<EOL>x_dot_parameters = np.zeros((I, J, S))<EOL>sparse_multiply(x_dot_parameters, self.sparse_x[<NUM_LIT:0>], self.sparse_x[<NUM_LIT:1>], parameters.T, I, J, K, C, S)<EOL><DEDENT>else:<EOL><INDENT>x_dot_parameters = np.dot(self.x, parameters.T) <EOL><DEDENT>alpha = self._forward(x_dot_parameters)<EOL>beta = self._backward(x_dot_parameters)<EOL>classes_to_ints = {k: i for i, k in enumerate(set(self.states_to_classes.values()))}<EOL>states_to_classes = np.array([classes_to_ints[self.states_to_classes[state]]<EOL>for state in range(max(self.states_to_classes.keys()) + <NUM_LIT:1>)], dtype='<STR_LIT>')<EOL>if not isinstance(self.sparse_x, str):<EOL><INDENT>ll, deriv = gradient_sparse(alpha, beta, parameters, states_to_classes,<EOL>self.sparse_x[<NUM_LIT:0>], self.sparse_x[<NUM_LIT:1>], classes_to_ints[self.y],<EOL>I, J, self.sparse_x[<NUM_LIT:0>].shape[<NUM_LIT:2>])<EOL><DEDENT>else:<EOL><INDENT>ll, deriv = gradient(alpha, beta, parameters, states_to_classes,<EOL>self.x, classes_to_ints[self.y], I, J, K)<EOL><DEDENT>return ll, deriv<EOL> | 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>I, J, _ = self.x.shape<EOL>class_Z = {}<EOL>Z = -np.inf<EOL>for state, predicted_class in self.states_to_classes.items():<EOL><INDENT>weight = alpha[I - <NUM_LIT:1>, J - <NUM_LIT:1>, state]<EOL>class_Z[self.states_to_classes[state]] = weight<EOL>Z = np.logaddexp(Z, weight)<EOL><DEDENT>return {label: np.exp(class_z - Z) for label, class_z in class_Z.items()}<EOL> | 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_array, value_array<EOL> | 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([(<NUM_LIT:0>, <NUM_LIT:0>, s) for s in start_states])<EOL>visited_nodes = set()<EOL>n_states = self.n_states<EOL>while unvisited_nodes:<EOL><INDENT>node = unvisited_nodes.popleft()<EOL>lattice.append(node)<EOL>i, j, s0 = node<EOL>for s1, delta, transition_index in transitions_d[s0]:<EOL><INDENT>try:<EOL><INDENT>di, dj = delta<EOL><DEDENT>except TypeError:<EOL><INDENT>di, dj = delta(i, j, x)<EOL><DEDENT>if i + di < I and j + dj < J:<EOL><INDENT>edge = (i, j, s0, i + di, j + dj, s1, transition_index + n_states)<EOL>lattice.append(edge)<EOL>dest_node = (i + di, j + dj, s1)<EOL>if dest_node not in visited_nodes:<EOL><INDENT>unvisited_nodes.append(dest_node)<EOL>visited_nodes.add(dest_node)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>lattice.sort()<EOL>final_lattice = []<EOL>visited_nodes = set((I-<NUM_LIT:1>, J-<NUM_LIT:1>, s) for s in range(n_states))<EOL>for node in lattice[::-<NUM_LIT:1>]:<EOL><INDENT>if node in visited_nodes:<EOL><INDENT>final_lattice.append(node)<EOL><DEDENT>elif len(node) > <NUM_LIT:3>:<EOL><INDENT>source_node, dest_node = node[<NUM_LIT:0>:<NUM_LIT:3>], node[<NUM_LIT:3>:<NUM_LIT:6>]<EOL>if dest_node in visited_nodes:<EOL><INDENT>visited_nodes.add(source_node)<EOL>final_lattice.append(node)<EOL><DEDENT><DEDENT><DEDENT>reversed_list = list(reversed(final_lattice))<EOL>lattice = [edge for edge in reversed_list if len(edge) > <NUM_LIT:3>]<EOL>return np.array(lattice, dtype='<STR_LIT>')<EOL> | 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 = lattice.tolist()<EOL><DEDENT>else:<EOL><INDENT>lattice = []<EOL>unvisited_nodes = deque([(<NUM_LIT:0>, <NUM_LIT:0>, s) for s in self._start_states])<EOL><DEDENT>lattice += _grow_independent_lattice(self._transitions, <EOL>self.n_states, (I, J), <EOL>unvisited_nodes)<EOL>lattice = np.array(sorted(lattice), dtype='<STR_LIT>')<EOL>return lattice<EOL> | 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 ndarrays, each with shape = (I_n, J_n, K), where I_n is the length of sequence1_n, J_n is the
length of sequence2_n, and K is the number of features.
Feature matrix list, for use with estimators or further transformers. | 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 shape = (I_n, J_n, K), where I_n is the length of sequence1_n, J_n is the
length of sequence2_n, and K is the number of features.
Feature matrix list, for use with estimators or further transformers. | 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_function in enumerate(self._binary_features):<EOL><INDENT>feature_array[..., k] = feature_function(array1, array2)<EOL><DEDENT>if self._sparse_features:<EOL><INDENT>n_binary_features = len(self._binary_features)<EOL>for i, j in np.ndindex(len(sequence1), len(sequence2)):<EOL><INDENT>k = n_binary_features<EOL>for feature_function, num_features in self._sparse_features:<EOL><INDENT>feature_array[i, j, k + feature_function(i, j, sequence1, sequence2)] = <NUM_LIT:1.0><EOL>k += num_features<EOL><DEDENT><DEDENT><DEDENT>return feature_array<EOL> | 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>)<EOL><DEDENT>except PermissionDenied as e:<EOL><INDENT>return self.render_to_response(str(e), status=<NUM_LIT>)<EOL><DEDENT>except ValueError as e:<EOL><INDENT>return self.render_to_response(str(e), status=<NUM_LIT>)<EOL><DEDENT> | 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><DEDENT>else:<EOL><INDENT>kwargs.setdefault('<STR_LIT>', ('<STR_LIT:U+002C>', '<STR_LIT::>'))<EOL><DEDENT>return json.dumps(*args, **kwargs)<EOL> | 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_filenames = [os.path.join(root, x) for x in template_filenames]<EOL>try:<EOL><INDENT>t = loader.select_template(template_filenames)<EOL>return render_roughpage(request, t)<EOL><DEDENT>except TemplateDoesNotExist:<EOL><INDENT>if settings.ROUGHPAGES_RAISE_TEMPLATE_DOES_NOT_EXISTS:<EOL><INDENT>raise<EOL><DEDENT>raise Http404<EOL><DEDENT> | 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 normalized url
request (instance): An instance of HttpRequest
Returns:
list
Examples:
>>> from mock import MagicMock
>>> request = MagicMock()
>>> backend = AuthTemplateFilenameBackend()
>>> request.user.is_authenticated.return_value = True
>>> filenames = backend.prepare_filenames('foo/bar/hogehoge',
... request)
>>> assert filenames == [
... 'foo/bar/hogehoge_authenticated.html',
... 'foo/bar/hogehoge.html'
... ]
>>> request.user.is_authenticated.return_value = False
>>> filenames = backend.prepare_filenames('foo/bar/hogehoge',
... request)
>>> assert filenames == [
... 'foo/bar/hogehoge_anonymous.html',
... 'foo/bar/hogehoge.html'
... ]
>>> request.user.is_authenticated.return_value = True
>>> filenames = backend.prepare_filenames('',
... request)
>>> assert filenames == [
... 'index_authenticated.html',
... 'index.html'
... ]
>>> request.user.is_authenticated.return_value = False
>>> filenames = backend.prepare_filenames('',
... request)
>>> assert filenames == [
... 'index_anonymous.html',
... 'index.html'
... ] | 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>backend_class = getattr(module, class_name)<EOL><DEDENT>setattr(get_backend, cache_name, backend_class())<EOL><DEDENT>return getattr(get_backend, cache_name)<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_filenames('foo/bar/hogehoge',
... request)
>>> assert filenames == [
... 'foo/bar/hogehoge.html'
... ]
>>> filenames = backend.prepare_filenames('',
... request)
>>> assert filenames == [
... 'index.html'
... ] | 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>return filenames<EOL><DEDENT>return inner<EOL> | 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 RuntimeError('<STR_LIT>')<EOL><DEDENT>elif isinstance(version, str):<EOL><INDENT>if not hasattr(ssl, '<STR_LIT>' + version):<EOL><INDENT>raise ValueError('<STR_LIT>' + version)<EOL><DEDENT>return getattr(ssl, '<STR_LIT>' + version)<EOL><DEDENT>raise TypeError("<STR_LIT>".format(type(version).__name__))<EOL> | 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(repr(arg)))<EOL><DEDENT>arg = int(arg)<EOL>if arg < <NUM_LIT:0> or arg > <NUM_LIT>:<EOL><INDENT>raise argparse.ArgumentTypeError("<STR_LIT>".format(repr(arg)))<EOL><DEDENT>return arg<EOL><DEDENT>description = (description or '<STR_LIT>')<EOL>server_klass = (server_klass or AdvancedHTTPServer)<EOL>handler_klass = (handler_klass or RequestHandler)<EOL>parser = argparse.ArgumentParser(conflict_handler='<STR_LIT>', description=description, fromfile_prefix_chars='<STR_LIT:@>')<EOL>parser.epilog = '<STR_LIT>'<EOL>parser.add_argument('<STR_LIT:-c>', '<STR_LIT>', dest='<STR_LIT>', type=argparse.FileType('<STR_LIT:r>'), help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', '<STR_LIT>', dest='<STR_LIT>', default='<STR_LIT>', help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', '<STR_LIT>', dest='<STR_LIT>', choices=('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'), default='<STR_LIT>', help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', '<STR_LIT>', dest='<STR_LIT:port>', default=<NUM_LIT>, type=_argp_port_type, help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', '<STR_LIT>', action='<STR_LIT:version>', version=parser.prog + '<STR_LIT>' + __version__)<EOL>parser.add_argument('<STR_LIT>', '<STR_LIT>', dest='<STR_LIT>', default='<STR_LIT:.>', type=_argp_dir_type, help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', dest='<STR_LIT>', help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', dest='<STR_LIT>', action='<STR_LIT>', default=True, help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', dest='<STR_LIT:password>', help='<STR_LIT>')<EOL>ssl_group = parser.add_argument_group('<STR_LIT>')<EOL>ssl_group.add_argument('<STR_LIT>', dest='<STR_LIT>', help='<STR_LIT>')<EOL>ssl_group.add_argument('<STR_LIT>', dest='<STR_LIT>', help='<STR_LIT>')<EOL>ssl_group.add_argument('<STR_LIT>', dest='<STR_LIT>', choices=[p[<NUM_LIT:9>:] for p in dir(ssl) if p.startswith('<STR_LIT>')], help='<STR_LIT>')<EOL>arguments = parser.parse_args()<EOL>logging.getLogger('<STR_LIT>').setLevel(logging.DEBUG)<EOL>console_log_handler = logging.StreamHandler()<EOL>console_log_handler.setLevel(getattr(logging, arguments.loglvl))<EOL>console_log_handler.setFormatter(logging.Formatter("<STR_LIT>"))<EOL>logging.getLogger('<STR_LIT>').addHandler(console_log_handler)<EOL>if arguments.log_file:<EOL><INDENT>main_file_handler = logging.handlers.RotatingFileHandler(arguments.log_file, maxBytes=<NUM_LIT>, backupCount=<NUM_LIT:5>)<EOL>main_file_handler.setLevel(logging.DEBUG)<EOL>main_file_handler.setFormatter(logging.Formatter("<STR_LIT>"))<EOL>logging.getLogger('<STR_LIT>').setLevel(logging.DEBUG)<EOL>logging.getLogger('<STR_LIT>').addHandler(main_file_handler)<EOL><DEDENT>if arguments.config:<EOL><INDENT>config = ConfigParser()<EOL>config.readfp(arguments.config)<EOL>server = build_server_from_config(<EOL>config,<EOL>'<STR_LIT>',<EOL>server_klass=server_klass,<EOL>handler_klass=handler_klass<EOL>)<EOL><DEDENT>else:<EOL><INDENT>server = server_klass(<EOL>handler_klass,<EOL>address=(arguments.ip, arguments.port),<EOL>use_threads=arguments.use_threads,<EOL>ssl_certfile=arguments.ssl_cert,<EOL>ssl_keyfile=arguments.ssl_key,<EOL>ssl_version=arguments.ssl_version<EOL>)<EOL>server.serve_files_root = arguments.web_root<EOL><DEDENT>if arguments.password:<EOL><INDENT>server.auth_add_creds('<STR_LIT>', arguments.password)<EOL><DEDENT>return server<EOL> | 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 server_klass: :py:class:`.AdvancedHTTPServer`
:param handler_klass: Alternative handler class to use.
:type handler_klass: :py:class:`.RequestHandler`
:return: A configured server instance.
:rtype: :py:class:`.AdvancedHTTPServer` | 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.has_option(section_name, '<STR_LIT>'):<EOL><INDENT>ip = config.get(section_name, '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>ip = '<STR_LIT>'<EOL><DEDENT>ssl_certfile = None<EOL>if config.has_option(section_name, '<STR_LIT>'):<EOL><INDENT>ssl_certfile = config.get(section_name, '<STR_LIT>')<EOL><DEDENT>ssl_keyfile = None<EOL>if config.has_option(section_name, '<STR_LIT>'):<EOL><INDENT>ssl_keyfile = config.get(section_name, '<STR_LIT>')<EOL><DEDENT>ssl_version = None<EOL>if config.has_option(section_name, '<STR_LIT>'):<EOL><INDENT>ssl_version = config.get(section_name, '<STR_LIT>')<EOL><DEDENT>server = server_klass(<EOL>handler_klass,<EOL>address=(ip, port),<EOL>ssl_certfile=ssl_certfile,<EOL>ssl_keyfile=ssl_keyfile,<EOL>ssl_version=ssl_version<EOL>)<EOL>if config.has_option(section_name, '<STR_LIT>'):<EOL><INDENT>password_type = config.get(section_name, '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>password_type = '<STR_LIT>'<EOL><DEDENT>if config.has_option(section_name, '<STR_LIT:password>'):<EOL><INDENT>password = config.get(section_name, '<STR_LIT:password>')<EOL>if config.has_option(section_name, '<STR_LIT:username>'):<EOL><INDENT>username = config.get(section_name, '<STR_LIT:username>')<EOL><DEDENT>else:<EOL><INDENT>username = '<STR_LIT>'<EOL><DEDENT>server.auth_add_creds(username, password, pwtype=password_type)<EOL><DEDENT>cred_idx = <NUM_LIT:0><EOL>while config.has_option(section_name, '<STR_LIT:password>' + str(cred_idx)):<EOL><INDENT>password = config.get(section_name, '<STR_LIT:password>' + str(cred_idx))<EOL>if not config.has_option(section_name, '<STR_LIT:username>' + str(cred_idx)):<EOL><INDENT>break<EOL><DEDENT>username = config.get(section_name, '<STR_LIT:username>' + str(cred_idx))<EOL>server.auth_add_creds(username, password, pwtype=password_type)<EOL>cred_idx += <NUM_LIT:1><EOL><DEDENT>if web_root is None:<EOL><INDENT>server.serve_files = False<EOL><DEDENT>else:<EOL><INDENT>server.serve_files = True<EOL>server.serve_files_root = web_root<EOL>if config.has_option(section_name, '<STR_LIT>'):<EOL><INDENT>server.serve_files_list_directories = config.getboolean(section_name, '<STR_LIT>')<EOL><DEDENT><DEDENT>return server<EOL> | 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`
:param str section_name: The section name of the configuration to use.
:param server_klass: Alternative server class to use.
:type server_klass: :py:class:`.AdvancedHTTPServer`
:param handler_klass: Alternative handler class to use.
:type handler_klass: :py:class:`.RequestHandler`
:return: A configured server instance.
:rtype: :py:class:`.AdvancedHTTPServer` | 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__<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' + repr(handler))<EOL><DEDENT> | :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(uri_base)<EOL>self.username = (None if username is None else str(username))<EOL>self.password = (None if password is None else str(password))<EOL>self.lock = threading.Lock()<EOL>"""<STR_LIT>"""<EOL>self.serializer = None<EOL>"""<STR_LIT>"""<EOL>self.set_serializer('<STR_LIT:application/json>')<EOL>self.reconnect()<EOL> | :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_context: An optional SSL context to use for SSL related options. | 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>'] = str(len(options))<EOL>headers['<STR_LIT>'] = '<STR_LIT>'<EOL>if self.username is not None and self.password is not None:<EOL><INDENT>headers['<STR_LIT>'] = '<STR_LIT>' + base64.b64encode((self.username + '<STR_LIT::>' + self.password).encode('<STR_LIT>')).decode('<STR_LIT>')<EOL><DEDENT>method = os.path.join(self.uri_base, method)<EOL>self.logger.debug('<STR_LIT>' + method[<NUM_LIT:1>:])<EOL>try:<EOL><INDENT>with self.lock:<EOL><INDENT>self.client.request('<STR_LIT>', method, options, headers)<EOL>resp = self.client.getresponse()<EOL><DEDENT><DEDENT>except http.client.ImproperConnectionState:<EOL><INDENT>raise RPCConnectionError('<STR_LIT>')<EOL><DEDENT>if resp.status != <NUM_LIT:200>:<EOL><INDENT>raise RPCError(resp.reason, resp.status)<EOL><DEDENT>resp_data = resp.read()<EOL>resp_data = self.decode(resp_data)<EOL>if not ('<STR_LIT>' in resp_data and '<STR_LIT:result>' in resp_data):<EOL><INDENT>raise RPCError('<STR_LIT>', resp.status)<EOL><DEDENT>if resp_data['<STR_LIT>']:<EOL><INDENT>raise RPCError('<STR_LIT>', resp.status, remote_exception=resp_data['<STR_LIT>'])<EOL><DEDENT>return resp_data['<STR_LIT:result>']<EOL> | 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, options_hash))<EOL>return_value = cursor.fetchone()<EOL><DEDENT>if return_value:<EOL><INDENT>return_value = bytes(return_value[<NUM_LIT:0>])<EOL>return self.decode(return_value)<EOL><DEDENT>return_value = self.call(method, *options)<EOL>store_return_value = sqlite3.Binary(self.encode(return_value))<EOL>with self.cache_lock:<EOL><INDENT>cursor = self.cache_db.cursor()<EOL>cursor.execute('<STR_LIT>', (method, options_hash, store_return_value))<EOL>self.cache_db.commit()<EOL><DEDENT>return return_value<EOL> | 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 name of the remote procedure to execute.
:return: The return value from the remote function. | 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, options_hash))<EOL><DEDENT>return_value = self.call(method, *options)<EOL>store_return_value = sqlite3.Binary(self.encode(return_value))<EOL>with self.cache_lock:<EOL><INDENT>cursor = self.cache_db.cursor()<EOL>cursor.execute('<STR_LIT>', (method, options_hash, store_return_value))<EOL>self.cache_db.commit()<EOL><DEDENT>return return_value<EOL> | 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))<EOL>fs = os.fstat(file_obj.fileno())<EOL>self.send_header('<STR_LIT>', str(fs[<NUM_LIT:6>]))<EOL>if attachment:<EOL><INDENT>file_name = os.path.basename(file_path)<EOL>self.send_header('<STR_LIT>', '<STR_LIT>' + file_name)<EOL><DEDENT>self.send_header('<STR_LIT>', self.date_time_string(fs.st_mtime))<EOL>self.end_headers()<EOL>shutil.copyfileobj(file_obj, self.wfile)<EOL>file_obj.close()<EOL>return<EOL> | 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())<EOL>displaypath = html.escape(urllib.parse.unquote(self.path), quote=True)<EOL>f = io.BytesIO()<EOL>encoding = sys.getfilesystemencoding()<EOL>f.write(b'<STR_LIT>')<EOL>f.write(b'<STR_LIT>' + displaypath.encode(encoding) + b'<STR_LIT>')<EOL>f.write(b'<STR_LIT>' + displaypath.encode(encoding) + b'<STR_LIT>')<EOL>f.write(b'<STR_LIT>')<EOL>for name in dir_contents:<EOL><INDENT>fullname = os.path.join(dir_path, name)<EOL>displayname = linkname = name<EOL>if os.path.isdir(fullname):<EOL><INDENT>displayname = name + "<STR_LIT:/>"<EOL>linkname = name + "<STR_LIT:/>"<EOL><DEDENT>if os.path.islink(fullname):<EOL><INDENT>displayname = name + "<STR_LIT:@>"<EOL><DEDENT>f.write(('<STR_LIT>' + urllib.parse.quote(linkname) + '<STR_LIT>' + html.escape(displayname, quote=True) + '<STR_LIT>').encode(encoding))<EOL><DEDENT>f.write(b'<STR_LIT>')<EOL>length = f.tell()<EOL>f.seek(<NUM_LIT:0>)<EOL>self.send_response(<NUM_LIT:200>)<EOL>self.send_header('<STR_LIT:Content-Type>', '<STR_LIT>' + encoding)<EOL>self.send_header('<STR_LIT>', length)<EOL>self.end_headers()<EOL>shutil.copyfileobj(f, self.wfile)<EOL>f.close()<EOL>return<EOL> | 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_info=True)<EOL><DEDENT>status = (status or <NUM_LIT>)<EOL>status_line = (status_line or http.client.responses.get(status, '<STR_LIT>')).strip()<EOL>self.send_response(status, status_line)<EOL>message = (message or status_line)<EOL>if isinstance(message, (str, bytes)):<EOL><INDENT>self.send_header('<STR_LIT>', len(message))<EOL>self.end_headers()<EOL>if isinstance(message, str):<EOL><INDENT>self.wfile.write(message.encode(sys.getdefaultencoding()))<EOL><DEDENT>else:<EOL><INDENT>self.wfile.write(message)<EOL><DEDENT><DEDENT>elif hasattr(message, '<STR_LIT>'):<EOL><INDENT>fs = os.fstat(message.fileno())<EOL>self.send_header('<STR_LIT>', fs[<NUM_LIT:6>])<EOL>self.end_headers()<EOL>shutil.copyfileobj(message, self.wfile)<EOL><DEDENT>else:<EOL><INDENT>self.end_headers()<EOL><DEDENT>return<EOL> | 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>words = filter(None, words)<EOL>tmp_path = '<STR_LIT>'<EOL>for word in words:<EOL><INDENT>_, word = os.path.splitdrive(word)<EOL>_, word = os.path.split(word)<EOL>if word in (os.curdir, os.pardir):<EOL><INDENT>continue<EOL><DEDENT>tmp_path = os.path.join(tmp_path, word)<EOL><DEDENT>self.path = tmp_path<EOL>if self.path == '<STR_LIT>' and self.__config['<STR_LIT>']:<EOL><INDENT>self.send_response_full(self.__config['<STR_LIT>'])<EOL>return<EOL><DEDENT>self.cookies = http.cookies.SimpleCookie(self.headers.get('<STR_LIT>', '<STR_LIT>'))<EOL>handler, is_method = self.__get_handler(is_rpc=False)<EOL>if handler is not None:<EOL><INDENT>try:<EOL><INDENT>handler(*((query,) if is_method else (self, query)))<EOL><DEDENT>except Exception:<EOL><INDENT>self.respond_server_error()<EOL><DEDENT>return<EOL><DEDENT>if not self.__config['<STR_LIT>']:<EOL><INDENT>self.respond_not_found()<EOL>return<EOL><DEDENT>file_path = self.__config['<STR_LIT>']<EOL>file_path = os.path.join(file_path, tmp_path)<EOL>if os.path.isfile(file_path) and os.access(file_path, os.R_OK):<EOL><INDENT>self.respond_file(file_path, query=query)<EOL>return<EOL><DEDENT>elif os.path.isdir(file_path) and os.access(file_path, os.R_OK):<EOL><INDENT>if not original_path.endswith('<STR_LIT:/>'):<EOL><INDENT>destination = self.path + '<STR_LIT:/>'<EOL>if self.command == '<STR_LIT:GET>' and self.query_data:<EOL><INDENT>destination += '<STR_LIT:?>' + urllib.parse.urlencode(self.query_data, True)<EOL><DEDENT>self.respond_redirect(destination)<EOL>return<EOL><DEDENT>for index in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>index = os.path.join(file_path, index)<EOL>if os.path.isfile(index) and os.access(index, os.R_OK):<EOL><INDENT>self.respond_file(index, query=query)<EOL>return<EOL><DEDENT><DEDENT>if self.__config['<STR_LIT>']:<EOL><INDENT>self.respond_list_directory(file_path, query=query)<EOL>return<EOL><DEDENT><DEDENT>self.respond_not_found()<EOL>return<EOL> | 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 the corresponding request. | 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>':<EOL><INDENT>return False<EOL><DEDENT>auth_info = base64.b64decode(auth_info[<NUM_LIT:1>]).decode(sys.getdefaultencoding())<EOL>username = auth_info.split('<STR_LIT::>')[<NUM_LIT:0>]<EOL>password = '<STR_LIT::>'.join(auth_info.split('<STR_LIT::>')[<NUM_LIT:1>:])<EOL>password_bytes = password.encode(sys.getdefaultencoding())<EOL>if hasattr(self, '<STR_LIT>'):<EOL><INDENT>if self.custom_authentication(username, password):<EOL><INDENT>self.basic_auth_user = username<EOL>return True<EOL><DEDENT>return False<EOL><DEDENT>if not username in store:<EOL><INDENT>self.server.logger.warning('<STR_LIT>' + username)<EOL>return False<EOL><DEDENT>password_data = store[username]<EOL>if password_data['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>if password == password_data['<STR_LIT:value>']:<EOL><INDENT>self.basic_auth_user = username<EOL>return True<EOL><DEDENT><DEDENT>elif hashlib.new(password_data['<STR_LIT:type>'], password_bytes).digest() == password_data['<STR_LIT:value>']:<EOL><INDENT>self.basic_auth_user = username<EOL>return True<EOL><DEDENT>self.server.logger.warning('<STR_LIT>' + username)<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT>return False<EOL> | 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_LIT:U+002C>')]<EOL>key = headers.get('<STR_LIT>', None)<EOL>digest = hashlib.sha1((key + self.guid).encode('<STR_LIT:utf-8>')).digest()<EOL>handler.send_response(<NUM_LIT>, '<STR_LIT>')<EOL>handler.send_header('<STR_LIT>', '<STR_LIT>')<EOL>handler.send_header('<STR_LIT>', '<STR_LIT>')<EOL>handler.send_header('<STR_LIT>', base64.b64encode(digest).decode('<STR_LIT:utf-8>'))<EOL>handler.end_headers()<EOL>handler.wfile.flush()<EOL>self.lock = threading.Lock()<EOL>self.connected = True<EOL>self.logger.info('<STR_LIT>')<EOL>self.on_connected()<EOL>self._last_buffer = b'<STR_LIT>'<EOL>self._last_opcode = <NUM_LIT:0><EOL>self._last_sent_opcode = <NUM_LIT:0><EOL>while self.connected:<EOL><INDENT>try:<EOL><INDENT>self._process_message()<EOL><DEDENT>except socket.error:<EOL><INDENT>self.logger.warning('<STR_LIT>')<EOL>self.close()<EOL><DEDENT>except Exception:<EOL><INDENT>self.logger.error('<STR_LIT>', exc_info=True)<EOL>self.close()<EOL><DEDENT><DEDENT>self.handler.close_connection = <NUM_LIT:1><EOL> | :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.handler.wfile.flush()<EOL>self.on_closed()<EOL> | 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>buffer += struct.pack('<STR_LIT:B>', <NUM_LIT> + opcode)<EOL>if length <= <NUM_LIT>:<EOL><INDENT>buffer += struct.pack('<STR_LIT:B>', length)<EOL><DEDENT>elif <NUM_LIT> <= length <= <NUM_LIT>:<EOL><INDENT>buffer += struct.pack('<STR_LIT>', <NUM_LIT>, length)<EOL><DEDENT>else:<EOL><INDENT>buffer += struct.pack('<STR_LIT>', <NUM_LIT>, length)<EOL><DEDENT>buffer += message<EOL>self._last_sent_opcode = opcode<EOL>self.lock.acquire()<EOL>try:<EOL><INDENT>self.handler.wfile.write(buffer)<EOL>self.handler.wfile.flush()<EOL><DEDENT>except Exception:<EOL><INDENT>self.logger.error('<STR_LIT>', exc_info=True)<EOL>self.close()<EOL><DEDENT>finally:<EOL><INDENT>self.lock.release()<EOL><DEDENT> | 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_pong, message)<EOL><DEDENT>elif opcode == self._opcode_pong:<EOL><INDENT>pass<EOL><DEDENT>elif opcode == self._opcode_binary:<EOL><INDENT>self.on_message_binary(message)<EOL><DEDENT>elif opcode == self._opcode_text:<EOL><INDENT>try:<EOL><INDENT>message = self._decode_string(message)<EOL><DEDENT>except UnicodeDecodeError:<EOL><INDENT>self.logger.warning('<STR_LIT>')<EOL>self.close()<EOL><DEDENT>else:<EOL><INDENT>self.on_message_text(message)<EOL><DEDENT><DEDENT>elif opcode == self._opcode_continue:<EOL><INDENT>self.close()<EOL><DEDENT>else:<EOL><INDENT>self.logger.warning("<STR_LIT>".format(opcode))<EOL>self.close()<EOL><DEDENT> | 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_LIT>' + self._compression<EOL><DEDENT> | :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><DEDENT>else:<EOL><INDENT>key, value = (part, None)<EOL><DEDENT>options[key] = value<EOL><DEDENT><DEDENT>if name.endswith('<STR_LIT>'):<EOL><INDENT>options['<STR_LIT>'] = '<STR_LIT>'<EOL>name = name[:-<NUM_LIT:5>]<EOL><DEDENT>return cls(name, charset=options.get('<STR_LIT>', '<STR_LIT>'), compression=options.get('<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>return data<EOL> | 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(self._charset)<EOL><DEDENT>data = g_serializer_drivers[self.name]['<STR_LIT>'](data, (self._charset if sys.version_info[<NUM_LIT:0>] == <NUM_LIT:3> else None))<EOL>if isinstance(data, list):<EOL><INDENT>data = tuple(data)<EOL><DEDENT>return data<EOL> | 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_LIT>, True))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if os.getuid():<EOL><INDENT>addresses.insert(<NUM_LIT:0>, ('<STR_LIT>', <NUM_LIT>, False))<EOL><DEDENT>else:<EOL><INDENT>addresses.insert(<NUM_LIT:0>, ('<STR_LIT>', <NUM_LIT>, False))<EOL><DEDENT><DEDENT><DEDENT>elif address:<EOL><INDENT>addresses.insert(<NUM_LIT:0>, (address[<NUM_LIT:0>], address[<NUM_LIT:1>], ssl_certfile is not None))<EOL><DEDENT>self.ssl_certfile = ssl_certfile<EOL>self.ssl_keyfile = ssl_keyfile<EOL>if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>self.logger = logging.getLogger('<STR_LIT>')<EOL><DEDENT>self.__should_stop = threading.Event()<EOL>self.__is_shutdown = threading.Event()<EOL>self.__is_shutdown.set()<EOL>self.__is_running = threading.Event()<EOL>self.__is_running.clear()<EOL>self.__server_thread = None<EOL>self.__wakeup_fd = None<EOL>self.__config = {<EOL>'<STR_LIT>': None,<EOL>'<STR_LIT>': b'<STR_LIT>',<EOL>'<STR_LIT>': False,<EOL>'<STR_LIT>': True, <EOL>'<STR_LIT>': os.getcwd(),<EOL>'<STR_LIT>': True,<EOL>'<STR_LIT>': '<STR_LIT>' + __version__<EOL>}<EOL>self.sub_servers = []<EOL>"""<STR_LIT>"""<EOL>if use_threads:<EOL><INDENT>server_klass = ServerThreaded<EOL><DEDENT>else:<EOL><INDENT>server_klass = ServerNonThreaded<EOL><DEDENT>for address in addresses:<EOL><INDENT>server = server_klass((address[<NUM_LIT:0>], address[<NUM_LIT:1>]), handler_klass, config=self.__config)<EOL>use_ssl = (len(address) == <NUM_LIT:3> and address[<NUM_LIT:2>])<EOL>server.using_ssl = use_ssl<EOL>self.sub_servers.append(server)<EOL>self.logger.info("<STR_LIT>".format(address[<NUM_LIT:0>], address[<NUM_LIT:1>]) + ('<STR_LIT>' if use_ssl else '<STR_LIT>'))<EOL><DEDENT>self._ssl_sni_entries = None<EOL>if any([server.using_ssl for server in self.sub_servers]):<EOL><INDENT>self._ssl_sni_entries = {}<EOL>if ssl_version is None or isinstance(ssl_version, str):<EOL><INDENT>ssl_version = resolve_ssl_protocol_version(ssl_version)<EOL><DEDENT>self._ssl_ctx = ssl.SSLContext(ssl_version)<EOL>self._ssl_ctx.load_cert_chain(ssl_certfile, keyfile=ssl_keyfile)<EOL>if g_ssl_has_server_sni:<EOL><INDENT>self._ssl_ctx.set_servername_callback(self._ssl_servername_callback)<EOL><DEDENT>for server in self.sub_servers:<EOL><INDENT>if not server.using_ssl:<EOL><INDENT>continue<EOL><DEDENT>server.socket = self._ssl_ctx.wrap_socket(server.socket, server_side=True, do_handshake_on_connect=False)<EOL><DEDENT><DEDENT>if hasattr(handler_klass, '<STR_LIT>'):<EOL><INDENT>self.logger.debug('<STR_LIT>')<EOL>self.auth_set(True)<EOL><DEDENT> | :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 threaded handler.
:param str ssl_certfile: An SSL certificate file to use, setting this enables SSL.
:param str ssl_keyfile: An SSL certificate file to use.
:param ssl_version: The SSL protocol version to use. | 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(ssl_keyfile)<EOL><DEDENT>cert_info = SSLSNICertificate(hostname, ssl_certfile, ssl_keyfile)<EOL>if ssl_version is None or isinstance(ssl_version, str):<EOL><INDENT>ssl_version = resolve_ssl_protocol_version(ssl_version)<EOL><DEDENT>ssl_ctx = ssl.SSLContext(ssl_version)<EOL>ssl_ctx.load_cert_chain(ssl_certfile, keyfile=ssl_keyfile)<EOL>self._ssl_sni_entries[hostname] = SSLSNIEntry(context=ssl_ctx, certificate=cert_info)<EOL> | 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 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 use of arguments to
:py:meth:`~.__init__`.
.. versionadded:: 2.0.0
:param str hostname: The hostname for this configuration.
:param str ssl_certfile: An SSL certificate file to use, setting this enables SSL.
:param str ssl_keyfile: An SSL certificate file to use.
:param ssl_version: The SSL protocol version to use. | 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 use of arguments to
:py:meth:`~.__init__`.
.. versionadded:: 2.2.0
:param str hostname: The hostname to delete the SNI configuration for. | 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.__wakeup_fd = WakeupFd()<EOL>self.__is_shutdown.clear()<EOL>self.__should_stop.clear()<EOL>self.__is_running.set()<EOL>while not self.__should_stop.is_set():<EOL><INDENT>try:<EOL><INDENT>self._serve_ready()<EOL><DEDENT>except socket.error:<EOL><INDENT>self.logger.warning('<STR_LIT>')<EOL>self.__should_stop.set()<EOL><DEDENT><DEDENT>self.__is_shutdown.set()<EOL>self.__is_running.clear()<EOL>return <NUM_LIT:0><EOL> | 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()<EOL><DEDENT>if self.__wakeup_fd is not None:<EOL><INDENT>self.__wakeup_fd.close()<EOL>self.__wakeup_fd = None<EOL><DEDENT>for server in self.sub_servers:<EOL><INDENT>server.shutdown()<EOL><DEDENT> | 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