一本久久综合亚洲鲁鲁五月天亚洲欧美一区二区,国产精品国色综合久久,国产亚洲美女精品久久久2020http://www.shnenglu.com/socketref/category/6607.htmlgis,mouse,luolasizh-cnWed, 01 Jul 2015 16:09:08 GMTWed, 01 Jul 2015 16:09:08 GMT60salesforce的oauth授權http://www.shnenglu.com/socketref/archive/2015/06/29/211090.html放屁阿狗 放屁阿狗 Mon, 29 Jun 2015 12:21:00 GMThttp://www.shnenglu.com/socketref/archive/2015/06/29/211090.htmlhttp://www.shnenglu.com/socketref/comments/211090.htmlhttp://www.shnenglu.com/socketref/archive/2015/06/29/211090.html#Feedback0http://www.shnenglu.com/socketref/comments/commentRss/211090.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/211090.html訪問sf,記錄下一下代碼

(注冊sf的app,登記 callback-url,執行sql查詢)
#coding:utf-8
__author__ = 'scott'
import imp
imp.load_source('init','../init_script.py')
import urllib2,urllib,json,sys,os
import traceback,threading,time,struct,os,os.path,shutil,distutils.dir_util,array,base64,zlib,struct,binascii
import datetime
from libs.python.lemon import webapi
callback = 'http://localhost:8002/oauth'
client_id = '3MVG9ZL0ppGP5UrC_wQ8U02mOhowPKwjeaaLsWZ3BcYYVqiSsy1rL_D2h6qG.rGPnb_j6IcgLHPdhmvomzDFj'
client_secret = '9046731979xxxxxxx'

def accessToken(request,code,state):
    url = 'https://login.salesforce.com/services/oauth2/token'
    data = {
        'grant_type':'authorization_code',
        'code':code,
        'client_id':client_id,
        'client_secret':client_secret,
        'redirect_uri':callback
    }
    result = ''
    try:
        result = urllib2.urlopen(url,urllib.urlencode(data) )
    except:
        traceback.print_exc()
    result = result.read()
    return json.loads( result )

def oauth(request):
    cr = webapi.SuccCallReturn()
    code =  webapi.GET(request,'code','')
    state = webapi.GET(request,'state','')
    cr.result=[code,state]
    token = accessToken(request,code,state)
    cr.result.append(token)
    print token
    try:
        sqlExecute(token['access_token'],token['instance_url'])
    except:
        traceback.print_exc()
    return cr.httpResponse()

import cookielib

# -H "Authorization: OAuth token" -H "X-PrettyPrint:1" "
def sqlExecute(token,url_host):
    httpHandler = urllib2.HTTPHandler(debuglevel=1)
    httpsHandler = urllib2.HTTPSHandler(debuglevel=1)
    opener = urllib2.build_opener(httpHandler, httpsHandler)
    urllib2.install_opener(opener)
    sf_cmd_query="%s/services/data/v20.0/query/?%s"%(url_host, urllib.urlencode({'q':'select count() from account'}))
    headers = {
        'Authorization':'OAuth %s'%token,
        'X-PrettyPrint':1
    }
    httpReq = urllib2.Request( sf_cmd_query,headers=headers )
    r = opener.open(httpReq).read()
    print r
    pass

url1 = """https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=%s&redirect_uri=%s&state=first"""%(client_id,callback)

def launchBrowserForOAuth():
    import webbrowser
    webbrowser.open(url1)

if __name__ == '__main__':
    launchBrowserForOAuth()


放屁阿狗 2015-06-29 20:21 發表評論
]]>
python::簡單數據對象到Object自動轉換http://www.shnenglu.com/socketref/archive/2015/05/26/210748.html放屁阿狗 放屁阿狗 Tue, 26 May 2015 06:44:00 GMThttp://www.shnenglu.com/socketref/archive/2015/05/26/210748.htmlhttp://www.shnenglu.com/socketref/comments/210748.htmlhttp://www.shnenglu.com/socketref/archive/2015/05/26/210748.html#Feedback0http://www.shnenglu.com/socketref/comments/commentRss/210748.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/210748.htmlpython內部數據容器有dict和list兩種 ,工作中最常用的方式是定義一些數據結構(數據即代碼),例如: 

1 frog={'name':'scott',
2           'age':2,
3           'parts':{
4                     'eye':'green','leg':85
5                     },
6           ''friend":['moee','wee'],
7           "hometown":'affica'
8          }

frog對象定義了小動物的某些屬性,訪問frog對象屬性時,通過 dict,list的取值方法進行訪問,例如:  
print frog['name']
print frog['friend'][0]  
有時覺得這種表達方式太原始了,需要改進,最好是以 '.'方式訪問對象屬性,例如:  
print frog.name
代碼來開始和結束吧, class _x 
 1 class _x:
 2     """
 3     從簡單數據類型轉換成python對象
 4 
 5     p = _x({'name':'boob','body':{'color':'black'},'toys':[1,2,3,],'age':100})
 6     print p['toys'][1]
 7     print len(p.toys)
 8     print p.body.colors
 9     """
10     def __init__(self,primitive):
11         self.data = primitive
12 
13     def __getattr__(self, item):
14         value = self.data.get(item,None)
15         if type(value) == dict:
16             value = _x(value)
17         return value
18 
19     def __len__(self):
20         return len(self.data)
21 
22     def __str__(self):
23         return str(self.data)
24 
25     def __getitem__(self, item):
26         value = None
27         if type(self.data) in (list,tuple):
28             value = self.data[item]
29             if type(value) in (dict,list,tuple):
30                 value = _x(value)
31         elif type(self.data) == dict:
32             value = self.__getattr__(item)
33         return value









放屁阿狗 2015-05-26 14:44 發表評論
]]>
python::配置文件簡單讀取 SimpleConfighttp://www.shnenglu.com/socketref/archive/2013/04/02/199040.html放屁阿狗 放屁阿狗 Tue, 02 Apr 2013 05:36:00 GMThttp://www.shnenglu.com/socketref/archive/2013/04/02/199040.htmlhttp://www.shnenglu.com/socketref/comments/199040.htmlhttp://www.shnenglu.com/socketref/archive/2013/04/02/199040.html#Feedback0http://www.shnenglu.com/socketref/comments/commentRss/199040.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/199040.html 1 class SimpleConfig:
 2     def __init__(self):
 3         self.confile =''
 4         self.props={}
 5 
 6     def load(self,file):
 7         try:
 8             f = open(file,'r')
 9             lines = f.readlines()
10             f.close()
11             self.props={}
12             for line in lines:
13                 line = line.strip()
14                 if not line or line[0]=='#':
15                     continue
16                 line = line.split('#')[0]
17                 pp = line.split('=')
18                 if len(pp)!=2:
19                     continue
20                 k,v = pp[0].strip(),pp[1].strip()
21                 self.props[k] = v
22         except:
23             traceback.print_exc()
24             self.props ={}
25         return True
26 
27     def get(self,key,default=None):
28         return self.props.get(key,default)

放屁阿狗 2013-04-02 13:36 發表評論
]]>
python::代碼學習http://www.shnenglu.com/socketref/archive/2012/07/10/182547.html放屁阿狗 放屁阿狗 Tue, 10 Jul 2012 02:04:00 GMThttp://www.shnenglu.com/socketref/archive/2012/07/10/182547.htmlhttp://www.shnenglu.com/socketref/comments/182547.htmlhttp://www.shnenglu.com/socketref/archive/2012/07/10/182547.html#Feedback0http://www.shnenglu.com/socketref/comments/commentRss/182547.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/182547.html
看看這個代碼,摘錄自gameobject
 1   def __init__(self, x=0., y=0.):
 2         """Initialise a vector
 3 
 4         @type x: number
 5         @param x: The x value (defaults to 0.), or a container of 2 values
 6         @type x: number
 7         @param y: The y value (defaults to 0.)
 8 
 9         """
10         if hasattr(x, "__getitem__"):
11             x, y = x
12             self._v = [float(x), float(y)]
13         else:
14             self._v = [float(x), float(y)]
挺好的,參數帶入可以支持 a(1,2)形式,也可支持a( (1,2) )形式 ,非常靈活,自已以前總是想不到用hasattr來判斷




放屁阿狗 2012-07-10 10:04 發表評論
]]>
python編寫網絡通信框架-基于線程的消息傳送http://www.shnenglu.com/socketref/archive/2012/03/08/167450.html放屁阿狗 放屁阿狗 Thu, 08 Mar 2012 15:12:00 GMThttp://www.shnenglu.com/socketref/archive/2012/03/08/167450.htmlhttp://www.shnenglu.com/socketref/comments/167450.htmlhttp://www.shnenglu.com/socketref/archive/2012/03/08/167450.html#Feedback0http://www.shnenglu.com/socketref/comments/commentRss/167450.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/167450.html閱讀全文

放屁阿狗 2012-03-08 23:12 發表評論
]]>
gis:ks102 設備解碼http://www.shnenglu.com/socketref/archive/2012/03/08/167401.html放屁阿狗 放屁阿狗 Thu, 08 Mar 2012 07:23:00 GMThttp://www.shnenglu.com/socketref/archive/2012/03/08/167401.htmlhttp://www.shnenglu.com/socketref/comments/167401.htmlhttp://www.shnenglu.com/socketref/archive/2012/03/08/167401.html#Feedback0http://www.shnenglu.com/socketref/comments/commentRss/167401.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/167401.html  1 # -- coding:utf-8 --  2...  閱讀全文

放屁阿狗 2012-03-08 15:23 發表評論
]]>
gis::ks108設備接入解碼http://www.shnenglu.com/socketref/archive/2012/03/08/167400.html放屁阿狗 放屁阿狗 Thu, 08 Mar 2012 07:20:00 GMThttp://www.shnenglu.com/socketref/archive/2012/03/08/167400.htmlhttp://www.shnenglu.com/socketref/comments/167400.htmlhttp://www.shnenglu.com/socketref/archive/2012/03/08/167400.html#Feedback0http://www.shnenglu.com/socketref/comments/commentRss/167400.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/167400.html  1 # -- coding:utf-8 --  2 #解碼器定...  閱讀全文

放屁阿狗 2012-03-08 15:20 發表評論
]]>
Ogr::簡化LineString輸出到shp文件http://www.shnenglu.com/socketref/archive/2012/03/02/166927.html放屁阿狗 放屁阿狗 Thu, 01 Mar 2012 17:04:00 GMThttp://www.shnenglu.com/socketref/archive/2012/03/02/166927.htmlhttp://www.shnenglu.com/socketref/comments/166927.htmlhttp://www.shnenglu.com/socketref/archive/2012/03/02/166927.html#Feedback1http://www.shnenglu.com/socketref/comments/commentRss/166927.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/166927.htmlOGR1.6 above
python2.4 above

只需要定義fields,roads數據調用serial_shpdata_road()即可一次輸出到shp文件
不適合大批量坐標一次生成shp
ogr的問題在于python代碼中初始化layer之后傳遞到其他函數使用將會導致莫名錯誤,應該是個bug

 1    #bin.zhang@sw2us.com
 2     fields=[
 3         {'name':'roadname','type':FIELD_STRING,'width':30}
 4     ]
 5     roads=[
 6         {
 7             'geom':[(121.1,31.1),(121.101,31.102),(121.101,31.2)],
 8             'attrs':('xscott.test',)
 9         }
10     ]
11     serial_shpdata_road('d:/temp3/aa.shp',fields,roads)
12 '''
13 def serial_shpdata_road(file,fields,roads):
14     '''
15         fields: [{name,type,width},]
16         roads - [{'geom':[(x,y),..],'wkt':'','attrs':[name,type,len,]},..]
17     '''
18     layer = None
19     
20     if os.path.exists(file):
21         os.remove(file)
22         
23     makePrjFile(file)
24     ds = driver.CreateDataSource(file)
25     layer = ds.CreateLayer("road",geom_type=ogr.wkbMultiLineString)
26     for f in fields:
27         fld = ogr.FieldDefn(f['name'],f['type'])
28         
29         if f['type'] == FIELD_STRING :
30             w = 30
31             if f.has_key('width'):
32                 w = f['width']
33             fld.SetWidth(w)
34         layer.CreateField(fld)
35     ftrdfn = layer.GetLayerDefn()
36     
37     for r in roads:
38         g = None
39         if r.has_key('wkt'):
40             g = ogr.CreateGeometryFromWkt(r['wkt'])
41         if r.has_key('geom'):
42             pts = r['geom']
43             pts = map(lambda pt: '%s %s'%(pt[0],pt[1]),pts)
44             txt = string.join(pts,',')
45             wkt = "MULTILINESTRING((%s))"%txt
46             g = ogr.CreateGeometryFromWkt(wkt)
47         
48         ftr = ogr.Feature(ftrdfn)
49         ftr.SetGeometry(g)
50         for n in range(len(r['attrs'])):
51             at = r['attrs'][n]
52             ftr.SetField(n,at)
53         layer.CreateFeature(ftr)
54     layer.SyncToDisk()
55    


放屁阿狗 2012-03-02 01:04 發表評論
]]>
如何Python編寫COM serverhttp://www.shnenglu.com/socketref/archive/2012/03/01/166843.html放屁阿狗 放屁阿狗 Thu, 01 Mar 2012 02:24:00 GMThttp://www.shnenglu.com/socketref/archive/2012/03/01/166843.htmlhttp://www.shnenglu.com/socketref/comments/166843.htmlhttp://www.shnenglu.com/socketref/archive/2012/03/01/166843.html#Feedback0http://www.shnenglu.com/socketref/comments/commentRss/166843.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/166843.html手頭的項目涉及不同部門的成果,還要與公司產品做無縫接入,必然要用到ctypes,qt,com之類的東西了
數據編碼采用json或者xml
以com方式提供生產系統訪問接口,直覺告訴我實現會有點問題,那就是python+Qt做com組件,這個組件與影像系統通信,
com組件訪問顯示qt的ui界面會存在問題,沒有做過嘗試,不知是否能行
Com方式提供服務采用獨立服務器模式還是獨立的組件模式(其實是個線程模型問題,獨立進程的com server還是加載到應用app進程的com object)

花點時間琢磨去........

放屁阿狗 2012-03-01 10:24 發表評論
]]>
python::寫ctypes的好幫手pyglet.wrap.pyhttp://www.shnenglu.com/socketref/archive/2012/03/01/166842.html放屁阿狗 放屁阿狗 Thu, 01 Mar 2012 02:16:00 GMThttp://www.shnenglu.com/socketref/archive/2012/03/01/166842.htmlhttp://www.shnenglu.com/socketref/comments/166842.htmlhttp://www.shnenglu.com/socketref/archive/2012/03/01/166842.html#Feedback1http://www.shnenglu.com/socketref/comments/commentRss/166842.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/166842.html要用ctypes當然要看文檔了,里面定義結構必須自己手動寫,POINTER,Structure之類的,好煩!
運氣來了,無意之間找到個pyglet的項目里面有個tools/wrap.py的東西,還是個式樣性質的東西,并沒有在他的發行代碼中,但可訪問他的svn可以獲取到,wrap.py輸入一個.h的文件便可自動生成對應的數據結構,試了一下avcodec.h,立馬出來個avcodec.py,爽啊


放屁阿狗 2012-03-01 10:16 發表評論
]]>
Ogr轉換shp秒到度單位http://www.shnenglu.com/socketref/archive/2012/02/02/164810.html放屁阿狗 放屁阿狗 Wed, 01 Feb 2012 18:14:00 GMThttp://www.shnenglu.com/socketref/archive/2012/02/02/164810.htmlhttp://www.shnenglu.com/socketref/comments/164810.htmlhttp://www.shnenglu.com/socketref/archive/2012/02/02/164810.html#Feedback0http://www.shnenglu.com/socketref/comments/commentRss/164810.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/164810.html
  1 #--coding:utf-8---
  2 #  brief:  內業shp數據,轉換秒到度為單位
  3 # author: scott
  4 # date: 2012.1.30    
  5 # org:  --navi.com
  6 # 
  7 # version: v0.1.0 2012.2.1
  8 #  1.create doc and test ok, types (included point|line|polygon|multipolygon) be supported
  9 # 
 10 
 11 import os,os.path,sys,time,copy,shutil
 12 from osgeo import ogr
 13 
 14 
 15 def do_layerPoint(layer):
 16     ftr = layer.ResetReading()
 17     ftr = layer.GetNextFeature()    
 18     print 'point num:',layer.GetFeatureCount()
 19     print 'extent:',layer.GetExtent()
 20     cc = 1
 21     while ftr:
 22         #print cc
 23         cc+=1
 24         pt = ftr.GetGeometryRef().GetPoint(0)
 25         g = ftr.GetGeometryRef()
 26         #print g#,g.ExportKML()
 27         if pt[0] >1000 or pt[1> 1000:
 28             g.SetPoint(0,pt[0]/3600.,pt[1]/3600.)
 29             #print g
 30             
 31             '''
 32             ng = ogr.Geometry(ogr.wkbPoint)
 33             print pt
 34             ng.SetPoint(0,pt[0]+40,pt[1])
 35             ftr.SetGeometry(ng)        
 36             '''
 37             layer.SetFeature(ftr)
 38         ftr = layer.GetNextFeature()    
 39 
 40 def do_layerLine(layer):
 41     ftr = layer.ResetReading()
 42     ftr = layer.GetNextFeature()
 43     
 44     while ftr:    
 45         g = ftr.GetGeometryRef()
 46         cnt = g.GetPointCount()
 47         cc = 0
 48         while cc < cnt:
 49             #print g.GetPoint(cc)
 50             cc+=1
 51         
 52         for n in range(cnt):
 53             pt = g.GetPoint(n)
 54             if pt[0]>1000 or pt[1> 1000:
 55                 g.SetPoint(n,pt[0]/3600.,pt[1]/3600.0)
 56         layer.SetFeature(ftr)
 57         
 58         ftr = layer.GetNextFeature()
 59 
 60 def do_layerPolygon(layer):
 61     ftr = layer.ResetReading()
 62     ftr = layer.GetNextFeature()
 63     
 64     while ftr:    
 65         g = ftr.GetGeometryRef()    
 66         cnt = g.GetGeometryCount()
 67         for n in range(cnt):
 68             gg = g.GetGeometryRef(n)
 69             for m in range(gg.GetPointCount() ):
 70                 pt = gg.GetPoint(m)
 71                 #print pt
 72                 if pt[0]>1000 or pt[1> 1000:
 73                     gg.SetPoint(m,pt[0]/3600.,pt[1]/3600.0)
 74         layer.SetFeature(ftr)
 75         ftr = layer.GetNextFeature()        
 76         
 77 def do_shpfile(file):
 78     #print file
 79     print 'ready file:',file
 80     driver = ogr.GetDriverByName('ESRI Shapefile')
 81     #shp = driver.Open('e:/shp_data/points.shp',1)  # 0 - read , 1 - write 
 82     shp = driver.Open(file,1)  # 0 - read , 1 - write 
 83     
 84     layer = shp.GetLayer()
 85     
 86     if layer.GetFeatureCount() == 0:
 87         return 
 88     
 89     gtyp = layer.GetLayerDefn().GetGeomType()
 90     
 91     if file.lower().find('province'== -1:
 92         pass #return 
 93         
 94     if gtyp == ogr.wkbPoint:
 95         do_layerPoint(layer)
 96     elif gtyp == ogr.wkbLineString:
 97         do_layerLine(layer)
 98     elif gtyp == ogr.wkbPolygon:
 99         do_layerPolygon(layer)
100     else:
101         print 'unknown type:',gtyp,'  ',file
102     
103     layer.SyncToDisk()    
104     shp.Destroy()
105     
106     
107 def convert(shpdir):
108     files = os.listdir(shpdir)
109     for file in files:
110         if  file.lower().find('.shp'==-1:
111             continue
112         
113         #if file == 'points.shp':
114         do_shpfile(shpdir+"/"+file)
115 
116 if __name__=='__main__':
117     #convert( 'e:/shp_data' )
118     if sys.argv[1:]:
119         convert(sys.argv[1])
120     else:
121         convert( 'D:/temp3/mess/MESH/H51F009012')
122    


放屁阿狗 2012-02-02 02:14 發表評論
]]>
python::增加fetchoneDict()http://www.shnenglu.com/socketref/archive/2011/12/29/163052.html放屁阿狗 放屁阿狗 Wed, 28 Dec 2011 17:34:00 GMThttp://www.shnenglu.com/socketref/archive/2011/12/29/163052.htmlhttp://www.shnenglu.com/socketref/comments/163052.htmlhttp://www.shnenglu.com/socketref/archive/2011/12/29/163052.html#Feedback0http://www.shnenglu.com/socketref/comments/commentRss/163052.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/163052.html

import
 sys,sqlite3,os
def fetchoneDict(cr):
    ff 
= [ r[0] for r in cr.description ]
    rr 
= cr.fetchone()
    
if rr:
        
return dict( zip(ff,rr)  )
    
return {}

cnn 
=  sqlite3.connect('e:/tax.db3')
print dir(sqlite3)
cr 
= cnn.execute('select * from core_bill')

while 1:
    r 
= fetchoneDict(cr)
    
if not r: break
    
print r


放屁阿狗 2011-12-29 01:34 發表評論
]]>
人事抄稅數據轉換(python)http://www.shnenglu.com/socketref/archive/2011/08/30/154680.html放屁阿狗 放屁阿狗 Tue, 30 Aug 2011 03:28:00 GMThttp://www.shnenglu.com/socketref/archive/2011/08/30/154680.htmlhttp://www.shnenglu.com/socketref/comments/154680.htmlhttp://www.shnenglu.com/socketref/archive/2011/08/30/154680.html#Feedback0http://www.shnenglu.com/socketref/comments/commentRss/154680.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/154680.html
  1 # -*- coding:utf-8 -*-
  2 # soctt.bin created  2011.8.29
  3 # sw2us.com @2011 
  4 #
  5 
  6 import sys,os,os.path,time,struct,traceback,threading,datetime,string,datetime,calendar
  7 import xlrd
  8 
  9 start_year=0
 10 start_month= 0
 11 start_day =1 
 12 end_day = start_day 
 13 
 14 end_year= 0
 15 end_month = 0
 16 
 17 employee_importFile=u'111111111.XLS'
 18 tax_importFile=u'題橋工資格式.xls'
 19 
 20 employee_exportFile=u'empolyees.txt'
 21 tax_exportFile=u'personTax.txt'
 22 employeelistfile='employee_simplelist.txt'
 23 
 24 fixDeduct = 2000.00 #扣除額
 25 
 26 #人員歸檔
 27 def employeeAchive():
 28     title = u'工號~~姓名~~證件類型~~證件號~~性別~~出生日期~~國家、地區~~開票標志~~申報方式~~職務~~地址~~含稅標志~~郵政編碼~~調入調離~~備注'
 29     #rowfmt = u"%s~~ %s~~  1       ~~%s    ~~0   ~~%s      ~~142       ~~1       ~~0       ~~    ~~    ~~1       ~~        ~~0       ~~0"
 30     rowfmt = u"%s~~ %s~~  1       ~~%s    ~~0   ~~%s      ~~142       ~~1       ~~0       ~~    ~~    ~~1       ~~        ~~0       ~~0"
 31     rowfmt = rowfmt.replace(' ','')
 32     
 33     wb = xlrd.open_workbook(employee_importFile) 
 34     sh = wb.sheet_by_index(0)
 35     file = open(employee_exportFile,'w')
 36     title = title.encode('gbk')
 37     file.write(title)
 38     file.write('\n')
 39     
 40     file2 = open(employeelistfile,'w'#清單表2
 41     for r in range(1,sh.nrows):
 42         v = sh.row_values(r)
 43         v = map(string.strip,v)
 44         
 45         
 46         birth = ''
 47         try:
 48             y,m,d = v[4].split('-')
 49             birth = "%04d%02d%02d"%(int(y),int(m),int(d))
 50         except:
 51             print u'出生年月空缺 (%s,%s)'%(v[1],v[2])
 52         
 53         txt = rowfmt%(v[1],v[2],v[5],birth)
 54         txt = txt.encode('gbk')
 55         #print len(txt)
 56         file.write(txt+'\n')
 57         
 58         txt = "%s~~%s~~%s\n"%(v[1],v[2],v[5])
 59         txt = txt.encode('gbk')
 60         
 61         file2.write(txt)
 62         
 63     file.close()
 64     file2.close()
 65     
 66 
 67 def precess_parameters():
 68     global start_year,start_month,end_year,end_month,start_day,end_day
 69     
 70     cur = datetime.datetime.now()
 71     start_year = cur.year
 72     start_month = cur.month
 73     #print len(sys.argv)
 74     if len(sys.argv) == 4 and sys.argv[1]=='tax':
 75         start_year = int(sys.argv[2]) 
 76         start_month = int(sys.argv[3])
 77     
 78     start_day = 1
 79     x,end_day= calendar.monthrange(start_year,start_month)
 80     
 81     
 82     
 83 def salaryTax():
 84     global start_year,start_month,end_year,end_month,start_day,end_day
 85     
 86     precess_parameters()
 87 
 88     hashemployee = {}
 89     file = open(employeelistfile,'r')
 90     lines = file.readlines()
 91     file.close()
 92     for line in lines:
 93         line = line.strip().split('~~')
 94         k = line[0]
 95         v = line[2]
 96         hashemployee[k] = v
 97     #以上建立員工查找表
 98     
 99     
100     title = u'證件類型~~證件號碼~~稅目代碼~~含稅標志~~所屬期起~~所屬期止~~天數~~收入額~~扣除額~~應繳稅額~~國家地區~~減免稅額~~實繳稅額'
101     #rowfmt = u"1     ~~%s      ~~010000  ~~1       ~~%s      ~~%s      ~~%s  ~~%s    ~~%s    ~~%s      ~~142     ~~0       ~~%s"
102     rowfmt =  u"1     ~~%s      ~~010000  ~~1       ~~%s      ~~%s      ~~%s  ~~%s    ~~%s    ~~%s      ~~142     ~~0       ~~%s"
103     rowfmt = rowfmt.replace(' ','')
104     
105     wb = xlrd.open_workbook(tax_importFile) 
106     sh = wb.sheet_by_index(0)
107     file = open(tax_exportFile,'w')
108     title = title.encode('gbk')
109     file.write(title)
110     file.write('\n')
111     
112     for r in range(1,sh.nrows):
113         v = sh.row_values(r)
114         
115         v = map(unicode,v)
116         v = map(string.strip,v)
117         sid = '' #身份證編號
118         try:        
119             sid = hashemployee[v[1]]
120         except:
121             print u'處理異常中斷: 工號不能匹配! 工號: %s'%(v[1])
122             return 
123             sys.exit(0)
124         start = "%04d%02d%02d"%(start_year,start_month,start_day)
125         end = "%04d%02d%02d"%(start_year,start_month,end_day)        
126         txt = rowfmt%(sid,start,end, end_day-start_day+1,v[22],fixDeduct,v[24],v[24] ) #應發工資 W(v[22])
127         txt = txt.encode('gbk')        
128         file.write(txt+'\n')
129     file.close()
130     
131 
132 if __name__=='__main__':
133     employeeAchive()
134     salaryTax()
135    


放屁阿狗 2011-08-30 11:28 發表評論
]]>
cx_Oracle訪問oracle 10g ,弄了半天才搞定http://www.shnenglu.com/socketref/archive/2011/07/19/151341.html放屁阿狗 放屁阿狗 Mon, 18 Jul 2011 16:54:00 GMThttp://www.shnenglu.com/socketref/archive/2011/07/19/151341.htmlhttp://www.shnenglu.com/socketref/comments/151341.htmlhttp://www.shnenglu.com/socketref/archive/2011/07/19/151341.html#Feedback0http://www.shnenglu.com/socketref/comments/commentRss/151341.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/151341.htmlcxoracle版本與oracle instantclient版本 必須嚴格匹配(花了很多時間)

http://cx-oracle.sourceforge.net/    

oracle 10g
cx_Oracle-5.1-10g.win32-py2.6.msi
instantclient-basic-win32-10.2.0.4.zip
解壓instantclient-basic-win32-10.2.0.4.zip ,并將此目錄設置為ORACLE_HOME
將instantclient-basic-win32-10.2.0.4目錄內的dll拷貝到c:\python26\lib\site_packages
運行oracle_test.py測試是否能連接到遠程oracle服務

import cx_Oracle
dsn_tns = cx_Oracle.makedsn('192.168.14.203', 1521,'ORCL')   -- ORCL為遠端oracle配置的listener的名稱
print cx_Oracle.connect('tax','tax',dsn_tns)


放屁阿狗 2011-07-19 00:54 發表評論
]]>
gps::ks-102設備協議接入代碼http://www.shnenglu.com/socketref/archive/2011/06/16/148810.html放屁阿狗 放屁阿狗 Thu, 16 Jun 2011 13:56:00 GMThttp://www.shnenglu.com/socketref/archive/2011/06/16/148810.htmlhttp://www.shnenglu.com/socketref/comments/148810.htmlhttp://www.shnenglu.com/socketref/archive/2011/06/16/148810.html#Feedback0http://www.shnenglu.com/socketref/comments/commentRss/148810.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/148810.html  1 # -- coding:utf-8 --  2 #TK102 解碼器定義  ...  閱讀全文

放屁阿狗 2011-06-16 21:56 發表評論
]]>
gps::ks-108設備協議接入代碼http://www.shnenglu.com/socketref/archive/2011/06/15/148721.html放屁阿狗 放屁阿狗 Wed, 15 Jun 2011 08:54:00 GMThttp://www.shnenglu.com/socketref/archive/2011/06/15/148721.htmlhttp://www.shnenglu.com/socketref/comments/148721.htmlhttp://www.shnenglu.com/socketref/archive/2011/06/15/148721.html#Feedback0http://www.shnenglu.com/socketref/comments/commentRss/148721.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/148721.html  1 # -- coding:utf-8 --  2 #解碼器定義  3 &nbs...  閱讀全文

放屁阿狗 2011-06-15 16:54 發表評論
]]>
python寫xmlhttp://www.shnenglu.com/socketref/archive/2011/06/06/148166.html放屁阿狗 放屁阿狗 Mon, 06 Jun 2011 15:23:00 GMThttp://www.shnenglu.com/socketref/archive/2011/06/06/148166.htmlhttp://www.shnenglu.com/socketref/comments/148166.htmlhttp://www.shnenglu.com/socketref/archive/2011/06/06/148166.html#Feedback0http://www.shnenglu.com/socketref/comments/commentRss/148166.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/148166.html

import xml.dom.minidom
from xml.dom.DOMImplementation import implementation
import xml.sax.writer
import xml.utils

# Create a new document with no namespace uri, qualified name,
# or document type
document = implementation.createDocument(None,None,None)
personnel = document.createElement("personnel")
personnel.setAttribute('number', '5')
document.appendChild(personnel)
sexnode = document.createElement("sex")
sexnode.appendChild(document.createTextNode("male"))

namenode = document.createElement("name")
namenode.appendChild(document.createTextNode("tianbin"))

personnel.appendChild(sexnode)
personnel.appendChild(namenode)

out = open("tianbin.xml", "w")
xml.dom.ext.PrettyPrint(document,out)



放屁阿狗 2011-06-06 23:23 發表評論
]]>
python字符轉換,老忘http://www.shnenglu.com/socketref/archive/2011/05/28/147477.html放屁阿狗 放屁阿狗 Sat, 28 May 2011 08:38:00 GMThttp://www.shnenglu.com/socketref/archive/2011/05/28/147477.htmlhttp://www.shnenglu.com/socketref/comments/147477.htmlhttp://www.shnenglu.com/socketref/archive/2011/05/28/147477.html#Feedback0http://www.shnenglu.com/socketref/comments/commentRss/147477.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/147477.html

decode的作用是將其他編碼的字符串轉換成unicode編碼,如str1.decode('gb2312'),表示將gb2312編碼的字符串轉換成unicode編碼。

encode的作用是將unicode編碼轉換成其他編碼的字符串,如str2.encode('gb2312'),表示將unicode編碼的字符串轉換成gb2312編碼。



放屁阿狗 2011-05-28 16:38 發表評論
]]>
交易系統備份方案http://www.shnenglu.com/socketref/archive/2011/01/25/139285.html放屁阿狗 放屁阿狗 Tue, 25 Jan 2011 08:20:00 GMThttp://www.shnenglu.com/socketref/archive/2011/01/25/139285.htmlhttp://www.shnenglu.com/socketref/comments/139285.htmlhttp://www.shnenglu.com/socketref/archive/2011/01/25/139285.html#Feedback0http://www.shnenglu.com/socketref/comments/commentRss/139285.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/139285.html每天安排6次備份,這種對于一個程序開發者來講的話真是一種痛苦和侮辱。

今天空下來就用python開始編寫自動備份方案:
1.http自動登錄
2.wget斷點下載
3.7zip壓縮
4.網盤 everbox的同步到服務器

與http server的交互信息用wireshark抓包分析,還蠻靈光的

python代碼:
 1 # -*- coding:utf-8 -*-
 2 #auto backup system database 
 3 #自動登錄,http下載,壓縮之后通過網盤同步到服務器
 4 
 5 import httplib, urllib,sys,os,re,datetime,time,os.path,gzip
 6 
 7 host="192.168.1.106"
 8 sys_user='anyuser'
 9 sys_pass='anypass'
10 
11 html = '''<body><h1>Object Moved</h1>This object may be found <a HREF="shuju.asp?err=
12 ok!&amp;dizhi=../data_backup/zhk0432011-1-26.7055475.mdb">here</a>.</body>
13 '''
14 
15 
16 tasklet=[]
17 backupTimes= 6# in day 每天備份次數
18 
19 
20 
21 def backup(outputfile):
22     params = urllib.urlencode({'login_name':sys_user, 'login_pass': sys_pass, 'submit.x'9,'submit.y':9})
23     conn = httplib.HTTPConnection(host)
24     headers = {"Content-type""application/x-www-form-urlencoded",
25                 "Accept""text/plain"}
26     conn.request("POST","/asp/huiyuan/login_check_gl.asp",params,headers)
27     resp = conn.getresponse()
28     #print resp.status,resp.reason
29     #print resp.getheaders()
30     cookie = resp.getheader('set-cookie')
31     #print resp.read()
32     conn.close()
33 
34     #print 'retry GET /'
35     conn = httplib.HTTPConnection(host)
36     headers = {"Content-type""application/x-www-form-urlencoded",
37                 "Accept""text/plain",'Cookie':cookie}
38 
39     conn.request("GET","/asp/admin/login_check001.asp",'',headers)
40     resp = conn.getresponse()
41 
42     #sys.exit(0)
43     conn = httplib.HTTPConnection(host)
44     headers = {"Content-type""application/x-www-form-urlencoded",
45                 "Accept""text/plain",'Cookie':cookie}
46 
47     conn.request("GET","/asp/admin/backup.asp",'',headers)
48     resp = conn.getresponse()
49     #print resp.status,resp.reason
50     html=  resp.read()
51 
52     m = re.search(".*?/data_backup/(.*?\.mdb).*",html)
53     backupfile = ''
54     if len(m.groups()):
55         backupfile = m.groups()[0]
56         print backupfile
57     else:
58         print 'backup access failed!'
59         return False
60 # -o wget.log
61     downloadurl= "http://%s/asp/data_backup/%s  -O %s "%(host,backupfile,outputfile)
62     #print 'try get %s '%downloadurl
63     cmd = "wget -c -t 0 %s"%downloadurl
64     print cmd
65     os.system(cmd)
66     return True
67 
68 firsttime = datetime.datetime.now()
69 if not os.path.exists('./backup'):
70     os.mkdir('backup')
71     
72 if not os.path.exists('./sync'):
73     os.mkdir('sync')
74     
75 while True:
76     now = datetime.datetime.now()
77     #filename = "backup/%s_%s-%s_%s_%s_%s.bak"%(now.year,now.month,now.day,now.hour,now.minute,now.second)    
78     sync_hour= int(now.hour/int(24/backupTimes)) * int(24/backupTimes)
79     filename = "%s_%s-%s_%s_%s_%s.bak"%(now.year,now.month,now.day,sync_hour,0,0)    
80     try:
81         if not os.path.exists("backup/"+filename):        
82             backup("backup/"+filename)
83             cmd = "7zip\\7z.exe a -t7z  sync\\%s.7z backup\\%s"%(filename,filename)
84             print cmd
85             os.system(cmd)    
86     except:
87         pass
88     time.sleep(10#
89 
90 
91 
92 




放屁阿狗 2011-01-25 16:20 發表評論
]]>
python @staticmethod @classmethod http://www.shnenglu.com/socketref/archive/2010/12/08/135795.html放屁阿狗 放屁阿狗 Wed, 08 Dec 2010 05:42:00 GMThttp://www.shnenglu.com/socketref/archive/2010/12/08/135795.htmlhttp://www.shnenglu.com/socketref/comments/135795.htmlhttp://www.shnenglu.com/socketref/archive/2010/12/08/135795.html#Feedback0http://www.shnenglu.com/socketref/comments/commentRss/135795.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/135795.html2.普通對象函數至少需要一個self參數,該參數命名可以是‘self’,也可以是其他。代表類實例對象
3.class方法至少需要一個cls參數,該參數命名可以是‘cls’,也可以是其他。代表類對象




放屁阿狗 2010-12-08 13:42 發表評論
]]>
http Server 簡單測試,返回圖像數據http://www.shnenglu.com/socketref/archive/2010/11/19/134062.html放屁阿狗 放屁阿狗 Fri, 19 Nov 2010 01:57:00 GMThttp://www.shnenglu.com/socketref/archive/2010/11/19/134062.htmlhttp://www.shnenglu.com/socketref/comments/134062.htmlhttp://www.shnenglu.com/socketref/archive/2010/11/19/134062.html#Feedback-2http://www.shnenglu.com/socketref/comments/commentRss/134062.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/134062.html 1 #################################
 2 # swMap Test 
 3 # scott  
 4 # 2010.11.19
 5 # wallizard.vicp.net sw2us.com
 6 #################################
 7 #simplest http server 
 8 # expose image 
 9 #
10 
11 import BaseHTTPServer,SocketServer,SimpleHTTPServer 
12 import time,sys,os,os.path
13   
14 
15 class MyThreadServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): pass
16 
17 '''
18 HTTP/1.1 200 OK
19 Cache-Control: private, max-age=30
20 Content-Type: text/html; charset=utf-8
21 Content-Encoding: gzip
22 Expires: Mon, 25 May 2009 03:20:33 GMT
23 Last-Modified: Mon, 25 May 2009 03:20:03 GMT
24 Vary: Accept-Encoding
25 Server: Microsoft-IIS/7.0
26 X-AspNet-Version: 2.0.50727
27 X-Powered-By: ASP.NET
28 Date: Mon, 25 May 2009 03:20:02 GMT
29 Content-Length: 12173
30 '''
31 '''
32 Pragma:no-cache
33 Cache-Control:no-cache
34 '''
35 
36 class MyHander(SimpleHTTPServer.SimpleHTTPRequestHandler):
37     def __init__(self,request, client_address, server):
38         SimpleHTTPServer.SimpleHTTPRequestHandler.__init__(self,request, client_address, server)
39     
40     def do_GET(self):
41         print self.headers         
42         
43         f= open('d:/nono.gif','rb')
44         image  = f.read()
45         f.close()
46         
47         self.send_response(200)
48         self.send_header( 'Server','swMapServer')
49         now = self.date_time_string(time.time())        
50         self.send_header('Date',now)
51         self.send_header('Content-Type','image/gif')
52         self.send_header('Content-Length',len(image))
53         self.end_headers()
54         
55         self.wfile.write(image)
56 
57 def run(server_class=MyThreadServer,handler_class=MyHander):
58     server_address = (''8000)
59     httpd = server_class(server_address, handler_class)
60     print 'serve on ',server_address
61     httpd.serve_forever()
62 
63     
64 run()


放屁阿狗 2010-11-19 09:57 發表評論
]]>
Python編寫同步游戲目錄http://www.shnenglu.com/socketref/archive/2010/09/30/128107.html放屁阿狗 放屁阿狗 Wed, 29 Sep 2010 16:34:00 GMThttp://www.shnenglu.com/socketref/archive/2010/09/30/128107.htmlhttp://www.shnenglu.com/socketref/comments/128107.htmlhttp://www.shnenglu.com/socketref/archive/2010/09/30/128107.html#Feedback0http://www.shnenglu.com/socketref/comments/commentRss/128107.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/128107.html閱讀全文

放屁阿狗 2010-09-30 00:34 發表評論
]]>
Python開發Http代理服務器http://www.shnenglu.com/socketref/archive/2010/09/30/128105.html放屁阿狗 放屁阿狗 Wed, 29 Sep 2010 16:16:00 GMThttp://www.shnenglu.com/socketref/archive/2010/09/30/128105.htmlhttp://www.shnenglu.com/socketref/comments/128105.htmlhttp://www.shnenglu.com/socketref/archive/2010/09/30/128105.html#Feedback2http://www.shnenglu.com/socketref/comments/commentRss/128105.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/128105.html閱讀全文

放屁阿狗 2010-09-30 00:16 發表評論
]]>
照片合并輸出http://www.shnenglu.com/socketref/archive/2010/09/22/127351.html放屁阿狗 放屁阿狗 Wed, 22 Sep 2010 11:50:00 GMThttp://www.shnenglu.com/socketref/archive/2010/09/22/127351.htmlhttp://www.shnenglu.com/socketref/comments/127351.htmlhttp://www.shnenglu.com/socketref/archive/2010/09/22/127351.html#Feedback0http://www.shnenglu.com/socketref/comments/commentRss/127351.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/127351.htmlconfig.txt配置信息
1 item_hspace=0.5
2 item_vspace=0.5
3 item_width = 20 #15cm
4 item_height = 15
5 DPI=96
6 canvas_heigth=88 #200cm
7 canvas_rotation=90 
8 source = D:\共享\2010.9.20\小天鵝幼兒園小4班照片
9 outfile=final2.tiff

main.py處理代碼
  1 #-*- coding:utf-8 -*-
  2 #
  3 #name: config.py
  4 #brief:
  5 #    系統配置文件
  6 #author: scott
  7 #
  8 
  9 
 10 import os,sys,time,os.path,traceback
 11 import zlib,binascii
 12 import PIL,Image
 13 import config
 14 
 15 DPI=96.0
 16 
 17 POINTS_PER_METER = DPI/2.54 * 100 #每米多少個像素
 18 POINT_PER_CMETER = DPI/2.54
 19 
 20 ITEM_HSPACE=0
 21 ITEM_VSPACE=1
 22 ITEM_WIDTH =#照片的寬度
 23 ITEM_HEIGTH = 0 #照片寬度決定了高度
 24 CANVAS_HEIGHT= 0 #畫板高度,長度是無限制的
 25 CANVAS_ROTATION = -90 #最終輸出照片進行旋轉輸出
 26 
 27 conf = config.SimpleConfig()
 28 conf.open('config.txt')
 29 DPI = conf.getPropertyValueAsFloat('DPI',96.0)
 30 ITEM_HSPACE = conf.getPropertyValueAsFloat('item_hspace',0.5* POINT_PER_CMETER
 31 ITEM_VSPACE = conf.getPropertyValueAsFloat('item_vspace',0.5* POINT_PER_CMETER
 32 ITEM_WIDTH = conf.getPropertyValueAsFloat('item_width',15* POINT_PER_CMETER
 33 ITEM_HEIGHT = conf.getPropertyValueAsFloat('item_height',10* POINT_PER_CMETER
 34 
 35 CANVAS_HEIGHT = conf.getPropertyValueAsFloat('canvas_heigth',200* POINT_PER_CMETER
 36 CANVAS_ROTATION = conf.getPropertyValueAsFloat('canvas_rotation',-90
 37 
 38 ITEM_HSPACE = int(ITEM_HSPACE)
 39 ITEM_VSPACE = int(ITEM_VSPACE)
 40 ITEM_WIDTH = int(ITEM_WIDTH)
 41 ITEM_HEIGHT = int(ITEM_HEIGHT)
 42 CANVAS_HEIGHT = int( CANVAS_HEIGHT)
 43 
 44 print conf.getPropertyValueAsFloat('canvas_rotation',-90)
 45 
 46 rows = CANVAS_HEIGHT / (ITEM_HEIGHT+ITEM_VSPACE)
 47 
 48 source = conf.getPropertyValue('source')
 49 final = conf.getPropertyValue('outfile')
 50 
 51 files = []
 52 
 53 imgsize=[0,0]
 54 
 55 for f in os.listdir(source):
 56     if os.path.isdir( "%s/%s"%(source,f)):
 57         continue
 58     try:
 59         imgfile = Image.open("%s/%s"%(source,f))
 60         size = imgfile.size
 61         if size[0]<size[1]:
 62             imgfile = imgfile.rotate(90)
 63             imgfile.save("%s/%s"%(source,f))
 64     except:
 65         continue
 66     files.append(    "%s/%s"%(source,f))
 67 #計算輸出文件的大小
 68 cols = len(files)/(rows)
 69 cols = int(cols)
 70 if  len(files)%(rows) != 0:
 71     cols +=1
 72     
 73 CANVAS_WIDTH = cols * (ITEM_VSPACE+ITEM_WIDTH)
 74 imgsize = (CANVAS_WIDTH,CANVAS_HEIGHT)
 75 imgcanvas = Image.new('RGB',imgsize,0xffffff)
 76 
 77 print CANVAS_WIDTH,CANVAS_HEIGHT
 78 print cols,rows
 79 
 80 for c in range(cols):
 81     x = c * (ITEM_WIDTH+ITEM_HSPACE)
 82     for r in range( int(rows)):
 83         y = r * (ITEM_HEIGHT+ITEM_VSPACE)
 84         if len(files):
 85             file = files[0]
 86             files.remove(file)
 87             try:
 88                 print 'open file:',file
 89                 imgfile = Image.open(file)
 90                 print (x,y,x+ITEM_WIDTH,y+ITEM_HEIGHT)
 91                 imgfile = imgfile.resize((ITEM_WIDTH,ITEM_HEIGHT))
 92                 imgcanvas.paste(imgfile,(x,y,x+ITEM_WIDTH,y+ITEM_HEIGHT))
 93                 
 94                 #imgcanvas.paste(imgfile,(x,y))
 95             except:
 96                 print traceback.print_exc()
 97                 #sys.exit()
 98 if CANVAS_ROTATION:
 99     print CANVAS_ROTATION
100     imgcanvas = imgcanvas.rotate(CANVAS_ROTATION)
101     pass
102     
103 imgcanvas.save(final)
104 
105 





放屁阿狗 2010-09-22 19:50 發表評論
]]>
抓www.xunbao173.com的交易記錄http://www.shnenglu.com/socketref/archive/2010/06/10/117598.html放屁阿狗 放屁阿狗 Thu, 10 Jun 2010 15:23:00 GMThttp://www.shnenglu.com/socketref/archive/2010/06/10/117598.htmlhttp://www.shnenglu.com/socketref/comments/117598.htmlhttp://www.shnenglu.com/socketref/archive/2010/06/10/117598.html#Feedback0http://www.shnenglu.com/socketref/comments/commentRss/117598.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/117598.html  1 # -*- coding:utf-8...  閱讀全文

放屁阿狗 2010-06-10 23:23 發表評論
]]>
Python::SocketServerhttp://www.shnenglu.com/socketref/archive/2010/02/15/107912.html放屁阿狗 放屁阿狗 Mon, 15 Feb 2010 15:42:00 GMThttp://www.shnenglu.com/socketref/archive/2010/02/15/107912.htmlhttp://www.shnenglu.com/socketref/comments/107912.htmlhttp://www.shnenglu.com/socketref/archive/2010/02/15/107912.html#Feedback0http://www.shnenglu.com/socketref/comments/commentRss/107912.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/107912.html
BaseServer: 定義基礎服務器接口,這些功能接口提供給子類繼承。同時提供服務處理的骨架
   serve_forever()  循環調用 handle_request()
   handle_request()  調用子類的get_request() ,在tcpServer時實則進行accept()應答; 驗證處理 verify_request(); 
             最終處理請求 process_request(),
   verify_request()   虛函數
   process_request()  虛函數,這個函數并沒有直接在BaseServer的子類TcpServer中被重載,而是在TcpServer的派生類中通過另一個父類來實
現,比如 ThreadingTCPServer的基類ThreadingMixIn.process_request()實現了此功能函數
   finish_request(request, client_address) 執行一次完整的socket數據讀入處理,如果是ThreadMixInTcpServer產生的request,這個方法內必須實行循環讀取socket數據,直到socket關閉。(此處 request 就是 socket對象)
 def finish_request(self, request, client_address):
        
"""Finish one request by instantiating RequestHandlerClass."""
        self.RequestHandlerClass(request, client_address, self)
   在finish_request里面便將讀取socket數據的任務扔給了RequestHandler去處理了,代碼可以跳過去看了
##---------------------------------------------

TcpServer:  tcp服務器
   __init__(self, server_address, RequestHandlerClass) 需要提供服務偵聽地址和請求處理類對象
   server_bind() 綁定服務器地址
   server_activate() 激活服務器
   server_close()  關閉服務器
   fileno()  返回服務器socket的句柄fd編號
   get_request() 接收應答accept()
   close_request(request) 關閉socket,request即為socket對象
 
三種輸出處理方式: 阻塞方式、線程處理(ThreadingMixIn)、進程處理(ForkingMixIn)

ThreadingMixIn: 線程模型
   process_request( request, client_address) 為請求的鏈接創建新的線程,在創建線程時直接指定線程入口和參數:
      
import threading
= threading.Thread(target = self.process_request_thread,
     args 
= (request, client_address))
if self.daemon_threads:
  t.setDaemon (
1)
   process_request_thread() 線程處理socket入口,負責接收數據,代碼實現有點繞,看看代碼
def process_request_thread(self, request, client_address):
        
try:
            self.finish_request(request, client_address)
            self.close_request(request)
        
except:
            self.handle_error(request, client_address)
            self.close_request(request)
    ThreadingMixIn其實就是線程代理,還是調用finish_request()進入處理tcp數據的循環,處理完成便close_request()。但是finish_request和close_request并未在ThreadingMinxIn內定義,在哪里呢? 通過研讀ThreadingTcpServer,原來通過ThreadingTcpServer這個finish_request又跑回了BaseServer.finish_request()

ThreadingTCPServer(ThreadingMixIn, TCPServer) 裝配成線程池處理的tcp服務器
  

BaseRequestHandler:  請求處理基礎對象,提供統一的行為接口實現處理socket數據。 BaseRequestHandler比較好玩,在構造函數內完成了所有的操作,見代碼:
def __init__(self, request, client_address, server):
        self.request 
= request
        self.client_address 
= client_address
        self.server 
= server
        
try:
            self.setup()
            self.handle()
            self.finish()
        
finally:
            sys.exc_traceback 
= None    # Help garbage collection
   setup()對應的子類會進行初始化處理
   self.handle()  直接調用子類的處理函數,可以參考 BaseHTTPRequestHandler(SocketServer.StreamRequestHandler)::handle()


StreamRequestHandler(BaseRequestHandler) 流式socket處理類
   setup() 設置好socket對象和讀寫文件句柄 rfile/wfile


HTTPServer(SocketServer.TCPServer) http服務器

BaseHTTPRequestHandler(SocketServer.StreamRequestHandler) 流式的請求處理類
   handle() 處理入口,在基類BaseRequestHandle()的構造函數中直接調用
   handle_one_request() 如果不是處理一次則返回false。接收一次socket數據,解析parse_request(),調用對應的do_xxx事件

python 的daemon線程:
如果一個進程的主線程運行完畢而子線程還在執行的話,那么進程就不會退出,直到所有子線程結束為止,如何讓主線程結束的時候其他子線程也乖乖的跟老大撤退呢?那就要把那些不聽話的人設置為聽話的小弟,使用線程對象的setDaemon()方法,參數為bool型。True的話就代表你要聽話,我老大(主線程)扯呼,你也要跟著撤,不能拖后腿。如果是False的話就不用那么聽話了,老大允許你們將在外軍命有所不受的。需要注意的是setDaemon()方法必須在線程對象沒有調用start()方法之前調用,否則沒效果。
  



放屁阿狗 2010-02-15 23:42 發表評論
]]>
python連接DB2http://www.shnenglu.com/socketref/archive/2008/07/04/55281.html放屁阿狗 放屁阿狗 Thu, 03 Jul 2008 17:28:00 GMThttp://www.shnenglu.com/socketref/archive/2008/07/04/55281.htmlhttp://www.shnenglu.com/socketref/comments/55281.htmlhttp://www.shnenglu.com/socketref/archive/2008/07/04/55281.html#Feedback1http://www.shnenglu.com/socketref/comments/commentRss/55281.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/55281.html項目的工期比較緊,同時我也不想花太多的時間研究數據庫訪問接口,所以在項目中許多模塊都是用python編寫,開發周期短,調試,跨平臺也是很吸引人,所以就用python拉。在python.org一搜索,便找到了pydb2,OK! 馬上下載pydb1.2,一解開壓縮包,原來是原代碼,只能編譯拉。還好有編譯腳本:), 運行setup.py install
出現以下異常:
Compiling under Visual Studio .NET v7 recieves the
following error:

_db2_module.c(1855) : error C2036: 'SQLPOINTER' :
unknown size

This can be resolved by casting to (SQLCHAR *) instead
of a (void *):

< SQLPOINTER buf = (SQLPOINTER)((SQLCHAR
*)bs->buf + (bs->bufLen * idx));

發現原來SQLCHAR類型沒有找到,沒問題,找到_db2_module.c:1855行修改為:
SQLPOINTER buf = (SQLPOINTER)((void *)bs->buf +
(bs->bufLen * idx));
再次 setup.py install
ok,編譯成功,db2.py的模塊也被拷貝得到 $PYTHONHOME/lib/site_pakages/下去了
然后安裝db2 client runtime
這樣就完成了pydb2的運行配置。然后就在odbc中配置一個dsn
測試以下代碼:

import DB2
conn = DB2.connect(dsn='sample', uid='db2inst1', pwd='secret')
無異常表示成功連接上DB2
之后訪問數據庫只要遵循python DBI2.0的規范就可以拉!
生活在python世界是很快樂的事情!

*注意: python2.4的話必須用vc7.1編譯pydb2的擴展模塊,因為python2.4(win32)也是用vc7.1編譯的





放屁阿狗 2008-07-04 01:28 發表評論
]]>
lua-快速閱讀http://www.shnenglu.com/socketref/archive/2008/05/13/49689.html放屁阿狗 放屁阿狗 Mon, 12 May 2008 19:13:00 GMThttp://www.shnenglu.com/socketref/archive/2008/05/13/49689.htmlhttp://www.shnenglu.com/socketref/comments/49689.htmlhttp://www.shnenglu.com/socketref/archive/2008/05/13/49689.html#Feedback0http://www.shnenglu.com/socketref/comments/commentRss/49689.htmlhttp://www.shnenglu.com/socketref/services/trackbacks/49689.htmltable 是個怪物,有很多facets,類似array,map,struct,整個是個混合物,用起來也比較怪異。
t={1,2,3,a="gen",b=100}
t={[0]=1;["name"]="ultra"}
t.a, t.b , t[0] , t["name"]

表操作函數:
ipairs,pairs迭代函數
table.getn(t)   len of table

================================================================
function() 可以接受任意多的參數,如果實參數過多將丟棄,過少將默認設置為nil
同樣可以返回多個參數
a,b=foo()

表作為參數傳遞到function
function rename( arg ) os.rename(arg.old,arg.new) end
rename{old="";new=""}

匿名函數(lambda in python )
foo = function(x) return x*2 end
局部函數 local f=function(x) ... end
================================================================
for n=start,end,step do ... end
while b do   ... end
repeat do .... until

if then .. elseif then ...  end;

有意思的語法表達式:
    print a or b or c   如果a=false,嘗試b...

注釋: --     --{ --} 


字符串操作:    .. 連接

==================================================
io 函數:
loadfile('test.lua')()    execute external lua script
loadstring('print 100')()


代碼測試:
=======================
c程序調用lua函數
c 程序:
void call_lua_func(){
    lua_State *s = lua_open();
    luaL_openlibs(s);
    int c = lua_gettop(s);
    luaL_dofile(s,"/nandflashpartition/test1.lua");
    lua_getglobal(s,"add");
    lua_pushnumber(s,0.25);
    lua_pushnumber(s,8);
    if( lua_pcall(s,2,1,0)){
        std::cout<< lua_tostring(s,-1)<<std::endl;
    }
    double r;
    r = lua_tonumber(s,-1);
    lua_close(s);
}
lua程序:
function add(x,y)
    return x*y
end
--------------------------------
lua訪問c程序空間變量

1.定義變量student.h
extern char * gender;
extern int class_count;

2.創建pkg文件 student.pkg
$#include "student.h"
extern char * gender;
extern int class_count;

3.產生tolua++存根框架
tolua++ -o student.pkg

4.創建lua測試代碼 call_c.lua
print(gender)
print(class_count)  訪問c 空間的變量

5.c測試代碼
char * gender;
int class_count;
void lua_call_c(){
    int  tolua_student_open (lua_State* tolua_S);
    lua_State * s = lua_open();
    luaopen_base(s);

    gender ="my gender is male!";
    class_count = 100;
    tolua_student_open(s);
    luaL_dofile(s,"/nandflashpartition/call_c.lua");
    lua_close(s);
}

6.build && test it!





放屁阿狗 2008-05-13 03:13 發表評論
]]>
国产精品伊人久久伊人电影 | 久久亚洲精品无码播放| 亚洲人成网站999久久久综合| 国产精品久久久久影视不卡| 亚洲精品无码专区久久同性男| 久久久久亚洲AV无码专区桃色| 热re99久久精品国产99热| 天天躁日日躁狠狠久久| 久久人做人爽一区二区三区| 久久免费香蕉视频| 久久综合给合综合久久| 欧洲性大片xxxxx久久久| 久久成人精品| 久久精品国产欧美日韩99热| 久久无码AV一区二区三区| 久久亚洲日韩看片无码| 一本一道久久综合狠狠老| 性欧美大战久久久久久久久 | 国内精品久久久久久99| 久久久久久久波多野结衣高潮| 久久久久人妻精品一区二区三区 | 国内精品伊人久久久久网站| 精品久久人人爽天天玩人人妻 | 久久强奷乱码老熟女网站| 亚洲国产精品一区二区三区久久| 伊人久久大香线焦AV综合影院| 久久国产精品成人片免费| 久久精品这里热有精品| 91精品国产高清久久久久久91| 日产久久强奸免费的看| 伊色综合久久之综合久久| 久久婷婷五月综合色奶水99啪 | 亚洲精品久久久www| 国产A级毛片久久久精品毛片| 久久综合九色综合精品| 国产精品欧美久久久久无广告| 久久久亚洲裙底偷窥综合 | 精品国产青草久久久久福利| 欧美麻豆久久久久久中文| 青青草原精品99久久精品66| 一本大道久久a久久精品综合|