import json,os,sys
def HttpGet(url,timeout = 10):
"""
发送GET请求
@url 被请求的URL地址(必需)
@timeout 超时时间默认60秒
return string
"""
if sys.version_info[0] == 2:
try:
import urllib2,ssl
if sys.version_info[0] == 2:
reload(urllib2)
reload(ssl)
try:
ssl._create_default_https_context = ssl._create_unverified_context
except:pass;
response = urllib2.urlopen(url,timeout=timeout)
return response.read()
except Exception as ex:
return str(ex);
else:
try:
import urllib.request,ssl
try:
ssl._create_default_https_context = ssl._create_unverified_context
except:pass;
response = urllib.request.urlopen(url,timeout=timeout)
result = response.read()
if type(result) == bytes: result = result.decode('utf-8')
return result
except Exception as ex:
return str(ex)
def HttpPost(url,data,timeout = 10):
"""
发送POST请求
@url 被请求的URL地址(必需)
@data POST参数,可以是字符串或字典(必需)
@timeout 超时时间默认60秒
return string
"""
if sys.version_info[0] == 2:
try:
import urllib,urllib2,ssl
ssl._create_default_https_context = ssl._create_unverified_context
data = urllib.urlencode(data)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req,timeout = timeout)
return response.read()
except Exception as ex:
return str(ex);
else:
try:
import urllib.request,ssl
try:
ssl._create_default_https_context = ssl._create_unverified_context
except:pass;
data = urllib.parse.urlencode(data).encode('utf-8')
req = urllib.request.Request(url, data)
response = urllib.request.urlopen(req,timeout = timeout)
result = response.read()
if type(result) == bytes: result = result.decode('utf-8')
return result
except Exception as ex:
return str(ex);
def md5(strings):
"""
生成MD5
@strings 要被处理的字符串
return string(32)
"""
import hashlib
m = hashlib.md5()
m.update(strings.encode('utf-8'))
return m.hexdigest()
def GetRandomString(length):
"""
取随机字符串
@length 要获取的长度
return string(length)
"""
from random import Random
strings = ''
chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
chrlen = len(chars) - 1
random = Random()
for i in range(length):
strings += chars[random.randint(0, chrlen)]
return strings
def ReturnJson(status,msg,args=()):
"""
取通用Json返回
@status 返回状态
@msg 返回消息
return string(json)
"""
return GetJson(ReturnMsg(status,msg,args));
def ReturnMsg(status,msg,args = ()):
return {'status':status,'msg':msg,'data':args}
def GetJson(data):
"""
将对象转换为JSON
@data 被转换的对象(dict/list/str/int...)
"""
from json import dumps
if data == bytes: data = data.decode('utf-8')
return dumps(data)
def getJson(data):
return GetJson(data)
def writeFile(filename,s_body,mode='w+'):
"""
写入文件内容
@filename 文件名
@s_body 欲写入的内容
return bool 若文件不存在则尝试自动创建
"""
try:
fp = open(filename, mode,encoding="utf-8");
fp.write(s_body)
fp.close()
return True
except:
try:
fp = open(filename, mode,encoding="utf-8");
fp.write(s_body)
fp.close()
return True
except:
return False
#获取识别码
def get_uuid():
import uuid
return uuid.UUID(int=uuid.getnode()).hex[-12:]