论坛首页 编程语言技术论坛

Python获取JE用户头像

浏览 1844 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-03-25   最后修改:2009-03-25

根据JE API说的内容,每个闲聊都附带用户信息,其中包括用户头像,这些logo不是保存在本地的,所以就需要从JE上获取,然后保存至本地,以下方法就加在core.py(http://phyeas.iteye.com/blog/352518 )中

    def getLogo(self, path=None, user=None, remote=False, localForld=APP_LOCAL_LOGO_FORLD_PATH):
        '''获取用户头像(此方法会将头像保存至本地,下次获取将获取本地图像)
        @param path:用户头像路径(服务器路径)
        @param user:用户
        @param remote: 是否从远程读取
        @param localForld: 本地存储路径 默认:config.APP_LOCAL_LOGO_FORLD_PATH
        @see: config.APP_LOCAL_LOGO_FORLD_PATH
        @return: 存储在本地的路径(str)
        '''
        if not path and not user:
            return None
        if not path and "logo" in user:
            path = user["logo"]
        localpath = self.getLocalLogoPath(path, localForld)
        
        if localpath and not remote:
            print "logo has exists in local!"
            return localpath
        request = Request(JE_URL + path)
        f = sendRequest(request)
        data = f["data"]
        #data=None
        return self.saveLogo(path, data, localForld)
            
    def saveLogo(self, path, data, localForld=APP_LOCAL_LOGO_FORLD_PATH):
        '''将头像保存至本地,生成本地序列号(文件名)
        @param path:服务器上的路径
        @param data:从服务器获取到的头像数据
        @param localForld:本地文件夹路径
        '''
        c = self.codeGenerator.generate()
        p = localForld + "/" + c
        f = open(p, "w")
        f2 = open(APP_LOCAL_LOGO_KEYS_FILE_PATH, "w")
        try:
            f.write(data)
            self.logos[path] = c
            f2.write(repr(self.logos))
        finally:
            if f:f.close()
            if f2:f2.close()
            self.codeGenerator.saveLast()
        return path
    
    def getLocalLogoPath(self, path, localForld=APP_LOCAL_LOGO_FORLD_PATH):
        '''获取服务器logo映射到本地logo的路径
        @param path:服务器路径
        @param localForld:本地存放logo文件夹
        '''
        if os.path.exists(APP_LOCAL_LOGO_KEYS_FILE_PATH):
            keysFile = open(APP_LOCAL_LOGO_KEYS_FILE_PATH, "r")
            try:
                f = keysFile.read()
                obj = eval(f)
                self.logos = obj if obj else self.logos
            except Exception, e:
                print e
            finally:
                if keysFile:keysFile.close()
        if path in self.logos:
            return localForld + self.logos[path]

 先查看本地是否已下载了,如果没有则下载并保存至本地,如果没有,就去网上下载,下载完毕后生成一个流水号,然后将流水号作为文件名存储,这个过程中设计到两个系统对象存储文件,一个就是存储当前的最大流水号,以便在下次再次启动程序时能从这个流水号开始往上加,再一个就是文件名的映射文件,将网络路径映射到本地文件名。

这里设计到一个叫Generator的类,这是我写的一个流水号生成器,代码如下:

 

文件名:SerialCode.py

#!/usr/bin/env python
#coding=UTF-8
'''
Created on 2009-3-13

@author: phy
'''
import time
import cPickle as pickle

class Generator(object):
    """流水号生成器"""
    def __init__(self, gs=[]):
        self.generators = gs
        self.lastCode = ""
        self.s_in_file = "/home/phy/code.sc"#流水号保存的位置
    def generate(self):
        """生成一个流水号"""
        code = ""
        for generator in self.generators:
            if hasattr(generator, "generate") and callable(getattr(generator, "generate")):
                code += generator.generate(code)
        self.lastCode = code
        return code
    def setLastCode(self, code):
        """初始化流水号"""
        if(len(self) != len(code)):
            return
        index = 0
        prefix = ""
        for generator in self.generators:
            if not hasattr(generator, "__len__"):
                continue
            n = len(generator)
            v, index = code[index:index + n], index + n
            if hasattr(generator, "setValue") and callable(getattr(generator, "setValue")):
                generator.setValue(prefix, v)
            prefix += v
    def __len__(self):
        """该长度表示所生成的流水号的总长"""
        n = 0
        for generator in self.generators:
            if hasattr(generator, "__len__"):
                n += len(generator)
        return n
    def saveLast(self):
        """保存最后一次生成的流水号"""
        f = file(self.s_in_file, "wb")
        try:
            pickle.dump(self.lastCode, f, True)
        except IOError, e:
            print e
        finally:
            f.close()
    def loadLast(self):
        """加载最后一次生成的流水号"""
        f = None
        try:
            f = file(self.s_in_file, "rb")
            self.lastCode = pickle.load(f)
            if(self.lastCode):
                self.setLastCode(self.lastCode)
            return self.lastCode
        except IOError, e:
            print e
        finally:
            if f:
                f.close()
class CharGenerator(object):
    def __init__(self, ch="A"):
        self.ch = ch
    def generate(self, code):
        return self.ch
    def __len__(self):
        return len(self.ch)
    
class DateGenerator(object):
    def __init__(self, format="%Y%m%d%H%M%S"):
        self.format = format
    def generate(self, code):
        return time.strftime(self.format, time.localtime())
    def __len__(self):
        return len(time.strftime(self.format, time.localtime()))

class FlowNumberGenerator(object):
    def __init__(self, restartOnPrefixChange=False, length=4, startBy=1):
        self.len_of_char = length#生成的字符长度
        self.currPrefix = ""#前面的字符
        self.restartOnPrefixChange = restartOnPrefixChange#在前缀字符改变是是否重新开始
        self.startBy = startBy if isinstance(startBy, int) else 1#上次生成的code
        self.preCode = self.startBy - 1
    def generate(self, code):
        if self.restartOnPrefixChange and self.currPrefix != code:
            self.preCode = self.startBy - 1
            self.currPrefix = code
        v = self.preCode + 1
        returnValue = self.intToChar(v)
        self.preCode = v
        return returnValue
    def intToChar(self, num):
        num = str(num)
        while len(num) < self.len_of_char:
            num = "0" + num
        return num
    def setValue(self, prefix, value):
        self.currPrefix = prefix
        self.preCode = int(value)
    def __len__(self):
        return self.len_of_char

def cretaeDefault(defaultChar=None, useDateGenerator=True):
    genertor = Generator()
    if defaultChar:
        genertor.generators.append(CharGenerator(defaultChar))
    if useDateGenerator:
        genertor.generators.append(DateGenerator("%Y%m%d%H"))
    genertor.generators.append(FlowNumberGenerator(restartOnPrefixChange=True))
    #genertor.generators.append(Config())
    genertor.loadLast()
    return genertor

if __name__ == '__main__':
    genertor = Generator()
    genertor.generators.append(CharGenerator("WN"))
    genertor.generators.append(DateGenerator("%Y%m%d%H"))
    genertor.generators.append(FlowNumberGenerator(restartOnPrefixChange=True))
    genertor.generators.append(Config())
    l_code = genertor.loadLast()
    l_code = genertor.generate() if not(l_code) else l_code
    print "上次的流水号:" + l_code
    while True:
        input = raw_input("请选择(输入q或其他退出,输入n显示下一个流水号):")
        if(input != "n"):
            genertor.saveLast()
            break
        l_code = genertor.generate()
        print l_code
    
        

 。。。这几天都在加班,累死了。。

论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics