def get_json_loads():
global _json_loads, _json_module_name
if _json_loads is None:
# Timings reported for a fragment file with 37177 lines
# (35634 "RECORD" and 1534 "IGNORE" records.)
try:
# 40.05 seconds
import ujson
_json_loads = ujson.decode
_json_module_name = "ujson"
except ImportError:
try:
# 41.85 seconds
import cjson
_json_loads = cjson.decode
_json_module_name = "cjson"
except ImportError:
# 55.5 seconds
_json_loads = json.loads
_json_module_name = "json"
return _json_loads
python类decode()的实例源码
def updates(callback):
"""
This function takes the callback as an input and creates an instance for each message received and stores
it(instance) into an array. Which is then returned
:param callback: contains the callback from facebook.
:return: array of Message instances.
"""
entries = []
try:
callback = json.decode(callback)
except:
pass
for entry in callback["entry"]:
messaging = entry["messaging"]
messages = [Message(data) for data in messaging]
entries.extend(messages)
return entries
def request(self, headers, payload, args, url):
while True:
proxy = self.proxyProvider.pick()
try:
response = requests.request(
"POST", url, data=payload, headers=headers,
proxies={"https": proxy.url},
timeout=5,verify=False
)
with self.lock:
with sqlite3.connect(self.db_name) as c:
try:
print(response.text)
decoded = ujson.decode(response.text)["object"]
self.done += 1
for x in decoded:
c.execute("INSERT INTO mobike VALUES (%d,"%s",%d,%d,%s,%s,%f,%f)" % (
int(time.time()) * 1000, x["bikeIds"], int(x["biketype"]), int(x["distId"]),
x["distNum"], x["type"], x["distX"],
x["distY"]))
timespend = datetime.datetime.now() - self.start_time
percent = self.done / self.total
total = timespend / percent
print(args, self.done, percent * 100, self.done / timespend.total_seconds() * 60, total,
total - timespend)
except Exception as ex:
print(ex)
break
except Exception as ex:
proxy.fatal_error()
def form(self):
result = {}
if self.request_content_length and self.request_content_type == 'application/json':
fp = self.environ['wsgi.input']
data = fp.read(self.request_content_length)
return ujson.decode(data)
try:
storage = cgi.FieldStorage(
fp=self.environ['wsgi.input'],
environ=self.environ,
strict_parsing=False,
keep_blank_values=True
)
except TypeError:
raise exceptions.HttpBadRequest('Cannot parse the request.')
if storage.list is None or not len(storage.list):
return result
def get_value(f):
# noinspection PyProtectedMember
return f.value if isinstance(f, cgi.MiniFieldStorage) \
or (isinstance(f, cgi.FieldStorage) and not f._binary_file) else f
for k in storage:
v = storage[k]
if isinstance(v, list):
result[k] = [get_value(i) for i in v]
else:
result[k] = get_value(v)
return result
def user_insert(self, member, data):
"""Create a new user entry with the given data"""
jd = self.dump({member.guild.id: data})
req = f"""INSERT INTO userdata (UUID, info) VALUES ({member.id}, '{jd}')"""
async with self._conn.acquire() as connection:
response = await connection.fetchval(req)
return json.decode(response) if response else response
def user_select(self, member):
"""Select a user's data for a specified server"""
req = f"""SELECT info -> '{member.guild.id}' FROM userdata WHERE UUID = {member.id}"""
async with self._conn.acquire() as connection:
response = await connection.fetchval(req)
return json.decode(response) if response else response
def user_full_select(self, member):
"""Select a user's data for a specified server"""
req = f"""SELECT info FROM userdata WHERE UUID = {member.id}"""
async with self._conn.acquire() as connection:
response = await connection.fetchval(req)
return json.decode(response) if response else response
def user_update(self, member, data):
"""Update a user's data for a specific server"""
jd = self.dump(data)
req = f"""UPDATE userdata
SET info = '{jd}'
WHERE UUID = {member.id}"""
async with self._conn.acquire() as connection:
response = await connection.fetchval(req)
return json.decode(response) if response else response
def get_all_user_data(self, member):
"""Get a user's data for all servers"""
req = f"""SELECT info FROM userdata WHERE UUID = {member.id}"""
async with self._conn.acquire() as connection:
response = await connection.fetchval(req)
return json.decode(response) if response else response
# Server functions
########################################################################
def guild_select(self, guild):
"""Get a guild from the db"""
req = f"""SELECT info FROM servdata WHERE UUID = {guild.id}"""
async with self._conn.acquire() as connection:
response = await connection.fetchval(req)
return json.decode(response) if response else response
def guild_update(self, guild, data):
"""Update a guild"""
jd = self.dump(data)
req = f"""UPDATE servdata
SET info = '{jd}'
WHERE UUID = {guild.id}"""
async with self._conn.acquire() as connection:
response = await connection.fetchval(req)
return json.decode(response) if response else response
def get_box(self, member):
"""Get user's Pokemon box"""
ub = await self.db.user_item(member, "box")
return [Pokemon(*x) for x in json.decode(ub)]
def get_inventory(self, member):
"""Get user's inventory"""
ui = await self.db.user_item(member, "items")
return json.decode(ui)
def get_user_info(self, user_id):
"""
The User Profile API lets your bot get more information about the user
for more info go to https://developers.facebook.com/docs/messenger-platform/user-profile
:param user_id: User id of the person of whom user info is to be retrieved.
:type user_id: str
:return: first name,last name,profile pic,locale,timezone,gender.
"""
url = self.URL.format(user_id)
key = {"fields": "first_name,last_name,profile_pic,locale,timezone,gender",
"access_token": self.Access_Token
}
response = requests.get(url, params=key)
data = response.json()
try:
data = json.decode(data)
except:
pass
try:
return data["first_name"], data["last_name"], data["profile_pic"], data["locale"], data["timezone"], data[
"gender"]
except:
return None