当前位置: 首页>>代码示例>>Python>>正文


Python utils.md5函数代码示例

本文整理汇总了Python中utils.md5函数的典型用法代码示例。如果您正苦于以下问题:Python md5函数的具体用法?Python md5怎么用?Python md5使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了md5函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_web

    def test_web(self):
        phone = self.get_random_phone_number()
        # check

        timestamp = str(time.time())
        action = random.choice(list(constants.ActionEnum)).value
        user = self.user
        ip = '::1'
        url = urlparse.urljoin(self.server, '/phone/check')
        params = dict(token=user.token, timestamp=timestamp, phone=phone, action=action, ip=ip)
        params['sign'] = utils.md5(user.key+timestamp+phone)
        response = requests.get(url, params=params)

        logging.info('response: %s', response.text)
        r = response.json()

        self.assertTrue(r['code'] == 0, 'access url failure: url: %s, response: %s' % (url, response.text))
        # add white list
        url = urlparse.urljoin(self.server, '/phone/commit/white_list')
        params = dict(token=user.token, timestamp=timestamp, phone=phone)
        params['sign'] = utils.md5(user.key+timestamp+phone)

        response = requests.get(url, params=params)
        logging.info('response.text: %s', response.text)
        r = response.json()

        self.assertTrue(r['code'] == 0, 'access url failure: url: %s, response: %s' % (url, response.text))

        return
开发者ID:nackng,项目名称:opennumber,代码行数:29,代码来源:test.py

示例2: post

 def post(self):
     params = {}
     for key in ['phone', 'icon']:
         params[key] = self.arguments.get(key, "")
     #fh = open("/static/gofree.png", "wb")
     #fh.write(params['icon'].decode('base64'))
     #fh.close()
     width = 100
     uid_hash = utils.md5(self.current_user['uid'])
     img_dir = 'static/headimg/%s/%s' % (uid_hash[:2], uid_hash[2:4])
     filename = utils.md5(str(time.time()+random.randint(10000, 99999)))
     img_file = '%s/%s.png' % (img_dir, filename)
     # 创建文件夹
     img_path = os.path.join(constants.BASE_DIR, img_dir)
     if not os.path.exists(img_path):
         os.makedirs(img_path)
     f = open(os.path.join(constants.BASE_DIR, img_file), 'wb+')
     f.write(params['icon'].decode('base64'))
     f.close()
     im = Image.open(os.path.join(constants.BASE_DIR, img_file))
     ratio = float(width)/im.size[0]
     height = int(im.size[1]*ratio)
     nim = im.resize((width, height), Image.BILINEAR)
     nim.save(os.path.join(constants.BASE_DIR, img_file))
     users.update_avatar(self.current_user['uid'], '/'+img_file)
     base_url = self.config['url']['base']
     url = base_url + '/' + img_file
     # print `url` + 'url'
     return self.return_result({"url": url})
开发者ID:lisongjian,项目名称:sp,代码行数:29,代码来源:user.py

示例3: reset_password

 def reset_password(handler, old, new):
     db = handler.db
     user = db.query(User).filter_by(name=handler.username).first()
     if user.pwd != utils.md5(old):
         return False
     user.pwd = utils.md5(new)
     return True
开发者ID:Shu-Ji,项目名称:multi-supervisord-web-admin,代码行数:7,代码来源:models.py

示例4: from_url

    def from_url(self, url):
        if md5(url) in self.cache:
            self.data = self.cache[md5(url)]
            return

        data = json.dumps({'url': url})
        headers = {'Content-Type': 'application/json'}
        self.data = self._get_faces(headers, data)
        self.cache[md5(url)] = self.data
开发者ID:rbparson,项目名称:thedailyshow,代码行数:9,代码来源:faces.py

示例5: from_file

    def from_file(self, path):
        if os.path.getsize(path) > 2*1024*1024:
            raise FileTooBigException('File must be under 2MB')

        if md5(path) in self.cache:
            self.data = self.cache[md5(path)]
            return

        data = open(path, 'rb').read()
        headers = {'Content-Type': 'application/octet-stream'}
        self.data = self._get_faces(headers, data)
        self.cache[md5(path)] = self.data
开发者ID:rbparson,项目名称:thedailyshow,代码行数:12,代码来源:faces.py

示例6: check_sign_duomeng

    def check_sign_duomeng(self):
        """ duomeng验证签名 """
        args = self.request.arguments
        kv = []
        for key in args:
            if key != 'sign':
                value = args[key][0].decode('utf-8')
                kv.append('%s=%s' % (key, value))
        raw_str = ''
        for s in sorted(kv):
            raw_str += s
        raw_str += self.config['duomeng_key']['ios']

        utils.loggers.use('callback', self.log_path).info('[duomeng_before_md5]'+raw_str)
        utils.loggers.use('callback', self.log_path).info('[duomeng_md5]'+utils.md5(raw_str))
        return utils.md5(raw_str)
开发者ID:lisongjian,项目名称:ts,代码行数:16,代码来源:callback.py

示例7: _IsNewPC

 def _IsNewPC(self):
     if sys.platform == 'win32':
         cur_name = md5(os.environ['COMPUTERNAME'])
         store_name = get_conf('perm', 'flag')
         if cur_name != store_name:
             clear_conf('db')
             set_conf('perm', 'flag', cur_name)
开发者ID:linzhonghong,项目名称:dnspod_desktop,代码行数:7,代码来源:dnspod_desktop.py

示例8: savestudent

def savestudent(request):
    conn = DBSession()
    params_tuple=['student.id','student.name','student.identity','student.clazzid']
    student_id,name,identity,clazzid=[request.params.get(x) for x in params_tuple]
    student = conn.query(Student).filter(Student.id == student_id).first()
    if student:
        student.name = name
        student.identity = identity
        student.clazzid = clazzid
        student.updatetime=time.time()
    else :
        student = Student()
        student.name = name
        student.identity = identity
        student.clazzid = clazzid
        student.state=0
        student.createtime=time.time()
        student.updatetime=time.time()
        user = User()
        user.name = identity
#md5加密           
        user.password = md5(identity)
        user.role = 2
        user.regtime=time.time()
        user.logintimes=0
        conn.add(user)
        conn.flush()
        student.userid = user.id
        conn.add(student)
        
    conn.flush()
    return HTTPFound(location=request.route_url('student_list'))
开发者ID:frostpeng,项目名称:frostcms,代码行数:32,代码来源:student.py

示例9: get

    def get(self):
        word_list = self.get_argument("word", default="").split("\n")
        if len(word_list) > 0:
            for word_item in word_list:
                word = word_item.strip()
                word_id = utils.md5(word)
                record_word = Words.objects(word_id=word_id).first()
                if record_word is not None:
                    self.write("该词条已经存在!")
                else:
                    word_type = int(self.get_argument("word_type", default=1))
                    record_word = Words()

                    record_word.word_id = word_id
                    record_word.word = word
                    record_word.src_type = word_type
                    record_word.word_type = 1
                    record_word.save()

                    top_flg = int(self.get_argument("word_type", default=1))
                    if top_flg == 1:
                        top_word = TopWords()
                        top_word.type = record_word.src_type
                        top_word.word_id = record_word.word_id
                        top_word.word = record_word.word
                        top_word.save()

                    self.write("词条添加成功!")

        self.finish()
开发者ID:marey,项目名称:xtalk-server,代码行数:30,代码来源:web_handler.py

示例10: create

def create(): 
    response={}
    try:
        reader = codecs.getreader("utf-8")
        data = json.load(reader(request.body))
        #data=json.load(request.body.read().decode('utf8'))
        firstName='\''+data['firstName']+'\''
        lastName='\''+data['lastName']+'\''
        nickName='\''+data['nickName']+'\''
        telephone='\''+data['telephone']+'\''
        email='\''+data['email']+'\''
        userPass='\''+utils.md5(data['userPass'])+'\''
        sql="insert into User (firstName, lastName, nickName, telephone,email,us
erPass) values(%s, %s,%s, %s,%s, %s)" %(firstName,lastName,nickName,telephone,em
ail, userPass)
        userID=mysql.query(sql,0)[0]
        #print (userID)        
        token=uuid.uuid4().hex
        response['userID']=userID
        response['token']=token
        userIDstr='\''+str(userID)+'\''
        token='\''+token+'\''
        sql="insert into Token (created_at, userID, generatedToken) values (TIME
STAMPADD(MONTH,1,CURRENT_TIMESTAMP), %s, %s)" % (userIDstr, token)
        mysql.query(sql,1)        
开发者ID:YupengGao,项目名称:web,代码行数:25,代码来源:manage.py

示例11: message_service_callback

 def message_service_callback(self,msg):
     if msg=="refresh_match_grid":
         self.data_grid_model = MatchsTreeModel(self.analyze_thread.dataset)
         self.matchs_grid.setModel(self.data_grid_model)
         if url_with_params(self.urlComboBox.currentText()):
             file_path = "data/"+md5(self.urlComboBox.currentText())
             if not os.path.exists(file_path):
                 # for row in self.analyze_thread.dataset:
                 #     row.pop("formula_total")
                 #     row.pop("formula_last10")
                 #     row.pop("formula_last4")
                 # write_file(file_path,json.dumps(self.analyze_thread.dataset))
                 pass
         self.execute_button.setEnabled(True)
         self.clear_button.setEnabled(True)
         self.urlComboBox.setEnabled(True)
     elif msg == "cache_history_data":
         #batch_save_history_matchs(self.download_history_thread.dataset)
         wl_lb_match_history_cache(self.download_history_thread.dataset)
         pass
     elif msg == "completed":
         self.execute_button.setEnabled(True)
         self.urlComboBox.setEnabled(True)
     elif msg == "trigger_matchs_analyze":
         self.trigger_matchs_analyze()
     else:
         self.msg_bar.setText(msg)
开发者ID:tinyms,项目名称:310game,代码行数:27,代码来源:WaterPress.py

示例12: get_sign

 def get_sign(self, params={}):
     """ 兑吧md5签名 """
     params = self._ksort(params)
     raw_str = ''
     for p in params:
         raw_str += str(p[1])
     return utils.md5(raw_str)
开发者ID:lisongjian,项目名称:lo,代码行数:7,代码来源:duibaV2.py

示例13: send_sms_ytx

def send_sms_ytx(phone, ytx):
    """ 容联云通讯短信验证码 """
    # FIXME 修改为异步 or 消息队列
    ts = datetime.now().strftime("%Y%m%d%H%M%S")
    sig = utils.md5(ytx['acid'] + ytx['actoken'] + ts).upper()
    url = '%s/2013-12-26/Accounts/%s/SMS/TemplateSMS?sig=%s' % \
        (ytx['url'], ytx['acid'], sig)
    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json;charset=utf-8",
        "Authorization": base64.b64encode(ytx['acid'] + ':' + ts),
    }
    code = str(random.randint(100000, 999999))
    payload = {
        "to": phone,
        "appId": ytx['appid'],
        "templateId": "18791",
        "datas": [code, '10'],
    }
    r = requests.post(url, headers=headers, data=json.dumps(payload))
    result = r.json()
    if result['statusCode'] == '000000':
        return True, code
    elif result['statusCode'] == '112314':
        return False, result['statusCode']
    else:
        return False, result['statusMsg'].encode('utf-8')
开发者ID:lisongjian,项目名称:lo,代码行数:27,代码来源:captcha.py

示例14: main

def main():
    # Let's use letter frequencies to detect English
    english = [     # a - z letter frequencies
        0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,
        0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,
        0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,
        0.00978, 0.02360, 0.00150, 0.01974, 0.00074]

    I_english = sum([p ** 2 for p in english])

    freqs = {' ': 0, '.': 0, ',': 0}  # I set these frequencies to 0, too lazy to look them up
    for (i, char) in enumerate(string.ascii_uppercase):
        freqs[char] = english[i]

    # Brute force!
    length = len(ciphertext)
    I = []
    for a in aa:
        for b in bb:
            trial_cipher = decrypt(ciphertext, a, b)
            counts = Counter(trial_cipher)
            Ij = sum([freqs[char] * n / length for (char, n) in counts.items()])
            I.append(((a, b), abs(Ij - I_english)))
    results = sorted(I, key=lambda x: x[1])

    a, b = results[0][0]
    plaintext = decrypt(ciphertext, a, b)
    solution = md5(plaintext)

    print(plaintext)
    print(solution)
开发者ID:ATouhou,项目名称:id0-rsa.pub,代码行数:31,代码来源:05-affine-cipher.py

示例15: post

    def post(self):
        username = self.get_argument("username")
        pattern = re.compile(r'^[A-Za-z0-9]{3,20}$')
        match = pattern.match(username)
        if match is False and username is None:
            self.api_response({'status':'fail','message':'会员名填写错误'})
            return
        usercount = self.db.execute_rowcount("select * from users where username = %s", username)
        if usercount > 0:
            self.api_response({'status':'fail','message':'此会员名已被使用'})
            return
        phone = self.session.get("phone")
        phonepattern = re.compile(r'^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\d{8}$')
        phonematch = phonepattern.match(phone)
        if phonematch is False and phone is None:
            self.api_response({'status':'fail','message':'手机号填写错误'})
            return
        phonecount = self.db.execute_rowcount("select * from users where phone = %s", phone)
        if phonecount > 0:
            self.api_response({'status':'fail','message':'此手机号已被使用'})
            return
        password = self.get_argument("password")
        pwdRepeat = self.get_argument("pwdRepeat")
        if password is None and pwdRepeat is None and password != pwdRepeat:
            self.api_response({'status':'fail','message':'密码和确认密码填写错误'})
            return
        type = self.get_argument("type")
        if type is None:
            self.api_response({'status':'fail','message':'经营主体不能为空'})
            return
        name = self.get_argument("company",None) if type == u'7' else self.get_argument("name", None)
        if name is None:
            self.api_response({'status':'fail','message':'真实姓名或单位名称不能为空'})
            return
        nickname = self.get_argument("nickname")
        if nickname is None:
            self.api_response({'status':'fail','message':'个人称呼不能为空'})
            return

        lastrowid = self.db.execute_lastrowid("insert into users (username, password, phone, type, name, nickname, status, createtime)"
                             "value(%s, %s, %s, %s, %s, %s, %s, %s)", username, utils.md5(str(password + config.salt)), phone
                             , type, name, nickname, 1, int(time.time()))

        #查看是否为供应商列表里面的供应商,如果是转移积分
        supplier=self.db.query("select id,pushscore from supplier where mobile=%s",phone)
        if supplier:
            self.db.execute("update users set pushscore=%s where id=%s", supplier[0]["pushscore"],lastrowid)
            self.db.execute("update supplier set pushstatus=2 where id=%s", supplier[0]["id"])



        #因为去掉了user_info表,所以name字段直接放在users表了
        # result = self.db.execute("insert into user_info (userid, name)value(%s, %s)", lastrowid, name)
        self.session["userid"] = lastrowid
        self.session["user"] = username
        self.session.save()
        #发短信通知用户注册成功
        utils.regSuccessPc(phone, name, username)
        self.api_response({'status':'success','message':'注册成功','data':{'username':username}})
开发者ID:zhouhang,项目名称:Btrade,代码行数:59,代码来源:register.py


注:本文中的utils.md5函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。