Esempio n. 1
0
def update_session(user_id, next_filter=None, **kwargs):
    if next_filter is not None:
        redis.hset(user_id, 'next_filter', next_filter)
    params = {k: v for k, v in kwargs.items() if k in FILTERS}
    if params:
        redis.hmset(user_id, params)
    redis.expire(user_id, app.config['EXPIRE'])
Esempio n. 2
0
    def _link_id_change(cls, old_field, new_field):
        """ change the hash field value in {model}:{models} """

        key = rmkey(cls, cls.model)
        id = redis.hget(key, old_field)
        redis.hdel(key, old_field)
        redis.hset(key, new_field, id)
Esempio n. 3
0
def get_log():
    logs = []
    json_data = json.loads(request.get_data())
    project = ProjectModel.query.filter_by(proname=json_data['data']).first()
    if not project.is_build():
        os.chdir(app.config['CODE_FOLDER'] + '/' + json_data['data'])
        cli = Client(base_url=HOST)
        for line in cli.build(path=os.getcwd(), stream=True, decode=True,
                              tag=str(REGISTRY + json_data['data'])):
            send_log(line)
            logs.append(line)
        # 向私有仓库推送镜像, 没有log的打印
        for line in cli.push(REGISTRY + json_data['data'], stream=True):
            # 打印出上传的log
            print line
            assert line
        redis.hset(project.id, project.verify, logs)
        project.build = True
        if 'Successfully built' in logs[-1]['stream']:
            project.success = 1
        else:
            project.success = 2
        db.session.add(project)
        db.session.commit()
    else:
        lines = eval(redis.hget(project.id, project.verify))
        for line in lines:
            send_log(line)
    return json.dumps({'msg': 'ok'})
Esempio n. 4
0
    def create(self):
        """
        Create a new session
        """
        # Generate a unique id
        self._data['id'] = str(uuid4())

        # Set created_at to now
        self._data['created_at'] = datetime.now().timestamp()

        # Save session settings
        redis.hset(f"session::{self.id}",
                   mapping={
                       "title": self.title,
                       "description": self.description,
                       "created_at": self.created_at,
                       "duration": self.duration
                   })

        # Set ttl of session settings (expire this redis key 500 seconds after the session ends)
        redis.expire(f'session::{self.id}', self.timeToEnd().seconds + (500))

        # enqueue a job to close the session at the session end time
        scheduler.enqueue_in(timedelta(seconds=self.duration), closeSession,
                             self.id)

        print(f"Session created: {self.id}")
Esempio n. 5
0
def set_thread_color(threadid, color):
    colors = get_colors()
    key = color_key(threadid)

    colors['threads'][key] = color
    colors['default'] = color

    redis.hset(opts_key(), 'colors', json.dumps(colors))
Esempio n. 6
0
def init_job(key, first_page_func):
    if not redis.exists(key):
        # 不存在该键,说明是第一次订阅该博客
        for item in first_page_func():
            redis.hset(key, item['title'], item['url'])
    else:
        # 存在该键,检测是否有更新
        check_update(key, first_page_func)
Esempio n. 7
0
    def link_id(cls, field, id):
        """
        link a model field to id in hash set, the key would be {model}:{models}
        e.g.
            key user:users could hold [username=4, username2=6 ...]
            so we can get user id by username
        """

        key = rmkey(cls, cls.model)
        redis.hset(key, field, id)
Esempio n. 8
0
def check_update(key, first_page_func):
    latest_item = first_page_func()[0]
    title, url = latest_item['title'], latest_item['url']

    if not redis.hexists(key, title):
        content = '您订阅的博客发布了新的文章《{}》,原文链接:\n{}'.format(title, url)
        logger.debug(content)
        bot.send_message(chat_id=1040935564, text=content)
        redis.hset(key, title, url)
    else:
        logger.debug('没更新')
Esempio n. 9
0
def dialog_preview(message):
    msg = message['msg']
    color = message['color']

    threadid = session.get('chn')
    user_id = session.get('s_user')

    pr_msg = {'userid': user_id, 'msg': msg, 'color':color}

    redis.hset('dlg_%s'%threadid,'usr_%s'%user_id, pr_msg)

    emit('preview_message', pr_msg ,room=dlg_room(session.get('chn')), broadcast=True, include_self=False)
Esempio n. 10
0
def set_favorites(message):
    userid = session['s_user']
    if userid!=0:
        threadid = str(message['threadid'])
        favorites = get_favorites()

        if not threadid in favorites:
            favorites.append(threadid)
        elif threadid in favorites:
            favorites.remove(threadid)

        redis.hset(opts_key(), 'fav_threads', json.dumps(favorites))
Esempio n. 11
0
def github_authorized():
    resp = GithubOAuth.github.authorized_response()
    session['github_token'] = (resp['access_token'], '')
    current_user.github_token = resp['access_token']
    db.session.add(current_user)
    db.session.commit()
    # 缓存个人的基本信息
    redis.hset(
        current_user.id,
        'github_data',
        json.dumps(GithubOAuth.github.get('user').data))
    # 缓存拥有的组织的基本信息
    redis.hset(
        current_user.id,
        'github_orgs_data',
        urllib2.urlopen(
            'https://api.github.com/user/orgs?access_token=%s&per_page=100' % resp['access_token']).read()
    )
    # 缓存个人项目信息
    redis.hset(
        current_user.id,
        'github_user_repos',
        urllib2.urlopen(
            'https://api.github.com/user/repos?access_token=%s&type=owner&per_page=100' % resp['access_token']).read()
    )
    # 缓存组织的项目信息
    github_orgs_data = redis.hget(current_user.id, 'github_orgs_data')
    if github_orgs_data is not None:
        github_orgs_data = eval(github_orgs_data)
        for github_org_data in github_orgs_data:
            redis.hset(
                current_user.id,
                github_org_data['login'],
                urllib2.urlopen(github_org_data['repos_url'] + '?per_page=100').read()
            )
    # 目前只是缓存所有的个人项目,其中包括组织中的所有项目,key 为项目的名称
    github_user_repos = redis.hget(
        current_user.id,
        'github_user_repos'
    )
    if github_user_repos is not None:
        github_user_repos = eval(github_user_repos)
        for github_user_repo in github_user_repos:
            redis.hset(
                current_user.id,
                github_user_repo['name'],
                github_user_repo['clone_url']
            )
    return redirect(url_for('build_code_new'))
Esempio n. 12
0
def process_prompt(next_prompt, user_id, message_text):
    if next_prompt < len(PROMPTS):
        prompt = PROMPTS[next_prompt]
        value = prompt['formatter'](message_text)
        redis.hset(user_id, prompt['name'], value)
        redis.hset(user_id, 'next_prompt', next_prompt+1)
        redis.expire(user_id, app.config['EXPIRE'])
        if next_prompt < len(PROMPTS):
            send_text_message(user_id, PROMPT_GREETINGS[next_prompt+1])
        return

    res = book_a_table(redis.hget(user_id, 'id_rest'),
                 redis.hget(user_id, 'time'),
                 redis.hget(user_id, 'persons'),
                 redis.hget(user_id, 'firstName'),
                 redis.hget(user_id, 'phone'))
    send_text_message(user_id, str(res))
Esempio n. 13
0
    def post(self):
        json_data = data_json()

        email = json_data["email"]
        password = json_data["password"]
        user = User.query.filter_by(email=email).first()
        if (user.verify_password(password)):
            if (redis.hexists(email, "field1")):
                token = redis.hget(email, "field1")
                return jsonify({"token": token})
            min_expire_token = 25
            number_bytes = 256
            token = token_urlsafe(number_bytes)
            redis.hset(email, "field1", token)
            redis.expire(email, 60 * min_expire_token)
            return jsonify({"token": token})
        else:
            return jsonify({"error": "password dont check"}), 400
Esempio n. 14
0
    def _create_credential(self, form):
        req = ['username', 'password']
        for field in req:
            if not form.get(field):
                flash("Missing " + field)
                return False
        username = form.get('username')
        password = form.get('password')
        email = form.get('email', None)

        exist = redis.hexists(USER_PREFIX + username, "password")
        if exist:
            flash("Username already in use")
            return False
        redis.hset(USER_PREFIX + username, "password", password)
        if email:
            redis.hset(USER_PREFIX + username, "email", email)
        session['username'] = username
        return True
Esempio n. 15
0
def save_diffs(data, threadid, user_id):
    prw = redis.hget('dlg_%s' % threadid, 'usr_%s' % user_id)
    if prw:
        prw = eval(prw)
        text = str(prw['msg'])
    else:
        text = ''

    if 'color' in data:
        color = data['color']
    else:
        color = ''

    if 'isCommenting' in data:
        isCommenting = data['isCommenting']
    else:
        isCommenting = False

    msg, nottext = dmp.patch_apply(dmp.patch_fromText(data['diffs']),text)
    pr_msg = {'userid': user_id, 'msg': msg, 'color': color, 'isCommenting':isCommenting}
    redis.hset('dlg_%s'%threadid,'usr_%s'%user_id, pr_msg)
Esempio n. 16
0
 def update(self):
     """
     Update a session's settings
     """
     if self.isEnded():
         raise Exception('This session has ended.')
     return redis.hset(f"session::{self.id}",
                       mapping={
                           "title": self.title,
                           "description": self.description,
                           "created_at": self.created_at,
                           "duration": self.duration
                       })
Esempio n. 17
0
def gitlab_authorized():
    req_url = "http://code.smartstudy.com/oauth/token"
    back_url = 'http://172.16.3.9:3000/gitlab/login/authorized'
    code = request.args.get('code')
    print code
    data = {
        'client_id':
            '675532f089b661c350f5b7f1be143145353124cca44ecdae1391d8cb8419e4e9',
        'client_secret':
            '290e4d19ff457771d6947f646c649a8ce4aade8c4e3f0d2c633c6df6f4581507',
        'code': code,
        'grant_type': 'authorization_code',
        'redirect_uri': back_url
    }
    post_data = urllib.urlencode(data)
    back_data = eval(post(req_url, post_data))
    current_user.gitlab_token = back_data['access_token']
    db.session.add(current_user)
    db.session.commit()
    # 缓存个人信息
    redis.hset(
        current_user.id,
        'gitlab_data',
        urllib2.urlopen(
            'http://code.smartstudy.com/api/v3/user?access_token=%s'
            % back_data['access_token']
        ).read()
    )
    # 缓存个人项目信息
    redis.hset(
        current_user.id,
        'gitlab_user_repos',
        urllib2.urlopen(
            'http://code.smartstudy.com/api/v3/projects?access_token=%s'
            % back_data['access_token']
        ).read()
    )
    # 目前只是缓存所有的个人项目,key 为项目的名称
    repos = urllib2.urlopen(
        'http://code.smartstudy.com/api/v3/projects?access_token=%s'
        % back_data['access_token']
    ).read()
    if repos is not None:
        repos = eval(repos)
        for repo in repos:
            redis.hset(
                current_user.id, repo['name'], repo['http_url_to_repo'])
    return redirect(url_for('build_code_new'))
Esempio n. 18
0
def set_unread_pm(s_user, s_private):
    redis.hset('pm_%s' % s_private, 'usr_%s' % s_user, s_user)
Esempio n. 19
0
def set_noteID(message):
    redis.hset('noteID',message['threadid'],message['noteID'])
Esempio n. 20
0
def update_markdown(post_id):
    content = redis.hget('post:%s' % post_id, 'content')
    content_markdown = markdown2.markdown(content, extras=['fenced-code-blocks'])
    redis.hset('post:%s' % post_id, 'content_markdown', content_markdown)
    return redirect(url_for('.detail', post_id=post_id))
Esempio n. 21
0
def start_prompt_user(sender_id, id_rest):
    redis.hset(sender_id, 'next_prompt', 0)
    redis.hset(sender_id, 'ready', 1)
    redis.hset(sender_id, 'id_rest', id_rest)
    redis.expire(sender_id, app.config['EXPIRE'])
    send_text_message(sender_id, PROMPT_GREETINGS[0])
Esempio n. 22
0
def set_commenting(message):
    redis.hset(opts_key(), 'is_commenting_'+str(message['threadid']), message['isCommenting'])
Esempio n. 23
0
from app import redis
from os import path

if __name__ == '__main__':
    accounts_dir = path.join(
        path.dirname(path.realpath(__file__)), 'accounts.txt'
    )
    with file(accounts_dir, 'r') as accounts_file:
        for line in accounts_file.readlines():
            print line
            id, v_id, a_id = line.split(',')
            redis.rpush('listings', 'listings:'+id)
            redis.hset('listings:'+id, 'airbnb', a_id)
            redis.hset('listings:'+id, 'vrbo', v_id)
Esempio n. 24
0
def set_last_thread(data):
    redis.hset(opts_key(), 'threadid', data['threadid'])
Esempio n. 25
0
def update_markdown(post_id):
    content = redis.hget('post:%s' % post_id, 'content')
    content_markdown = markdown2.markdown(content,
                                          extras=['fenced-code-blocks'])
    redis.hset('post:%s' % post_id, 'content_markdown', content_markdown)
    return redirect(url_for('.detail', post_id=post_id))
Esempio n. 26
0
from app import redis
from os import path

if __name__ == "__main__":
    accounts_dir = path.join(path.dirname(path.realpath(__file__)), "accounts.txt")
    with file(accounts_dir, "r") as accounts_file:
        for line in accounts_file.readlines():
            print line
            id, v_id, a_id = line.split(",")
            redis.rpush("listings", "listings:" + id)
            redis.hset("listings:" + id, "airbnb", a_id)
            redis.hset("listings:" + id, "vrbo", v_id)
Esempio n. 27
0
def set_passwd_update_time(name):
    return redis.hset(update_passwd_time_string, name, time.time())
Esempio n. 28
0
def set_user_last_interact_time(openid, timestamp):
    """ 保存最后一次交互时间 """
    redis.hset('wechat:user:'******'last_interact_time', timestamp)
    return None
Esempio n. 29
0
def add_new_user(msg):
    chat_id = msg.chat.id
    if not redis.hget(user_key(), chat_id):
        data = {'nickname': utils.get_nickname(msg.chat)}
        redis.hset(user_key(), chat_id, json.dumps(data))