• 小组件


    python基于PIL模块写的验证码小组件:

    import random
    from PIL import Image,ImageDraw,ImageFont,ImageFilter
    from static.character import *    #导入字体类型
    def check_code(width=120,height=30,char_length=5,font_file='kumo.ttf',font_size=28):
        code=[]
        img=Image.new(mode='RGB',size=(width,height),color=(255,255,255))
        draw=ImageDraw.Draw(img,mode='RGB')
    
        def rdChar():
            '''生成随机字母'''
            return chr(random.randint(65,90))
        def rdColor():
            '''生成随机颜色'''
            return (random.randint(0,255),random.randint(0,255),random.randint(0,255))
    
        font=ImageFont.truetype(font_file,font_size)
        # 写文字
        for i in range(char_length):
            char=rdChar()
            code.append(char)
            h=random.randint(0,8)
            draw.text([i*width/char_length,h],char,font=font,fill=rdColor())
    
       # 写干扰点
        for i in range(20):
            draw.point([random.randint(0,width),random.randint(0,height)],fill=rdColor())
    
        # 写干扰圆圈
        for i in range(20):
            draw.point([random.randint(0, width), random.randint(0, height)], fill=rdColor())
            x=random.randint(0,width)
            y=random.randint(0,height)
            draw.arc((x,y,x+4,y+4),0,90,fill=rdColor())
        # 画干扰线
        for i in range(5):
            x1=random.randint(0,width)
            y1=random.randint(0,height)
            x2=random.randint(0,width)
            y2=random.randint(0,height)
            draw.line((x1,y1,x2,y2),fill=rdColor())
    
        img=img.filter(ImageFilter.EDGE_ENHANCE_MORE)        #过滤
        return img,''.join(code)      

    返回img图片和验证号码

    自定义分页小组件

    class Pageinfo(object):
        def __init__(self,current_page,all_count,base_url,per_page=5,show_page=11):
            '''
            :param current_page:当前页
            :param per_page:每页的个数
            :param all_count:数据库总个数
            :param base_url:当前页地址        
            '''
            try:
               self.current_page=int(current_page)
            except Exception as e:
               self.current_page=1
            self.per_page=per_page
            a,b = divmod(all_count,per_page)
            if b:
                a=a+1
            self.all_page=a        #全部页数
            self.show_page=show_page
            self.base_url=base_url
        @property
        def start(self):
            '''开始页的id'''
            return (self.current_page-1)*self.per_page
    
        @property
        def stop(self):
            '''结束页id'''
            return self.current_page * self.per_page
    
        def pager(self):
            '''生成分页'''
            page_list=[]
            half=int((self.show_page-1)/2)    #要变为整形
            #如果数据库中数据小于默认显示的页数(比如只有2页内容,默认显示值为11页)
            if self.all_page<self.show_page:
                begin=1
                end=self.all_page+1
             #如果总页数 > 11
            else:
                #如果当前页<=5,永远显示1,11
                if self.current_page <= half:  #如果当前页小于5页
                    begin=1
                    end=self.show_page+1
                else:
                    if self.current_page+ half>self.all_page:    #如果当前页距离最后一页小于默认显示值
                        begin = self.all_page - self.show_page + 1
                        end=self.all_page + 1
                    else:
                        begin=self.current_page -half
                        end = self.current_page+ half +1   #下面for循环里面range要头不要尾,所有加1
            if self.current_page<=1:       #上一页
                prev = "<li><a href='#''>上一页</a></li>"
            else:
                prev="<li><a href='%s?page=%s'>上一页</a></li>"%(self.base_url,self.current_page-1)
    
            page_list.append(prev)
    
            for i in range(begin,end):      #创建分页的范围
                if i == self.current_page:
                    # print(i)
                    temp="<li class='active'><a href='%s?page=%s'>%s</a></li>"%(self.base_url,i,i,)
                else:
                    temp="<li><a href='%s?page=%s'>%s</a></li>"%(self.base_url,i,i,)
                page_list.append(temp)
    
            if self.current_page >=self.all_page:      #下一页
                #nex="<li><a href='%s?page=%s'>下一页</a></li>" % (self.base_url,self.all_page-1)
                nex = "<li><a href='#'>下一页</a></li>"
            else:
                nex = "<li><a href='%s?page=%s'>下一页</a></li>" % (self.base_url,self.current_page+1,)
    
            page_list.append(nex)
            return "".join(page_list)
    from . import settings
    import time,json
    def gen_random_str():
        import time
        import hashlib
        md5=hashlib.md5()
        md5.update(str(time.time()).encode('utf-8'))
        return md5.hexdigest()
    
    class CashSession(object):
        container={}
        def __init__(self,handler):
            self.handler=handler
            self.inital()
    
        def inital(self):
            '''cookie和session初始化'''
            client_random_str=self.handler.get_cookie(settings.SESSION_ID)
            if client_random_str and client_random_str in self.container:
                self.random_str=client_random_str
            else:
                self.random_str=gen_random_str()
                self.container[self.random_str]={}
    
            self.handler.set_cookie(settings.SESSION_ID,self.random_str,expires=time.time()+settings.EXPIRRE)
    
        def __getitem__(self, item):
            return self.container[self.random_str].get(item)
    
        def __setitem__(self, key, value):
            self.container[self.random_str][key] = value
    
        def __delete__(self, key):
            "字典为空的时候不能删,会报错"
            if key in self.container[self.random_str]:
                del self.container[self.random_str][key]
    
    class RedisSession(object):
        def __init__(self,handler):
            self.handler=handler
    
            self.inital()
    
        @property
        def conn(self):
            import redis
            conn=redis.Redis(host=settings.REDIS_HOST,port=6379)
            return conn
        def inital(self):
            '''cookie和session初始化'''
            client_random_str=self.handler.get_cookie(settings.SESSION_ID)
            if client_random_str and self.conn.exists(client_random_str):
                self.random_str=client_random_str
            else:
                self.random_str=gen_random_str()
    
    
            self.handler.set_cookie(settings.SESSION_ID,self.random_str,expires=time.time()+settings.EXPIRRE)
            self.conn.expire(self.random_str,settings.EXPIRRE)
    
        def __getitem__(self, item):
            '''json'''
            if self.conn.hget(self.random_str,item):
                return json.loads(self.conn.hget(self.random_str,item))
            else:
                return None
    
        def __setitem__(self, key, value):
            '''json'''
            self.conn.hset(self.random_str,key,json.dumps(value))
    
        def __delete__(self, key):
            "字典为空的时候不能删,会报错"
            if key in self.conn[self.random_str]:
                self.conn.hdel(self.random_str,key)
    
    
    class SessionFactory(object):
        @staticmethod
        def get_session():
            import importlib
    
            path=settings.SESSION_ENGIN
            md,cls=path.rsplit(".",maxsplit=1)
            m=importlib.import_module(md)
            clas=getattr(m,cls)
            return clas
    ssion组件1
    class SessionHandler(object):
        def initialize(self,*args,**kwargs):
            # print(kwargs)
            cls=SessionFactory.get_session()   #RedieSession对象或CashSession对象
            self.session=cls(self)
    
    class LoginHandler(SessionHandler,tornado.web.RequestHandler):
    
    
        def get(self, *args, **kwargs):
            # print(kwargs)          #这里面是在url上传值
            # url_n1 = self.application.reverse_url('n1')
            # url_n2 = self.application.reverse_url('n2', 666)
            # print(url_n1, url_n2)
            self.render('login.html')
    
        def post(self,*args,**kwargs):
            user=self.get_argument('user')
            if user=='qq':
                self.session['user']=user   #促发里面的setitem方法
                self.redirect('/index')
            else:
                self.render('login.html')
    
    
    class IndexHandler(SessionHandler,tornado.web.RequestHandler):
    
        def get(self, *args, **kwargs):
            user=self.session['user']
            if self.session['user']:
                self.render('index.html')
            else:
                self.redirect('/login')
    
    
    sett={
        'template_path':'view',
    }
    application = tornado.web.Application([
        (r'/login', LoginHandler, {"k1":'v1'}, "n1"),  #第三个位置的字典可以传值给initialize里面
        (r'/index',IndexHandler,),
    ],**sett)
    
    # application.add_handlers('www.baidu.com',[(r'/index',MainHandler)])   #y通过域名进行匹配
    
    
    if __name__ == "__main__":
        application.listen(8888)
        tornado.ioloop.IOLoop.instance().start()
    session组件app
  • 相关阅读:
    zen_cart 支付提前生成订单
    SSL加密过程
    建立自己的代码库
    自动代码工具
    mssqlserver 学习资源
    自己动手写操作系统(1)
    Windows Phone 7 优秀开源项目收集
    正则表达式工具
    .net framework source code
    vs2012 打包应用程序(创建部署/安装包)
  • 原文地址:https://www.cnblogs.com/hejunqing/p/9155780.html
Copyright © 2020-2023  润新知