def form_encode(obj,
instanceName):
"""Encodes a model in a form-encoded manner such as person[Name]
Args:
obj (object): The given Object to form encode.
instanceName (string): The base name to appear before each entry
for this object.
Returns:
dict: A dictionary of form encoded properties of the model.
"""
retval = dict()
# If we received an object, resolve it's field names.
value = APIHelper.resolve_name(obj)
if value is None:
return None
elif isinstance(value, list):
for index, entry in enumerate(value):
retval.update(APIHelper.form_encode(entry, instanceName + "[" + str(index) + "]"))
elif isinstance(value, dict):
for item in value:
retval.update(APIHelper.form_encode(value[item], instanceName + "[" + item + "]"))
else:
retval[instanceName] = obj
return retval
python类encode()的实例源码
def get_record(self):
web_show = WebShow(self.playrecords)
# return jsonpickle.encode(web_show, unpicklable=False)
return web_show
#????????
def to_json(bundle):
return jsonpickle.encode(bundle)
def json_serialize(obj):
"""JSON Serialization of a given object.
Args:
obj (object): The object to serialise.
Returns:
str: The JSON serialized string of the object.
"""
if obj is None:
return None
# Resolve any Names if it's one of our objects that needs to have this called on
if isinstance(obj, list):
value = list()
for item in obj:
try:
value.append(item.resolve_names())
except (AttributeError, TypeError):
value.append(item)
obj = value
else:
try:
obj = obj.resolve_names()
except (AttributeError, TypeError):
obj = obj
return jsonpickle.encode(obj, False)
def form_encode(obj,
instanceName):
"""Encodes a model in a form-encoded manner such as person[Name]
Args:
obj (object): The given Object to form encode.
instanceName (string): The base name to appear before each entry
for this object.
Returns:
dict: A dictionary of form encoded properties of the model.
"""
# Resolve the names first
value = APIHelper.resolve_name(obj)
retval = dict()
if value is None:
return None
# Loop through every item we need to send
for item in value:
if isinstance(value[item], list):
# Loop through each item in the list and add it by number
i = 0
for entry in value[item]:
retval.update(APIHelper.form_encode(entry, instanceName + "[" + item + "][" + str(i) + "]"))
i += 1
elif isinstance(value[item], dict):
# Loop through each item in the dictionary and add it
retval.update(APIHelper.form_encode(value[item], instanceName + "[" + item + "]"))
else:
# Add the current item
retval[instanceName + "[" + item + "]"] = value[item]
return retval
def process_bind_param(self, value, engine):
return unicode(jsonpickle.encode(value))
def get_state(self):
return jsonpickle.encode({
'start_date': self._start_date,
'static_unit_net_value': self._static_unit_net_value,
'units': self._units,
'accounts': {
name: account.get_state() for name, account in six.iteritems(self._accounts)
}
}).encode('utf-8')
def json_serialize(obj):
"""JSON Serialization of a given object.
Args:
obj (object): The object to serialise.
Returns:
str: The JSON serialized string of the object.
"""
if obj is None:
return None
# Resolve any Names if it's one of our objects that needs to have this called on
if isinstance(obj, list):
value = list()
for item in obj:
if hasattr(item, "_names"):
value.append(APIHelper.to_dictionary(item))
else:
value.append(item)
obj = value
else:
if hasattr(obj, "_names"):
obj = APIHelper.to_dictionary(obj)
return jsonpickle.encode(obj, False)
def form_encode(obj,
instance_name,
array_serialization="indexed"):
"""Encodes a model in a form-encoded manner such as person[Name]
Args:
obj (object): The given Object to form encode.
instance_name (string): The base name to appear before each entry
for this object.
array_serialization (string): The format of array parameter serialization.
Returns:
dict: A dictionary of form encoded properties of the model.
"""
retval = []
# If we received an object, resolve it's field names.
if hasattr(obj, "_names"):
obj = APIHelper.to_dictionary(obj)
if obj is None:
return []
elif isinstance(obj, list):
for element in APIHelper.serialize_array(instance_name, obj, array_serialization):
retval += APIHelper.form_encode(element[1], element[0], array_serialization)
elif isinstance(obj, dict):
for item in obj:
retval += APIHelper.form_encode(obj[item], instance_name + "[" + item + "]", array_serialization)
else:
retval.append((instance_name, obj))
return retval
def toJson(obj):
json_obj = jsonpickle.encode(obj, unpicklable=False)
return json_obj
def setUp(self):
self.fake_model = tests_models.CredentialsModel()
self.fake_model_field = self.fake_model._meta.get_field('credentials')
self.field = models.CredentialsField(null=True)
self.credentials = client.Credentials()
self.pickle_str = _helpers._from_bytes(
base64.b64encode(pickle.dumps(self.credentials)))
self.jsonpickle_str = _helpers._from_bytes(
base64.b64encode(jsonpickle.encode(self.credentials).encode()))
def _make_flow(request, scopes, return_url=None):
"""Creates a Web Server Flow
Args:
request: A Django request object.
scopes: the request oauth2 scopes.
return_url: The URL to return to after the flow is complete. Defaults
to the path of the current request.
Returns:
An OAuth2 flow object that has been stored in the session.
"""
# Generate a CSRF token to prevent malicious requests.
csrf_token = hashlib.sha256(os.urandom(1024)).hexdigest()
request.session[_CSRF_KEY] = csrf_token
state = json.dumps({
'csrf_token': csrf_token,
'return_url': return_url,
})
flow = client.OAuth2WebServerFlow(
client_id=django_util.oauth2_settings.client_id,
client_secret=django_util.oauth2_settings.client_secret,
scope=scopes,
state=state,
redirect_uri=request.build_absolute_uri(
urlresolvers.reverse("google_oauth:callback")))
flow_key = _FLOW_KEY.format(csrf_token)
request.session[flow_key] = jsonpickle.encode(flow)
return flow
def get_prep_value(self, value):
"""Overrides ``models.Field`` method. This is used to convert
the value from an instances of this class to bytes that can be
inserted into the database.
"""
if value is None:
return None
else:
return encoding.smart_text(
base64.b64encode(jsonpickle.encode(value).encode()))
def json_serialize(obj):
"""JSON Serialization of a given object.
Args:
obj (object): The object to serialise.
Returns:
str: The JSON serialized string of the object.
"""
if obj is None:
return None
# Resolve any Names if it's one of our objects that needs to have this called on
if isinstance(obj, list):
value = list()
for item in obj:
try:
value.append(item.resolve_names())
except (AttributeError, TypeError):
value.append(item)
obj = value
else:
try:
obj = obj.resolve_names()
except (AttributeError, TypeError):
obj = obj
return jsonpickle.encode(obj, False)
def form_encode(obj,
instanceName):
"""Encodes a model in a form-encoded manner such as person[Name]
Args:
obj (object): The given Object to form encode.
instanceName (string): The base name to appear before each entry
for this object.
Returns:
dict: A dictionary of form encoded properties of the model.
"""
# Resolve the names first
value = APIHelper.resolve_name(obj)
retval = dict()
if value is None:
return None
# Loop through every item we need to send
for item in value:
if isinstance(value[item], list):
# Loop through each item in the list and add it by number
i = 0
for entry in value[item]:
retval.update(APIHelper.form_encode(entry, instanceName + "[" + item + "][" + str(i) + "]"))
i += 1
elif isinstance(value[item], dict):
# Loop through each item in the dictionary and add it
retval.update(APIHelper.form_encode(value[item], instanceName + "[" + item + "]"))
else:
# Add the current item
retval[instanceName + "[" + item + "]"] = value[item]
return retval
def save(self) -> None:
with open(self.dump_filename, "w", encoding='utf-8') as f:
f.write(jsonpickle.encode(self, f))
def to_json(self):
"""
:return: ???????????? ? json.
"""
return jsonpickle.encode(self)
def json_serialize(cls, obj):
"""
JSON Serialization of a given object.
Args:
obj (object): The object to serialise.
Returns:
str: The JSON serialized string of the object.
"""
if obj is None:
return None
# Resolve any Names if it's one of our objects
# that needs to have this called on
if isinstance(obj, list):
value = list()
for item in obj:
try:
value.append(item.resolve_names())
except (AttributeError, TypeError):
value.append(item)
obj = value
else:
try:
obj = obj.resolve_names()
except (AttributeError, TypeError):
obj = obj
return jsonpickle.encode(obj, False)
def form_encode(cls, obj, instanceName):
"""
Encodes a model in a form-encoded manner such as person[Name]
Args:
obj (object): The given Object to form encode.
instanceName (string): The base name to appear before each entry
for this object.
Returns:
dict: A dictionary of form encoded properties of the model.
"""
# Resolve the names first
value = APIHelper.resolve_name(obj)
retval = dict()
if value is None:
return None
# Loop through every item we need to send
for item in value:
if isinstance(value[item], list):
# Loop through each item in the list and add it by number
i = 0
for entry in value[item]:
retval.update(APIHelper.form_encode(
entry, instanceName + "[" + item + "][" + str(
i) + "]"))
i += 1
elif isinstance(value[item], dict):
# Loop through each item in the dictionary and add it
retval.update(APIHelper.form_encode(value[item], instanceName +
"[" + item + "]"))
else:
# Add the current item
retval[instanceName + "[" + item + "]"] = value[item]
return retval
def json_of_spec(spec):
return json.loads(jsonpickle.encode(spec, unpicklable=False))