本文整理匯總了Python中jsonpickle.encode方法的典型用法代碼示例。如果您正苦於以下問題:Python jsonpickle.encode方法的具體用法?Python jsonpickle.encode怎麽用?Python jsonpickle.encode使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類jsonpickle
的用法示例。
在下文中一共展示了jsonpickle.encode方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: with_context
# 需要導入模塊: import jsonpickle [as 別名]
# 或者: from jsonpickle import encode [as 別名]
def with_context(params, proc):
ctx = create_context(params)
if 'args' not in params:
params['args'] = []
if 'kwargs' not in params:
params['kwargs'] = {}
res = proc(ctx)
if 'tmp_file_to_remove' in params:
remove_tmp_file.delay(params['tmp_file_to_remove'])
ctx.set_runs_on_server(False)
ctx.config.set('use_server', True, config_name='config')
return {'response': res, 'config': jsonpickle.encode(ctx.config)}
示例2: create_report
# 需要導入模塊: import jsonpickle [as 別名]
# 或者: from jsonpickle import encode [as 別名]
def create_report(self, runtime, span_records):
report = ttypes.ReportRequest(runtime, span_records, None)
for span in report.span_records:
if not span.log_records:
continue
for log in span.log_records:
index = span.log_records.index(log)
if log.payload_json is not None:
try:
log.payload_json = \
jsonpickle.encode(log.payload_json,
unpicklable=False,
make_refs=False,
max_depth=constants.JSON_MAX_DEPTH)
except:
log.payload_json = jsonpickle.encode(constants.JSON_FAIL)
span.log_records[index] = log
return report
示例3: create_child_qtable
# 需要導入模塊: import jsonpickle [as 別名]
# 或者: from jsonpickle import encode [as 別名]
def create_child_qtable(self, provider, option, transaction_hash, child_index):
"""
Creates the QTable configuration for the child agent. This is done by copying the own QTable configuration and including the new host provider, the parent name and the transaction hash.
:param provider: the name the child tree name.
:param transaction_hash: the transaction hash the child is bought with.
"""
next_state = VPSState(provider=provider, option=option)
tree = self.tree + "." + str(child_index)
dictionary = {
"environment": self.environment,
"qtable": self.qtable,
"providers_offers": self.providers_offers,
"self_state": next_state,
"transaction_hash": transaction_hash,
"tree": tree
}
filename = os.path.join(user_config_dir(), 'Child_QTable.json')
with open(filename, 'w') as json_file:
encoded_dictionary = jsonpickle.encode(dictionary)
json.dump(encoded_dictionary, json_file)
示例4: write_dictionary
# 需要導入模塊: import jsonpickle [as 別名]
# 或者: from jsonpickle import encode [as 別名]
def write_dictionary(self):
"""
Writes the QTABLE configuration to the QTable.json file.
"""
config_dir = user_config_dir()
filename = os.path.join(config_dir, 'QTable.json')
to_save_var = {
"environment": self.environment,
"qtable": self.qtable,
"providers_offers": self.providers_offers,
"self_state": self.self_state,
"tree": self.tree
}
with open(filename, 'w') as json_file:
encoded_to_save_var = jsonpickle.encode(to_save_var)
json.dump(encoded_to_save_var, json_file)
示例5: predict
# 需要導入模塊: import jsonpickle [as 別名]
# 或者: from jsonpickle import encode [as 別名]
def predict(imagepath, target_x, target_y, name, model):
if imagepath.startswith('http://') or imagepath.startswith('https://') or imagepath.startswith('ftp://'):
response = requests.get(imagepath)
img = Image.open(BytesIO(response.content))
img = img.resize((target_x, target_y))
else:
if not os.path.exists(imagepath):
raise Exception('Input image file does not exist')
img = image.load_img(imagepath, target_size=(target_x, target_y))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = processInputImage(name, x)
preds = decodePrediction(name, model.predict(x))
result = []
for p in preds[0]:
result.append({"synset": p[0], "text": p[1], "prediction": float("{0:.2f}".format((p[2] * 100)))})
return json.loads(jsonpickle.encode(result, unpicklable=False))
示例6: tokenize
# 需要導入模塊: import jsonpickle [as 別名]
# 或者: from jsonpickle import encode [as 別名]
def tokenize(data, language="english", filterStopWords = False, tagging = False):
result = {}
tags = []
filterChars = [",", ".", "?", ";", ":", "'", "!", "@", "#", "$", "%", "&", "*", "(", ")", "+", "{", "}", "[", "]", "\\", "|"]
sent_token = nltk.tokenize.sent_tokenize(data, language)
word_token = nltk.tokenize.word_tokenize(data, language)
word_token = [w for w in word_token if not w in filterChars]
if filterStopWords is True:
stop_words = set(stopwords.words(language))
word_token = [w for w in word_token if not w in stop_words]
if tagging is True:
tags = nltk.pos_tag(word_token)
result = {"sent_token": sent_token, "word_token": word_token, "pos_tag": tags}
return json.loads(jsonpickle.encode(result, unpicklable=False))
示例7: synset
# 需要導入模塊: import jsonpickle [as 別名]
# 或者: from jsonpickle import encode [as 別名]
def synset(data):
result = {}
syns = wordnet.synsets(data)
list = []
for s in syns:
r = {}
r["name"] = s.name()
r["lemma"] = s.lemmas()[0].name()
r["definition"] = s.definition()
r["examples"] = s.examples()
list.append(r)
result["list"] = list
synonyms = []
antonyms = []
for syn in syns:
for l in syn.lemmas():
synonyms.append(l.name())
if l.antonyms():
antonyms.append(l.antonyms()[0].name())
result["synonyms"] = synonyms
result["antonyms"] = antonyms
return json.loads(jsonpickle.encode(result, unpicklable=False))
示例8: predictint
# 需要導入模塊: import jsonpickle [as 別名]
# 或者: from jsonpickle import encode [as 別名]
def predictint():
message = "Success"
code = 200
result = []
try:
start = datetime.utcnow()
data = request.args.get('data')
result = intentanalyzer.predict(data)
result = json.loads(jsonpickle.encode(result, unpicklable=False))
logmgr.LogPredSuccess("intent", constants.ServiceTypes.LangIntent, start)
except Exception as e:
code = 500
message = str(e)
logmgr.LogPredError("intent", constants.ServiceTypes.LangIntent, start, message)
return jsonify({"statuscode": code, "message": message, "result": result})
示例9: writeOutSubmissionsAsHtml
# 需要導入模塊: import jsonpickle [as 別名]
# 或者: from jsonpickle import encode [as 別名]
def writeOutSubmissionsAsHtml(redditList, file):
submissionsStr = ""
for submission in redditList:
submissionsStr += submission.getHtml() + u'\n'
htmlStructure = u"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Reddit Saved Comments</title>
</head>
<body>
{0}
</body>
</html>
""".format(submissionsStr)
file.write(htmlStructure.encode('utf8'))
示例10: test_load_by_isbn
# 需要導入模塊: import jsonpickle [as 別名]
# 或者: from jsonpickle import encode [as 別名]
def test_load_by_isbn(self, mock_get):
isbn_key = 'ISBN:0137903952'
isbn_bibkeys = { isbn_key: { 'info_url': "https://openlibrary.org/books/%s/Artificial_intelligence" % self.target_olid } }
mock_get.return_value.json.side_effect = [isbn_bibkeys, self.raw_edition.copy(), self.raw_author.copy()]
actual = json.loads(jsonpickle.encode(self.ol.Edition.get(isbn=u'0137903952')))
mock_get.assert_has_calls([
call("%s/api/books.json?bibkeys=%s" % (self.ol.base_url, isbn_key)),
call().raise_for_status(),
call().json(),
call("%s/books/%s.json" % (self.ol.base_url, self.target_olid)),
call().raise_for_status(),
call().json(),
call("%s/authors/OL440500A.json" % self.ol.base_url),
call().raise_for_status(),
call().json()
])
self.assertEqual(actual, self.expected,
"Data didn't match for ISBN lookup: \n%s\n\nversus:\n\n %s" % (actual, self.expected))
示例11: _store_item_to_str
# 需要導入模塊: import jsonpickle [as 別名]
# 或者: from jsonpickle import encode [as 別名]
def _store_item_to_str(self, item: object) -> str:
return encode(item)
示例12: run
# 需要導入模塊: import jsonpickle [as 別名]
# 或者: from jsonpickle import encode [as 別名]
def run(self, params={}):
client_id = params.get("client_id")
urls = params.get("urls")
# Create individual payload arrays for use in whole payload
threat_types = self.get_threat_types(params)
platform_types = self.get_platforms(params)
threat_entries = self.make_threat_entries(urls=urls)
threat_entry_types = self.get_threat_entry_types(params)
# Create object hierarchy and payload to send to Google
client = Client(client_id=client_id)
threat_info = ThreatInfo(threatTypes=threat_types, platformTypes=platform_types,
threatEntryTypes=threat_entry_types, threatEntries=threat_entries)
request_payload = Request(client=client, threatInfo=threat_info) # Create request payload
# Marshall & serialize object hierarchy into JSON
payload = jsonpickle.encode(request_payload, unpicklable=False)
self.logger.info("Run: Created payload: {payload}".format(payload=payload))
# Send request to Google
response = requests.post(self.__URL,
data=payload,
params={"key": self.connection.API_KEY})
# Check if status code is good. If not, raise an exception and halt.
if not self.status_code_ok(status_code=response.status_code):
raise Exception("Run: Non-200 status code received, halting. (Got {status_code})"
.format(status_code=response.status_code))
# Get matches from the response. If they don't exist, then early call sys.exit.
matches = response.json().get("matches")
if not matches:
self.logger.info("Run: No matches found!")
matches = [{'threat':{'url':''}, 'threat_type':'','cache_duration':'','threat_entry_type':'','platform_type':''}]
results = 0
else:
results = len(matches)
return {"matches": matches, 'results': results}
示例13: __eq__
# 需要導入模塊: import jsonpickle [as 別名]
# 或者: from jsonpickle import encode [as 別名]
def __eq__(self, other):
if isinstance(other, type(self)):
other_encoded = jsonpickle.encode(other.as_dialogue())
encoded = jsonpickle.encode(self.as_dialogue())
return (other_encoded == encoded and
self.sender_id == other.sender_id)
else:
return False
示例14: encode
# 需要導入模塊: import jsonpickle [as 別名]
# 或者: from jsonpickle import encode [as 別名]
def encode(self, active_features, input_feature_map):
raise NotImplementedError("Featurizer must have the capacity to "
"encode features to a vector")
示例15: persist
# 需要導入模塊: import jsonpickle [as 別名]
# 或者: from jsonpickle import encode [as 別名]
def persist(self, path):
featurizer_file = os.path.join(path, "featurizer.json")
with io.open(featurizer_file, 'w') as f:
f.write(str(jsonpickle.encode(self)))