Esempio n. 1
0
 def setDb(self, data):
     import re
     db.delete("listdb", where="Name LIKE \"%\"")
     for line in data.splitlines():
         if re.match(r"^\d{8}-.{1,10}-(\d{6}|\d{11})$", line.strip()):
             no, name, phone = line.split('-')
             db.insert("listdb", No=no, Name=name, Phone=phone)
Esempio n. 2
0
def create_account(email, password, privilege ):
    email = email.lower()
    hashed_password = hash_password(password)
    db.insert('users',
              email=email,
              password=hashed_password,
              privilege=privilege)
Esempio n. 3
0
def new_mention_notification(pid, nid, aid, uid, mid):
    db.insert('_notification_mention',
              pid=pid,
              nid=nid,
              aid=aid,
              uid=uid,
              mid=mid)
Esempio n. 4
0
 def moveData2History(self):
     #step0: 判定是否需要启动数据搬迁>_max_start_num
     _ret = db.query("SELECT COUNT(*) AS sum FROM HistoryTrack")
     if _ret[0].sum<_max_start_num:
         return 0
     #step1:确定当前流入历史库的速度
     incrNum   = self.getCurrentInputSpeed()
     #step2: 确定迁移的目标数据库
     selTable =self.getInput2Table(incrNum)
     selTableId = selTable.id
     #step3: 确定选定要迁移的数据
     items = db.query("SELECT * FROM HistoryTrack ORDER BY report_at LIMIT {0}".format(incrNum))
     for i in range(incrNum):
         item = items[i]
         if selTable.sum==0:
             db.update("HistoryTrackTable",where='id=$selTableId',
                                          from_time=item.report_at.strftime("%Y-%m-%d %H:%M:%S"),
                                          vars=locals())
         #将数据移入新的数据库
         db.insert(selTable.tableName,imei   =  item.imei,          
                             report_at       =  item.report_at,     
                             gpsLat    	    =  item.gpsLat,    	  
                             gpsLng          =  item.gpsLng,        
                             speed     	    =  item.speed,     	  
                             realState       =  item.realState,     
                             lngType         =  item.lngType,       
                             latType         =  item.latType,       
                             direction       =  item.direction,     
                             addr            =  item.addr,          
                             province        =  item.province,     
                             city            =  item.city,          
                             gpsReport       =  item.gpsReport,     
                             reportMode      =  item.reportMode,    
                             ACC             =  item.ACC,           
                             CellID          =  item.CellID,        
                             LAC             =  item.LAC,           
                             MNC             =  item.MNC,           
                             MCC             =  item.MCC,           
                             satNum          =  item.satNum,        
                             locatedState    =  item.locatedState,  
                             gpsTime         =  item.gpsTime,       
                             qqLat           =  item.qqLat,         
                             qqLng           =  item.qqLng,         
                             baiduLat        =  item.baiduLat,      
                             baiduLng        =  item.baiduLng,      
                             country         =  ('中国' if item.country is None else item.country),       
                             alarm           =  ('' if item.alarm is None else item.alarm),        
                             height          =  item.height,        
                             battery         =  item.battery,       
                             gsm_intensity   =  item.gsm_intensity,      
                             seatStatus      =  item.seatStatus,    
                             mileage         =  item.mileage,      
         )               
         #删除原来库的数据
         db.query("DELETE FROM HistoryTrack WHERE id={0}".format(item.id))
     #刷新截至时间与最新数据
     db.update("HistoryTrackTable",where='id=$selTableId',
                                   sum = selTable.sum+incrNum,
                                   to_time=item.report_at.strftime("%Y-%m-%d %H:%M:%S"),vars=locals())
     return incrNum
Esempio n. 5
0
    def POST(self, client_id, entry_id=None):
        entry = get_one("time_entries", entry_id)
        f = self.form(client_id)
        if f.validates():
            date_str = "{} {}".format(f.d.start_date.strip(),
                                      f.d.start_time.strip())
            start_time = end_time = datetime.strptime(date_str,
                                                      "%m/%d/%Y %I:%M %p")

            end_time = utils.compute_end_time(f.d.duration, start_time)
            if entry:
                db.update("time_entries",
                          where="id=$entry_id",
                          vars={'entry_id': entry_id},
                          description=f.d.description,
                          start_time=start_time,
                          end_time=end_time,
                          category_id=f.d.category_id)
            else:
                db.insert("time_entries",
                          client_id=client_id,
                          description=f.d.description,
                          start_time=start_time,
                          end_time=end_time,
                          category_id=f.d.category_id)
            raise web.seeother("/clients/%s/entries/" % client_id)
        else:
            return render.form(f)
Esempio n. 6
0
def add_feed_change(feedid, summary, details, is_error):
    db.insert('change',
              feedid=feedid,
              time=utils.now(),
              is_error=is_error,
              summary=summary,
              details=details)
Esempio n. 7
0
def create_account(email, password, privilege):
    email = email.lower()
    hashed_password = hash_password(password)
    db.insert('users',
              email=email,
              password=hashed_password,
              privilege=privilege)
Esempio n. 8
0
def record_playlog(object_id, asked_questions, right):
    '''Records the questions and responses, and outcomes of each game. Allows us
       to experiment using different parameters without having to retrain from scratch.'''
    db.insert('playlog',
              object_id=object_id,
              data=str(asked_questions),
              right=right)
Esempio n. 9
0
 def response_handler(self, parsed_response, original_response):
     # If the response is the block page => don't activate the response detector.
     if self.kb[
             "blocked_url"] in self._request.host_name and self._request.path == self.kb[
                 "blocked_path"]:
         return UserProtectionResults(
         ), RedirectAnswerTo.Client, original_response
     self._response = parsed_response
     parsed_response.from_server_id = self._server.item_id
     res_cookies = self._request.headers.get("Cookie", "")
     m = re.match(".*?Elro-Sec-Bit=.*\"(\d*)@Elro-Sec-End", res_cookies)
     self._bit_indicator = 255 if m is None else int(m.group(1))
     user_protection = UserProtectionDetector(parsed_response)
     results = user_protection.detect(self._bit_indicator)
     detector_data = DetectorDataResponse(
         request_id=self._request_data.item_id,
         from_server_id=parsed_response.from_server_id,
         to_ip=parsed_response.to_ip)
     db.insert(detector_data)
     # User Protection Bit
     if m is None and self.kb["file_type"] in self._request.headers.get(
             "Content-Type", ""):
         bit_cookie = cookies.SimpleCookie()
         bit_cookie['Elro-Sec-Bit'] = self.kb["elro_sec_bit_format"].format(
             self._bit_indicator)
         bit_cookie['Elro-Sec-Bit']['max-age'] = 2592000  # 30 days
         original_response.headers["Set-Cookie"] = bit_cookie
     return results, RedirectAnswerTo.Client, original_response
Esempio n. 10
0
def POST(web):
    db.insert('post',
              title=web.params['title'],
              content=web.params['content'])


    return redirect("/")
Esempio n. 11
0
 def getJsapiTicket(self):
     _ret = db.query("SELECT * FROM GlobalPara WHERE name='jsapi_ticket'")
     if len(_ret) == 0:
         html = urllib2.urlopen(
             self.cmdUrl("ticket/getticket") + "&type=jsapi")
         ret = json.loads(html.read().decode("utf-8"))
         ticket = ret['ticket']
         db.insert("GlobalPara",
                   name='jsapi_ticket',
                   value=ticket,
                   create_at=datetime.datetime.now())
     else:
         jsapi_ticket = _ret[0]
         ticket = jsapi_ticket.value
         create_at = jsapi_ticket.create_at
         if time.time() >= time.mktime(create_at.timetuple()) + 7200:
             html = urllib2.urlopen(
                 self.cmdUrl("ticket/getticket") + "&type=jsapi")
             ret = json.loads(html.read().decode("utf-8"))
             ticket = ret['ticket']
             db.insert("GlobalPara",
                       name='jsapi_ticket',
                       value=ticket,
                       create_at=datetime.datetime.now())
     return ticket
Esempio n. 12
0
 def setDb(self,data):
     import re
     db.delete("listdb",where="Name LIKE \"%\"")
     for line in data.splitlines():
         if re.match(r"^\d{8}-.{1,10}-(\d{6}|\d{11})$",line.strip()):
             no,name,phone=line.split('-')
             db.insert("listdb",No=no,Name=name,Phone=phone,Total=0)
Esempio n. 13
0
File: pm.py Progetto: peremen/noah3k
def send_mail(from_id, to_id, title, body):
    sender_info = user.get_user(from_id)
    receiver_info = user.get_user(to_id)
    if not sender_info[0]:
        return (False, _('INVALID_SENDER'))
    if not receiver_info[0]:
        return (False, _('INVALID_RECEIVER'))
    if title.strip() == '':
        return (False, _('EMPTY_TITLE'))
    if body.strip() == '':
        return (False, _('EMPTY_BODY'))

    t = db.transaction()
    try:
        db.insert('Mails', mSenderSerial = from_id,
                mReceiverSerial = to_id,
                mSenderId = sender_info[1].uId,
                mSenderNick = sender_info[1].uNick,
                mDatetime = web.SQLLiteral('NOW()'),
                mTitle = title,
                mContent = body)
    except:
        t.rollback()
        return (False, _('DATABASE_ERROR'))
    else:
        t.commit()
    return (True, _('SUCCESS'))
Esempio n. 14
0
def newNode(nodeImg, nodeName, nodeDesc, nodeOpen, nodeCreater):

    if not nodeOpen:
        nodeOpen = '0'
    else:
        nodeOpen = '1'

    db.insert('_node', nodeImg=nodeImg, nodeName=nodeName, nodeDesc=nodeDesc, nodeOpen=nodeOpen, node_author=nodeCreater)
Esempio n. 15
0
def add_data(object_id, question_id, value=0):
    '''Inserts a weight with value=value for a specified object_id and question_id
       into data. Defaults to value=0.'''

    db.insert('data',
              object_id=object_id,
              question_id=question_id,
              value=value)
Esempio n. 16
0
def get_or_create_category(client, name):
    cat = get_safe(db.select("categories",
                              where="client_id=$client_id AND name=$name",
                              vars={'client_id': client.id, 'name': name}))
    if cat:
        return cat
    db.insert("categories", client_id=client.id, name=name)
    return get_or_create_category(client, name)
Esempio n. 17
0
def add(thread):
    success = False
        
    if thread.author and thread.title and thread.content:
        db.insert('forum_threads', **thread)
        success = True

    return success
Esempio n. 18
0
def reply(thread):
    success = False
        
    if thread.reply_to and thread.author and thread.content:
        db.insert('forum_threads', **thread)
        success = True

    return success
def run():
    args = parser.parse_args()
    username = args.user_name
    user = Users(email=username,
                 password=args.password,
                 active=True,
                 is_admin=True)
    db.insert(user)
    print("The new user id is: ", user.item_id)
Esempio n. 20
0
 def insert(self):
     self.pre_insert and self.pre_insert()
     params = {}
     for k, v in self.__mappings__.iteritems():
         if v.insertable:
             if not hasattr(self, k):
                 setattr(self, k, v.default)
             params[v.name] = getattr(self, k)
     db.insert(self.__table__, **params)
     return self
Esempio n. 21
0
def newPost(postImage, postTitle, postCaption, postArticle, postAuthor, postTemp, nodeId):
    if postImage != '':
        postImage = postImage.split('_')[0] + "_" + postImage.split('_')[1] + "_" + postImage.split('_')[2];
    
    postArticle = htmlquote(postArticle).strip()

    # postArticle = postArticle.replace("\r\n", "<br/>")

    db.insert('_post', postImage=postImage, postTitle=postTitle, postCaption=postCaption, postArticle=postArticle, postAuthor=postAuthor, postTemp=postTemp, nodeId= nodeId)
    db.query("UPDATE _node set postMount=postMount+1 WHERE id=$id", vars=dict(id=nodeId))
Esempio n. 22
0
 def writeDb(self,data):
     import time
     self.postTime=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
     
     db.insert("bugs",Content=data.Content,Name=data.Name,
             Phone=data.Phone,Room=data.Room,
             PostTime=self.postTime,
             IsOver=0,
             Time=data.Time,
             )
Esempio n. 23
0
 def POST(self, client_id=None):
     f = self.form()
     if f.validates():
         if client_id:
             db.update("clients", where="id=$client_id",
                       vars=locals(), **f.d)
         else:
             db.insert("clients", **f.d)
         raise web.seeother("/clients/")
     else:
         return render.form(f)
Esempio n. 24
0
def add(form):
    i = db.insert('users',
                  username=form.username.value,
                  password=web.SQLLiteral("PASSWORD('%s')" %
                                          form.password.value),
                  created_at=web.SQLLiteral("NOW()"),
                  firstname=form.firstname.value,
                  lastname=form.lastname.value,
                  isactive=1)
    db.insert('users_roles', user_id=i, role_id=get_role_by_name('login').id)
    return i
Esempio n. 25
0
def update_task_state(task_id, target_state):
    # 更新任务状态
    db.insert('''
            UPDATE
                `system_task_records`
            SET
                `state` = %s
            WHERE
                `id` = %s''',
              target_state,
              task_id)
Esempio n. 26
0
def add(module_id, vote, user_ip):
    if already_voted(module_id, user_ip):
        success = True
    else:
        success = False
        if module_id and -5 <= vote <= 5:
            db.insert('votes',
                module_id=module_id, vote=vote, ip=user_ip,
                datetime_created=web.SQLLiteral('now()'))
            success = True
        update_calculated_vote(module_id)
    return success
Esempio n. 27
0
    def POST(self):
        f = self.form()
        if not f.validates(web.input(_unicode=False)):
            show = web.input(show='all').show
            return render_account(show, register_form=f)
        elif len(f.d.username) > 16 :
            return render_account(
                show = 'register_only',
                error_message = '<span class="alert alert-error">不能超过16位</span>',
                register_form=f
            )
        elif len(f.d.username) < 2 :
            return render_account(
                show = 'register_only',
                error_message = '<span class="alert alert-error">不能少过2位</span>',
                register_form=f
            )
        elif not (re.search('^[a-zA-Z]{1}[\w\-]{5,15}$', f.d.username)):
            return render_account(
                show = 'register_only',
                error_message = '<span class="alert alert-error">请以字母开头,6-16个字母、数字</span>',
                register_form=f
            )
        else:
            users.create_account(f.d.username, f.d.email, f.d.password, f.d.nickname, '/static/public/img/default_48x48.jpg')
            id = users.get_user_by_email(f.d.email).id
            users.update_user_by_id(
                id,
                douban_id=id
            )

            if not users.is_user_exist_in__permission(id):
                db.insert('_permission', douban_id = id, rights = 1)
            if users.is_user_profile_exist(id):
                users.update_profile(id, city = '上海', bio = '')
            else:
                users.insert_profile(id, city = '上海', bio = '')

            session.login(f.d.email)
            user.is_logged = False # 虽然注册了, 但是还要等邮件确认
            user.douban_id = id

            token = md5.md5(time.ctime() + f.d.email).hexdigest()
            try:
                email_templates.msg_new_user_email(user, f.d.email, token)
                #保存记录到数据库
                users.save_confirm_email(f.d.email, user.id, token)
                #跳转到邮件发送成功页面
                return web.seeother('/welcome/'+ f.d.username +'/send_email_feedback?status=succesful')
            except Exception, e:
                print 'error--------, send email feedback ------------------'
                print e
                return web.seeother('/welcome/'+ f.d.username +'/send_email_feedback?status=failed')
 def _get_previous_request_info(self, ip, path, dns_name):
     brute_force_data = db.get_session().query(
         BruteForceDataItem).filter_by(ip=ip, path=path,
                                       dns_name=dns_name).first()
     if brute_force_data is None:
         brute_force_data = BruteForceDataItem(ip=ip,
                                               dns_name=dns_name,
                                               path=path,
                                               counter=0,
                                               time_stamp=time.time())
         db.insert(brute_force_data)
     return brute_force_data
Esempio n. 29
0
 def wrapper(self, *args, **kwargs):
     response_code, redirect_to, the_request, parsed_request = func(
         self, *args, **kwargs)
     if response_code == ControllerResponseCode.Failed:
         return response_code, redirect_to, the_request, parsed_request
     parsed_request.decision = True
     if response_code == ControllerResponseCode.NotValid:
         parsed_request.host_name = self.kb["blocked_url"]
         parsed_request.path = self.kb["blocked_path"]
         parsed_request.query = ""
         parsed_request.decision = False
     db.insert(self._request_data)
     return response_code, redirect_to, the_request, parsed_request
Esempio n. 30
0
def newNode(nodeImg, nodeName, nodeDesc, nodeOpen, nodeCreater):

    if not nodeOpen:
        nodeOpen = '0'
    else:
        nodeOpen = '1'

    db.insert('_node',
              nodeImg=nodeImg,
              nodeName=nodeName,
              nodeDesc=nodeDesc,
              nodeOpen=nodeOpen,
              node_author=nodeCreater)
Esempio n. 31
0
def add(form):
	i = db.insert('users',
		username=form.username.value,
		password=web.SQLLiteral("PASSWORD('%s')" % form.password.value),
		created_at=web.SQLLiteral("NOW()"),
		firstname=form.firstname.value,
		lastname=form.lastname.value,
		isactive=1
	)
	db.insert('users_roles',
		user_id = i,
		role_id = get_role_by_name('login').id
	)
	return i
def run():
    args = parser.parse_args()
    server = Server(user_id=args.user_id,
                    server_ip=args.server_ip,
                    server_dns=args.server_dns,
                    active=True)
    db.insert(server)
    services = Services(
        server_id=server.item_id,
        user_id=args.user_id,
    )
    db.insert(services)
    print("Done")
    print("The new server id is: ", server.item_id)
Esempio n. 33
0
    def writeDb(self, data):
        import time
        self.postTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

        db.insert(
            "bugs",
            Content=data.Content,
            Name=data.Name,
            Phone=data.Phone,
            Room=data.Room,
            PostTime=self.postTime,
            IsOver=0,
            Time=data.Time,
        )
Esempio n. 34
0
def add(module_id, author, comment):
    success, err_msg = False, ''
    
    banned_word = is_banned_keyword(author + ' ' + comment)
    if banned_word:
        err_msg = 'Ooops! Please go back to remove "%s" if you can...' % banned_word
    
    elif module_id and author and comment:
        db.insert('comments',
            module_id=module_id, author=author, content=comment, 
            datetime_created=web.SQLLiteral('now()'))
        success = True
        
    return success, err_msg
Esempio n. 35
0
def create_board(parent_id, settings):
    original_board_info = get_board_info(parent_id)
    if original_board_info == None:
        return (False, _('NO_SUCH_BOARD'))
    if not util.validate_boardname(settings['path']):
        return (False, _('INVALID_BOARDNAME'))
    check = _get_board_id_from_path(settings['path'])
    if check > 0:
        return (False, _('BOARD_ALREADY_EXIST'))
    if not acl.is_allowed('board', parent_id, settings['current_uid'], 'create'):
        return (False, _('NO_PERMISSION'))
    if settings['type'] == 2:
        if _get_board_id_from_path(settings['description']) < 0 or settings['description'].strip() == '':
            return (False, _('NO_SUCH_BOARD'))

    t = db.transaction()
    try:
        ret = db.insert('Boards', bName = settings['path'],
                uSerial = settings['board_owner'],
                bParent = parent_id, bDatetime = web.SQLLiteral('NOW()'),
                bInformation = settings['cover'],
                bDescription = settings['description'],
                bType = settings['type'],
                bReply = 1, bWrite = settings['guest_write'],
                bComment = settings['can_comment'],
                indexable = settings['indexable'], show_avatar = settings['show_avatar'])
    except:
        t.rollback()
    else:
        t.commit()

    return (True, 'SUCCESS')
Esempio n. 36
0
def update_issue(issue_id, content, status, priority, milestone_id, user_id, category, assignee):
    issue = db.select('issue', where='id=$issue_id', vars=locals())[0]
    db.update(
            'issue',
            where='id=$issue_id',
            vars=locals(),
            status=status,
            priority=priority,
            milestone_id=milestone_id,
            category_id=category,
            assignee_id=assignee)
    return db.insert(
            'issue_update',
            issue_id=issue_id,
            content=content,
            user_id=user_id,
            old_category=issue.category_id,
            new_category=category,
            old_assignee=issue.assignee_id,
            new_assignee=assignee,
            old_status=issue.status,
            new_status=status,
            old_priority=issue.priority,
            new_priority=priority,
            old_milestone=issue.milestone_id,
            new_milestone=milestone_id)
Esempio n. 37
0
def add(module_id, author, comment):
    success, err_msg = False, ''

    banned_word = is_banned_keyword(author + ' ' + comment)
    if banned_word:
        err_msg = 'Ooops! Please go back to remove "%s" if you can...' % banned_word

    elif module_id and author and comment:
        db.insert('comments',
                  module_id=module_id,
                  author=author,
                  content=comment,
                  datetime_created=web.SQLLiteral('now()'))
        success = True

    return success, err_msg
Esempio n. 38
0
def create_group(group_info):
    s = app.helpers.session.get_session()

    if 'is_active' in group_info:
        group_info.is_active = '1'
    else:
        group_info.is_active = '0'
    last_insert_rowid = db.insert("groups", description=group_info.description, email=group_info.email, creator=s.userid, created=int(time.time()), name=group_info.name, is_active=group_info.is_active)
    last_group = get_group_by_id(last_insert_rowid)

    # initiate dictionary
    records = {}

    # initiate list
    resposta = []

    # se last_insert_rowid == True, assume que usuario foi criado com sucesso
    if last_insert_rowid:
        # set response message to OK
        records['Result'] = 'OK'
        records['Record'] = last_group
    else:
        records['Result'] = 'ERROR'
        records['Message'] = 'GRUPO NÃO CRIADO!'

    return json.dumps(records)
Esempio n. 39
0
def create_message(message_info):
    s = app.helpers.session.get_session()

    if 'is_active' in message_info:
        message_info.is_active = '1'
    else:
        message_info.is_active = '0'
    last_insert_rowid = db.insert("messages", title=message_info.title, message=message_info.message, creator=s.userid, created=int(time.time()), is_active=message_info.is_active)
    last_message = get_message_by_id(last_insert_rowid)

    # initiate dictionary
    records = {}

    # initiate list
    resposta = []

    # se last_insert_rowid == True, assume que usuario foi criado com sucesso
    if last_insert_rowid:
        # set response message to OK
        records['Result'] = 'OK'
        records['Record'] = last_message
    else:
        records['Result'] = 'ERROR'
        records['Message'] = 'MENSAGEM NÃO CRIADA!'

    return json.dumps(records)
Esempio n. 40
0
def join(member):
    """
    회원 등록. 회원 정보를 포함하고 있는 딕셔너리를 던져 주면
    회원 등록을 시도한다. 실패했을 경우 상황에 따른 오류 코드를 반환한다.

    member에 오는 키와 값은 다음과 같다.

    - username: 사용자 ID
    - password: 사용자 암호. 두 번 입력받는 걸 검증하는 역할은 프론트엔드에서 담당한다. 암호화되지 않음.
    - nick: 별명.
    - email: 이메일 주소.
    - signature: 글 뒤에 붙는 시그.
    - introduction: 회원 정보 페이지에 뜨는 자기 소개.

    @type member: dict
    @param member: 회원 정보 딕셔너리.
    @rtype tuple
    @return: 회원 등록 성공 여부(T/F)와 오류 코드(실패 시)를 포함하는 튜플.
    """
    if not util.validate_username(member['username']):
        return (False, _('INVALID_USERNAME'))
    if _get_uid_from_username(member['username']) > 0:
        return (False, _('ID_ALREADY_EXISTS'))
    t = db.transaction()
    try:
        result = db.insert('Users', uNick = member['nick'], uEmail = member['email'],
                uId = member['username'], uPasswd = generate_password(member['password']),
                uDatetime = web.SQLLiteral('NOW()'), uSig = '', uPlan = '')
    except:
        t.rollback()
        return (False, _('DATABASE_ERROR'))
    else:
        t.commit()
    return (True, '')
Esempio n. 41
0
def user_create(email, hashed, user_name):
    user_id = db.insert('users', seqname = 'users_user_id_seq', 
            user_email = email,
            user_password = hashed,
            user_name = user_name, 
            user_last_login = datetime.datetime.utcnow()
        )
    return user_id
Esempio n. 42
0
def createBreak(frame_id, break_num, player_id):
    break_id = 0
    try:
        break_id = db.insert('tbreak',
                             frame_id=frame_id,
                             break_num=break_num,
                             player_id=player_id)
    except sqlite3.IntegrityError, e:
        pass
Esempio n. 43
0
def createMatch(date=''):
    if date == '':
        date = datetime.date.today().strftime("%Y-%m-%d")

    match_id = 0
    try:
        match_id = db.insert('tmatch', date=date)
    except sqlite3.IntegrityError, e:
       pass
Esempio n. 44
0
def add_reg(uid,s):
    with db.transaction():
        db.insert('reg_log',uid = uid ,
                  studentid=s.studentid,
                  college=s.college,
                  name=s.name,
                  telephone=s.telephone,
                  gender=s.gender,
        )
        db.update('users', vars = dict(uid=uid),
                  where = 'uid = $uid',
                  studentid=s.studentid,
                  college=s.college,
                  name=s.name,
                  telephone=s.telephone,
                  gender=s.gender,
        )
        return True
    return False
Esempio n. 45
0
def download_clip(url, bot, update, content_type, fname=None):
    """Download clips."""
    if not fname:
        fname = hashlib.sha1(url.encode(encoding='UTF-8')).hexdigest()

    author = update.message.from_user.first_name
    if content_type not in SUPPORTED_TYPES:
        logger.info("Link not supported: \n{}\nType{}".format(
            url, content_type))
        bot.sendMessage(chat_id=update.message.chat_id, text="👾 Link not supported. Only mp4, webm and gif links.")
    elif duplicate(url):
        logger.info("Detected duplicate {}".format(url))
        update.message.reply_text("👾 Reposter!")
    else:
        fpath = os.path.join(DATA_DIR, "clips", fname)
        logger.debug("Downloading clip to {}...".format(fpath))

        with open(fpath, "wb+") as f:
            r = requests.get(url, stream=True)

            if r.ok:
                for block in r.iter_content(1024):
                    f.write(block)
            else:
                logger.error("Download failed {}".format(r))

        # Convert gif files using ffmpeg
        if url[-3:] == "gif":
            fpath = convert_gif(fpath)
            fname = os.path.basename(fpath)

        clip = {
            "type": "clip",
            "url": url,
            "author": author,
            "filename": fname,
            "created": datetime.datetime.now().isoformat(),
            "incoming": True
        }

        db.insert(clip)
        bot.sendMessage(chat_id=update.message.chat_id, text="👾 Added video to database.")
        logger.info("Saved new clip {} from {}".format(fname, author))
Esempio n. 46
0
def add_subscription_board(uid, board_id):
    t = db.transaction()
    try:
        result = db.insert('Subscriptions', uSerial = uid, bSerial = board_id, lastSubscriptedDate=web.SQLLiteral('NOW()'))
    except:
        t.rollback()
        return False
    else:
        t.commit()
    return result
Esempio n. 47
0
def add_favorite_board(uid, board_id):
    t = db.transaction()
    try:
        result = db.insert('Favorites', uSerial = uid, bSerial = board_id)
    except:
        t.rollback()
        return False
    else:
        t.commit()
    return result
Esempio n. 48
0
def add_question(question):
    '''Adds a question with the given text to the questions table in the database.
       Also initializes weights for each object in the data table.'''
       
    question_id = db.insert('questions', text=question)
    # initialize weights for each object in data
    objects = get_objects()
    for object in objects:
        add_data(object.id, question_id)
    return question_id
Esempio n. 49
0
def create_account(username, email, password, nickname):
    #生成10位随机数
    all = list('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSQUVWXYZ')
    randStr = ''
    for i in range(10):
        index = random.randint(0,len(all)-1)
        randStr = randStr + all[index]
    #joinTime = time.mktime(time.localtime())
    currTime = time.strftime('%Y%m%d%H%I%M%S',time.localtime(time.time()))
    #note: 加密:随机数 + 时间 + 邮箱地址 + 密钥. //authKey为找回密码用? 每个用户都有一个唯一的authKey //现在没用上 囧
    authKey = hashlib.md5(randStr + currTime + email + encryption_key).hexdigest()
    #得到客户端IP地址
    ipAddress = web.ctx.ip

    #昵称时间
    nicknameTime = datetime.datetime.now()

    #入库    
    db.insert('users', username=username, email=email, password=hashlib.md5(password + encryption_key).hexdigest(), nickname=nickname, authKey = authKey, ipAddress = ipAddress, nicknameChangeTime = nicknameTime)#注:password 为混合密钥进行md5加密
Esempio n. 50
0
def add_question(question):
    '''Adds a question with the given text to the questions table in the database.
       Also initializes weights for each object in the data table.'''

    question_id = db.insert('questions', text=question)
    # initialize weights for each object in data
    objects = get_objects()
    for object in objects:
        add_data(object.id, question_id)
    return question_id
Esempio n. 51
0
def createMatchScore(match_id, player_id, won, frames_won, total_points):
    try:
        iid = db.insert('tmatchscore',
                            match_id=match_id,
                            player_id=player_id,
                            won=won,
                            frames_won=frames_won,
                            total_points=total_points)
    except sqlite3.IntegrityError, e:
        pass
Esempio n. 52
0
    def POST(self):
        events = [web.storage(e) for e
                  in gcal.fetch_events(config.g_username,
                                       config.g_password,
                                        config.g_calendar_name)]

        for event in events:
            client = get_safe(db.select("clients",
                                        where="lower(name)=lower($name)",
                                        vars={'name': event.client_name}))
            if not client:
                event['status'] = 'Client could not be found.'
                continue
            category_id = None
            if event.category_name:
                category = get_or_create_category(client, event.category_name)
                category_id = category.id

            entry = get_safe(db.select("time_entries",
                                       where="external_reference=$ref",                                      vars={'ref': event.id}))
            if not entry:
                db.insert("time_entries",
                          client_id=client.id,
                          description=event.description,
                          start_time=event.start,
                          end_time=event.end,
                          category_id=category_id,
                          external_reference=event.id)
                event.status = 'Creating new time entry'

            elif entry.invoice_id:
                event.status = 'Skipping, entry has already been invoiced.'
            else:
                db.update("time_entries",
                          where="id=$entry_id",
                          vars={'entry_id': entry.id},
                          description=event.description,
                          start_time=event.start,
                          end_time=event.end,
                          category_id=category_id)
                event.status = 'Updated time entry'
        return render.fetch_status(events=events)
Esempio n. 53
0
def add_object(name):
    '''Adds an object with the given name to the objects table in the database.
       Also initializes weights for each question in the data table.'''

    object_id = db.insert('objects', name=name)
    # initialize weights for each question in data
    questions = get_questions()
    for question in questions:
        add_data(object_id, question.id)

    return object_id
Esempio n. 54
0
def add_object(name):
    '''Adds an object with the given name to the objects table in the database.
       Also initializes weights for each question in the data table.'''
       
    object_id = db.insert('objects', name=name)
    # initialize weights for each question in data
    questions = get_questions()
    for question in questions:
        add_data(object_id, question.id)
    
    return object_id
Esempio n. 55
0
 def register_competition(self, name: str, modality: str,
                          event_date: str) -> dict:
     public_id = str(uuid.uuid4())
     query = db.insert(competitions_table).values(
         public_id=public_id,
         name=name,
         status="Open",
         modality=self.modality[f"{modality}"],
         event_date=event_date)
     connection.execute(query)
     return public_id