Python数据库访问公共组件及模拟Http请求
前言
最近一段時間除了忙于工作之外,在業余時,迷上了python,對它的跨平臺深深的吸引。經過一段時間的自我學習,了解了其基本的語法,便開始自己著手擺弄起來。主要想把以前對接的接口再實現一次,以便于在做中發現問題,解決問題。只看不做,沒有實際的操練,永遠都是紙上談兵。在此過程中遇到了許多問題,通過不斷查詢資料和請教基本完善了功能。現將自我覺得比較重要的部分拿出來和大家一起探討一下,也順便自己對此做個記錄!
模擬Http請求
在請求別人接口時,我們最常使用的是模擬Http請求。在python中有許多方式,我選用了新版的httplib2。有興趣的可以查看一下其他文檔。
# encoding: utf-8 __author__ = 'changyang' ''' @author: changyang @software: PyCharm @file: httphelper.py @time: 2015/12/14 10:48 @function:http請求操作''' import httplib2,json#get def get(url):return handler(url,None,'GET')#post def post(url,data):return handler(url,data,'POST')#統一處理http函數 def handler(url,data,method):try:httpClient=httplib2.Http()headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}if data!=None:data=json.dumps(data)response,content=httpClient.request(uri=url,method=method,body=data,headers=headers)return content.decode('utf-8')except Exception as e:print(e)if __name__=='__main__':print('choice http method...')Mysql數據庫訪問類
由于使用.net習慣了,還真不知道怎樣描述,大家理解意思就行。是在不知道怎樣說了,直接上代碼。
# encoding: utf-8 __author__ = 'changyang' ''' @author: changyang @software: PyCharm @file: mysql_helper.py @time: 2015/12/24 16:15 @function:數據庫訪問幫助類 ''' import mysql.connectorclass MySqlHelper(object):def __init__(self,config_mysql):self.create_connector(config_mysql)#創建數據庫連接def create_connector(self,config_mysql):try:self.connector= mysql.connector.connect(host=config_mysql['host'],user=config_mysql['user'],password=config_mysql['password'],database=config_mysql['database'],port=config_mysql['port'],charset='utf8',buffered=True)self.cursor=self.connector.cursor(buffered=True)except Exception as e:print('myql connector is error:%s' % e)#插入單條信息,parameters為元組,sql語句中的占位符必須與參數的順序相同,且sql語句中以‘%s’進行占位def insert(self,sql,parameters):try:if sql==None or sql=='':return 0self.cursor.execute(sql,parameters)self.connector.commit()return self.cursor.rowcountexcept Exception as e:print('insert is error:%s' % e)finally:self.cursor.close()self.connector.close()#一次性插入多條數據,parameters為數組,每個元素都是一個元組,元組內容的順序必須與sql語句中的占位符相同,且sql語句中以‘%s’進行占位def multiinsert(self,sql,parameters):try:if sql==None or sql=='':return 0self.cursor.executemany(sql,parameters)self.connector.commit()return self.cursor.rowcountexcept Exception as e:print('multiinsert is error:%s' % e)finally:self.cursor.close()self.connector.close()#分頁查詢,parameters為元組,sql語句中的占位符必須與參數的順序相同,且sql語句中以‘%s’進行占位#可用于分頁查詢,但是需要在sql語句中進行分頁def findlimit(self,sql,parameters,size):try:if sql==None or sql=='':return 0self.cursor.execute(sql,parameters)allcount=self.cursor.rowcountlist=Noneif size!=0:list= self.cursor.fetchmany(size)else:list= self.cursor.fetchall()return list,allcountexcept Exception as e:print('findlimit is error:%s' % e)finally:self.connector.commit()self.cursor.close()self.connector.close()#查詢全部,parameters為元組,sql語句中的占位符必須與參數的順序相同,且sql語句中以‘%s’進行占位def findall(self,sql,parameters):return self.findlimit(sql,parameters,0)這里我使用了配置文件,便于后期管理,其實說白了,也就是一個數組。直接上配置
configs_mysql={'host':'ip地址','user':'賬號','password':'密碼','database':'數據庫','port':端口號}其他比較重要的訪問類
xml和json相互轉化:
# encoding: utf-8 __author__ = 'changyang' ''' @author: changyang @software: PyCharm @file: json_to_xml.py @time: 2015/12/15 9:57 @function:json轉化為xml ''' import xmltodict,json#xml轉化為json def xml_to_json(str):if str=='':raise 'str is null'str=xmltodict.parse(str)return json.dumps(str)#json轉化為xml def json_to_xml(str):if str=='':raise 'str is null'str={'Ticket':json.loads(str)}return xmltodict.unparse(str,encoding='utf-8',full_document=True)if __name__=='__main__':xml = """ <student><stid>10213</stid><info><name>name</name><mail>xxx@xxx.com</mail><sex>male</sex></info><course><name>math</name><age>90</age></course><course><name>english</name><age>88</age></course> </student> """result=xml_to_json(xml)print(result)print(json_to_xml(result))?
文件操作
# encoding: utf-8 __author__ = 'changyang' ''' @author: changyang @software: PyCharm @file: file_helper.py @time: 2015/12/15 8:49 @function:文件操作 ''' import sys,time,os,shutil#保存xml文件并寫入內容 def save(path_type,filename,content):try:path=get_common_path(path_type)if not os.path.exists(path):os.makedirs(path)filename='%s\%s' % (path,filename)if os.path.exists(filename):os.remove(filename)with open(filename, "w",encoding='utf-8') as f:f.write(content)except Exception as e:print(e) #移除文件類型下的所有文件 def remove(path_type):try:path=get_common_path(path_type)if os.path.exists(path):shutil.rmtree(path,True)except Exception as e:print(e)#獲取當前門票xml路徑 def getpath(xml,path_type):return get_common_path(path_type,xml)?
2015的最后總結
2015有許多未完成的,還有一些已經完成的。在自己生日這天,訂了車,算是走出了第一步。此后一直堅持給母親每個月打錢回去,開始存錢準備買房的艱辛道路。在這年中,還有許多該看的書未完成,還有許多值得提升的地方還在進行中。一直對數據比較感興趣,所以最近一直在自學python。也許自己有一些底子,但只能說是觸類旁通吧。還有待自己去多加實踐。我是一個不善言辭的人,也不知道該說些什么,只是按照自己的目前,一步一步走下去的,相信不會讓自己失望的。
2016,加油!
轉載于:https://www.cnblogs.com/zcy-xy/p/5082092.html
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
以上是生活随笔為你收集整理的Python数据库访问公共组件及模拟Http请求的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: android Studio 配置LUA
 - 下一篇: C语言中的字符和字符串