本文整理匯總了Python中json.write方法的典型用法代碼示例。如果您正苦於以下問題:Python json.write方法的具體用法?Python json.write怎麽用?Python json.write使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類json
的用法示例。
在下文中一共展示了json.write方法的7個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: process_request
# 需要導入模塊: import json [as 別名]
# 或者: from json import write [as 別名]
def process_request(packet):
pktlen=packet[0:4]
cmd=packet[4]
msg=eval(packet[5:])
msgjson=json.write(msg)
yyyymm=time.strftime('%Y%m',time.localtime(msg['ts']))
if cmd=='i': #收件箱
filename=FILENAME_INBOX%{'month':yyyymm,}
elif cmd=='t': #發件箱
filename=FILENAME_SENT%{'month':yyyymm,}
else:
print 'UNKNOWN:',repr(packet)
return
needwrite=False
if os.path.exists(filename):
ff=open(filename,'rU')
for line in ff.xreadlines():
line=line.strip()
if line==msgjson:
needwrite=False
break
else:
needwrite=True
ff.close()
else:
needwrite=True
if needwrite:
ff=open(filename,'a+')
ff.write(msgjson+'\n')
ff.close()
return
示例2: valueTreeToString
# 需要導入模塊: import json [as 別名]
# 或者: from json import write [as 別名]
def valueTreeToString(fout, value, path = '.'):
ty = type(value)
if ty is types.DictType:
fout.write('%s={}\n' % path)
suffix = path[-1] != '.' and '.' or ''
names = value.keys()
names.sort()
for name in names:
valueTreeToString(fout, value[name], path + suffix + name)
elif ty is types.ListType:
fout.write('%s=[]\n' % path)
for index, childValue in zip(xrange(0,len(value)), value):
valueTreeToString(fout, childValue, path + '[%d]' % index)
elif ty is types.StringType:
fout.write('%s="%s"\n' % (path,value))
elif ty is types.IntType:
fout.write('%s=%d\n' % (path,value))
elif ty is types.FloatType:
fout.write('%s=%.16g\n' % (path,value))
elif value is True:
fout.write('%s=true\n' % path)
elif value is False:
fout.write('%s=false\n' % path)
elif value is None:
fout.write('%s=null\n' % path)
else:
assert False and "Unexpected value type"
示例3: rewriteValueTree
# 需要導入模塊: import json [as 別名]
# 或者: from json import write [as 別名]
def rewriteValueTree(value, rewrite_path):
rewrite = json.dumps(value)
#rewrite = rewrite[1:-1] # Somehow the string is quoted ! jsonpy bug ?
file(rewrite_path, 'wt').write(rewrite + '\n')
return rewrite
示例4: save
# 需要導入模塊: import json [as 別名]
# 或者: from json import write [as 別名]
def save(self, path=None):
if path is None:
path = self.path
if path is None:
raise Exception('Path not provided!')
with open(path, 'w') as f:
json.write(self.get_config(), f)
示例5: backup_month
# 需要導入模塊: import json [as 別名]
# 或者: from json import write [as 別名]
def backup_month(start_tick,stop_tick,yyyymm):
"""備份一個月的短信"""
conn=sqlite3.connect(DB_FILENAME)
curr=conn.cursor()
sql=SQL_GETSMS%{
'start_tick':start_tick,
'stop_tick':stop_tick,}
curr.execute(sql)
dataset=curr.fetchall()
curr.close()
conn.close()
savedset=set()
if os.path.exists(INBOX_FILENAME%{'yyyymm':yyyymm}):
fr_inbox=open(INBOX_FILENAME%{'yyyymm':yyyymm},'r')
fr_sent=open(SENT_FILENAME%{'yyyymm':yyyymm},'r')
for line in fr_inbox.xreadlines():
msgdict=json.read(line)
savedset.add(msgdict['msgid'])
for line in fr_sent.xreadlines():
msgdict=json.read(line)
savedset.add(msgdict['msgid'])
fr_inbox.close()
fr_sent.close()
msglist=[]
fw_inbox=open(INBOX_FILENAME%{'yyyymm':yyyymm},'a+')
fw_sent=open(SENT_FILENAME%{'yyyymm':yyyymm},'a+')
for (starttime,flag,msg,addr) in dataset:
msgdict={
'msg':msg.encode('utf-8'),
'msgid':'%d-%s-%d'%(starttime,
addr.encode('utf-8'),len(msg)),
'ts':starttime,}
if msgdict['msgid'] in savedset:
continue
if flag==3: #sent
msgdict['tfrom']=LOCAL_PHONENUMBER
msgdict['to']=addr.encode('utf-8')
fw_sent.write(json.write(msgdict)+'\n')
elif flag==2: #inbox
msgdict['tto']=LOCAL_PHONENUMBER
msgdict['tfrom']=addr.encode('utf-8')
fw_inbox.write(json.write(msgdict)+'\n')
else:
raise ValueError('Unknown flags=%d'%flags)
fw_inbox.close()
fw_sent.close()
return
示例6: backup_month
# 需要導入模塊: import json [as 別名]
# 或者: from json import write [as 別名]
def backup_month(start_tick,stop_tick,yyyymm):
"""備份一個月的短信"""
conn=sqlite3.connect(DB_FILENAME)
curr=conn.cursor()
sql=SQL_GETSMS%{
'start_tick':start_tick,
'stop_tick':stop_tick,}
#print sql
curr.execute(sql)
dataset=curr.fetchall()
savedset=set()
if os.path.exists(INBOX_FILENAME%{'yyyymm':yyyymm}):
fr_inbox=open(INBOX_FILENAME%{'yyyymm':yyyymm},'r')
fr_sent=open(SENT_FILENAME%{'yyyymm':yyyymm},'r')
for line in fr_inbox.xreadlines():
msgdict=json.read(line)
savedset.add(msgdict['msgid'])
for line in fr_sent.xreadlines():
msgdict=json.read(line)
savedset.add(msgdict['msgid'])
fr_inbox.close()
fr_sent.close()
msglist=[]
fw_inbox=open(INBOX_FILENAME%{'yyyymm':yyyymm},'a+')
fw_sent=open(SENT_FILENAME%{'yyyymm':yyyymm},'a+')
#print 'len(dataset)=',len(dataset)
for (starttime,outgoing,freetext,remoteuid) in dataset:
#print repr(outgoing),repr(freetext),repr(starttime)
msgdict={
'msg':freetext.encode('utf-8'),
'msgid':'%d-%s-%d'%(starttime,
remoteuid.encode('utf-8'),len(freetext)),
'ts':starttime,
}
if msgdict['msgid'] in savedset:
continue
if outgoing==1:
msgdict['tfrom']=LOCAL_PHONENUMBER
msgdict['tto']=remoteuid.encode('utf-8')
fw_sent.write(json.write(msgdict)+'\n')
elif outgoing==0:
msgdict['tto']=LOCAL_PHONENUMBER
msgdict['tfrom']=remoteuid.encode('utf-8')
fw_inbox.write(json.write(msgdict)+'\n')
else:
raise ValueError('Unknow outgoing=%d'%outgoing)
#print msgdict
# do it
fw_inbox.close()
fw_sent.close()
curr.close()
conn.close()
return
示例7: _call
# 需要導入模塊: import json [as 別名]
# 或者: from json import write [as 別名]
def _call(self, cmd, data=None):
if data is None:
data = {}
data['cmd'] = cmd
data['version'] = API_VERSION
request = bytearray(json_encode(data), encoding='utf-8')
response = None
for _ in range(2):
if not self.socket and cmd != 'login':
self._call('login', self.userpwd.copy())
self.socket_lock.acquire()
try:
sock = self.connect()
response = self._sendrecv(sock, request)
except IOError as err:
sys.stderr.write(str(err) + "\n")
self.close()
except socket.error as err:
sys.stderr.write(str(err) + "\n")
self.close()
raise IOError('Connection refused')
else:
break
finally:
self.socket_lock.release()
if response is None:
raise IOError('Connection lost or timed out during API request')
try:
if PY2:
return json_decode(response.decode('utf-8'))
else:
return json_decode(response)
except Exception:
raise RuntimeError('Invalid API response')
if not response.get('error'):
return response
error = response['error']
if error in ('not-logged-in', 'invalid-credentials'):
raise AccessDeniedException('Access denied, check your credentials')
elif 'banned' == error:
raise AccessDeniedException('Access denied, account is suspended')
elif 'insufficient-funds' == error:
raise AccessDeniedException(
'CAPTCHA was rejected due to low balance')
elif 'invalid-captcha' == error:
raise ValueError('CAPTCHA is not a valid image')
elif 'service-overload' == error:
raise OverflowError(
'CAPTCHA was rejected due to service overload, try again later')
else:
self.socket_lock.acquire()
self.close()
self.socket_lock.release()
raise RuntimeError('API server error occured: %s' % error)