コード例 #1
0
ファイル: models.py プロジェクト: kaninfod/musicplayer
    def get_coverart(self, album):
        path = "app/static/media/"
        filename = "%s.jpg" % album.id

        musicbrainzngs.set_useragent("python-musicplayer-flask","0.1","*****@*****.**")
        covers = cache.get('covers')
        if album.id in covers:
            return

        covers.append(album.id)
        cache.set("covers", covers)


        if not album.musicbrainz_albumid or album.coverimage:
            return
            #raise NameError('musicbrainz_albumid not set')
        try:
            data = musicbrainzngs.get_image_list(album.musicbrainz_albumid)
        except Exception as e:
            return e

        if len(data['images']) == 0:
            raise NameError('No images returned from service')

        urllib.request.urlretrieve(data['images'][0]['image'], "%s%s" % (path, filename))
        ci = open("%s%s" % (path, filename), 'rb')
        album.coverimage.put(ci, content_type = 'image/jpeg')


        return
コード例 #2
0
    def fetchCategory(category_id=0, slug='', name=''):
        from app import cache
        if category_id:
            cache_key = 'category_' + str(category_id)
            query_cond = 'category_id'
            entity = category_id
        elif slug:
            cache_key = 'category_' + slug
            query_cond = 'slug_url'
            entity = slug
        elif name:
            cache_key = 'category_' + name.replace(' ', '_')
            query_cond = 'category_name'
            entity = name
        else:
            return {}
        category = cache.get(cache_key)
        if category:
            return category

        cursor = mysql.connect().cursor()
        cursor.execute(
            "SELECT * FROM categories WHERE " + query_cond + " = %s",
            (entity, ))
        category = Utils.fetchOneAssoc(cursor)
        category = WebUtils.extendCategoryProperties(category)
        cache.set(cache_key, category)
        return category
コード例 #3
0
    def request_access_token(self, use_cache=True):

        if use_cache:
            cache_token = cache.get(ease_mob_token_cache_key)
            if cache_token:
                return cache_token

        params = {
            "grant_type": "client_credentials",
            "client_id": self.client_id,
            "client_secret": self.client_secret
        }
        request = requests.post(self.generate_token_url(),
                                headers=self.request_header,
                                data=json.dumps(params))

        access_token = request.json().get("access_token", None)

        # 请求access_token失败的log
        if not access_token:
            log.error(
                json.dumps({
                    "params": params,
                    "result": request.json(),
                }))

        if access_token:
            cache.set(ease_mob_token_cache_key, access_token, 60 * 60 * 24)
        return access_token
コード例 #4
0
 def increase(self, key):
     user_statistic = self.get()
     if key == 1:
         user_statistic['added'] += 1
     elif key == 2:
         user_statistic['wrong'] += 1
     cache.set(self.key, user_statistic, timeout=int(self.tomorrow.total_seconds()))
コード例 #5
0
def edit_job(job_id: int) -> "render_template('job/add_job.html')":

    edit = True

    job = Job.find_job_by_id(job_id)
    form = JobForm(obj=job)

    if request.method == "POST" and form.validate_on_submit():
        job_id = str(job_id)
        form.populate_obj(job)
        job.last_edited = get_date_now()

        cache.delete(job_id)
        cache.set(key=job_id, value=job)
        job.save()

        log = f"You successful edited a job with ID {job_id} on the {format_date(job.applied_date)}"
        log_account_activity(session["username"], log)

        flash("You have successfully edited your job", "success")
        return secure_redirect_or_403(
            url_for('job_app.get_job_with_id', job_id=job_id))

    return render_template("job/add_job.html",
                           form=form,
                           login_form=LoginForm(),
                           edit=edit,
                           job_id=job_id)
コード例 #6
0
def create_token_seller():
    token = cache.get('token-seller')
    if token is None:
        ## prepare request input
        data = {'client_key': 'seller_2', 'client_secret': 'seller2'}

        ## do request
        req = call_client(request)
        res = req.post('/signin',
                       data=json.dumps(data),
                       content_type='application/json'
                       )  # seperti nembak API luar (contoh weather.io)

        ## store response
        res_json = json.loads(res.data)

        logging.warning('RESULT : %s', res_json)

        ## assert / compare with expected result
        assert res.status_code == 200

        ## save token into cache
        cache.set('token-seller', res_json['token'], timeout=60)

        ## return because it useful for other test
        return res_json['token']
    else:
        return token
コード例 #7
0
ファイル: slack.py プロジェクト: shivamgupta211/Ostrich
def rentbook():
    from app import cache
    data = request.form['text']
    if not data:
        return "Please enter book_id and locality after /rent"

    print request.form
    cache.set(request.form['user_id'] + '_book_id',
              data.split(' ')[0],
              timeout=10000)
    area = ' '.join(data.split(' ')[1:])
    validation = User.validateLocality(area)
    if validation['is_valid']:
        response = {
            "username":
            "******",
            "mrkdwn":
            True,
            "text":
            "*" + validation['delivery_message'] +
            "*\n Please enter /contact full_address phone_number. Eg.: /contact 58,1st Main Road 9898989898"
        }
        return Response(json.dumps(response), mimetype='application/json')
    else:
        return validation[
            'delivery_message'] + ": Sorry. Ostrich doesn't deliver here yet :slightly_frowning_face:"
コード例 #8
0
ファイル: routes.py プロジェクト: schlosser/go-to-sleep
def get_num_commits():
    num = cache.get('num_commits')
    if num is None:
        num = sum((len(requests.get(GITHUB_API%i).json()) for i in range(1, MAX_PAGES)))
        cache.set('num_commits', num, timeout=5*60)
        print "caclulated"
    return num
コード例 #9
0
ファイル: views.py プロジェクト: Hehe-Zhc/websth.com
def get_top_technology(category, order = 'DESC', limit = 5):
    """获取最高使用率的不同种类的技术类型"""
    result = cache.get('top_' + category + '_item_' + order)
    if result is None:

        rs = db.session.execute('select technology.title, count(website.id) from website \
                                left join website_tech on website_tech.website_id = website.id \
                                left join technology on technology.id = website_tech.tech_id \
                                and technology.title in (\
                                    select distinct technology.title from technology \
                                    where technology.category = \'' + category + '\' \
                                    and technology.title != \'Unknown\') \
                                group by technology.title \
                                order by count(website.id) ' + order + ' limit 1,' + str(limit))

        # 添加网站总数
        result = []
        for i in rs:
            if i[0] and i[0] != 'Unknown':
                result.append({
                           'title' : i[0],
                           'total' : i[1]
                           })
        cache.set('top_' + category + '_item_' + order, result, timeout=app.config['SQL_CACHE_TIMEOUT'])
    return result
コード例 #10
0
ファイル: sockets.py プロジェクト: hdavidzhu/wh2_music
 def on_move(self, data):
     current, playlist = get_playlist()
     to = data['to']
     playlist.insert(int(data['to']),
                     playlist.pop(playlist.index(int(data['from']))))
     cache.set('playlist', playlist)
     self.broadcast('update', {'current':current, 'playlist':playlist})
コード例 #11
0
ファイル: views.py プロジェクト: Hehe-Zhc/websth.com
def show_tech_json(title, page = 1, pagesize = app.config['PAGE_SIZE']):
    result = cache.get('tech_' + title + '_website_' + str(page) + '_' + str(pagesize))

    if not result:
        websites = Website.query\
                    .filter(Website.technologies.any(Technology.title == title))\
                    .order_by(Website.frequency.desc())\
                    .paginate(page, pagesize, True)

        websites.items = filter_website(websites.items)
        result = []

        for i in websites.items:
            techs = []
            for t in i.technologies:
                if t.title != 'Unknown':
                    techs.append({
                            'title': t.title,
                            'detail' : t.detail
                        })
            result.append({
                            'hostname' : i.hostname,
                            'port'     : i.port,
                            'technologies' : techs
                          })

        cache.set('tech_' + title + '_website_' + str(page) + '_' + str(pagesize), result, timeout=app.config['SQL_CACHE_TIMEOUT'])

    return jsonify(status = 'ok', page = page, pagesize = pagesize, websites = result)
コード例 #12
0
ファイル: views.py プロジェクト: chungs1/HackerNet
def edit_profile():
    if request.remote_addr != "127.0.0.1":
        return "UNAUTHORIZED ACCESS ATTEMPT REJECTED"
    form = ProfileForm()
    if form.validate_on_submit():
        if cache.get('ip_dict_valid'):
            cache.set('rerun_setup', True)
            cache.set('ip_dict_valid', True)

        file = request.files['picture']
        file.save(os.path.join(basedir,"app/static/profile.jpg"))

        pickling = {}
        #Get form data here!
        pickling["name"] = form.name.data
        pickling["location"] = form.location.data
        pickling["organization"] = form.organization.data
        pickling["about"] = form.about.data
        pickling["project"] = form.project.data
        pickling["project_description"] = form.project_description.data

        pickle.dump(pickling, open('pickledUser.p', 'wb'))
        
        #form.picture.save(filename)
        return redirect(url_for('profile'))
        
    #Get cpickle stuff here
    return render_template('edit_profile.html', form=form)
コード例 #13
0
 def beg(params, user_info):
     if user_info['data']['id'] == params['be_focused_user_id']:
         return Utils.formatError(CONST['CODE']['BAD_REQUEST']['value'],
                                  '无法添加自己为新朋友')
     addressBookdata = AddressBook.getAdddressBookByFocusedUserId(
         user_info['data']['id'], params['be_focused_user_id'])
     if addressBookdata != None:
         return Utils.formatError(CONST['CODE']['BAD_REQUEST']['value'],
                                  '已添加')
     msg_uuid = Utils.unique_id()
     userData = Users().getOne({Users.id == user_info['data']['id']})
     data = {
         'data': userData,
         'action': 'beg_add',
         'msg_uuid': msg_uuid,
         'be_focused_user_id': params['be_focused_user_id'],
         'focused_user_id': user_info['data']['id']
     }
     socketio.emit('beg',
                   Utils.formatBody(data),
                   namespace='/api',
                   room='@broadcast.' +
                   str(params['be_focused_user_id']))  #,callback=success)
     #只缓存最新的一条
     cache.set('@broadcast.beg' + str(params['be_focused_user_id']), data)
     return Utils.formatBody({}, msg='发送成功')
コード例 #14
0
def create_token(isInternal):
    # Checking whether internal or not and prepare the data
    if isInternal:
        cachename = "test-internal-token"
        data = {'email': '*****@*****.**', 'kata_sandi': 'l3l11234'}
    else:
        cachename = "test-non-internal-token"
        data = {'email': '*****@*****.**', 'kata_sandi': 'l3l1123456'}

    token = cache.get(cachename)
    if token is None:
        # Do Request
        req = call_client(request)
        res = req.post('/token', json=data, content_type='application/json')

        # Store Response
        res_json = json.loads(res.data)

        logging.warning('RESULT : %s', res_json)

        # Assertion
        assert res.status_code == 200

        # Save token into cache
        cache.set(cachename, res_json['token'], timeout=60)

        # Return, because it is useful for other test
        return res_json['token']
    else:
        return token
コード例 #15
0
def create_token_int():
    token = cache.get('test-token-int')
    # supaya tokennya bisa diambil lagi
    if token is None:
        data = {
            'client_key': 'internal1',
            'client_secret': 'th1s1s1nt3rn4lcl13nt'
        }
        # do request
        req = call_client(request)
        res = req.get('/auth',
                      query_string=data,
                      content_type='application/json')

        # store response
        res_json = json.loads(res.data)

        logging.warning('RESULT : %s', res_json)
        # assert if the result is as expected
        assert res.status_code == 200

        # save token into cache
        cache.set('test_token-int', res_json['token'], timeout=60)

        return res_json['token']
    else:
        return token
コード例 #16
0
 def get(self):
     '''
     新增博客缓存
     将博客信息按照blog_id_{blog_id}的形式存储在缓存中
     '''
     if 'manager_id' not in session:
         return {'status_code': 400, 'message': 'illegal request'}, 400
     manager_id = session['manager_id']
     parser = reqparse.RequestParser()
     parser.add_argument('blog_id', type=int)
     args = parser.parse_args()
     blog_id = args['blog_id']
     # cache.delete('blog_id_%s'%blog_id)
     blog = cache.get('blog_id_%s' % blog_id)
     if not blog:
         blog = getBlog(blog_id=blog_id, user_id=manager_id)
         if blog is None:
             return {
                 'status_code': 400,
                 'message': 'some error happened in mysql, please check log'
             }, 400
         cache.set('blog_id_%s' % blog_id, blog, timeout=600)
         updateBlogRead(blog_id=blog_id, user_id=manager_id)
     return {
         'status_code': 200,
         'message': 'get successfully',
         'blog': blog
     }
コード例 #17
0
def create_token(isInternal=False):
    if isInternal:
        cachename = 'test-admin-token'
        data = {"username": "******", "password": "******"}
    else:
        cachename = 'test-nonadmin-token'
        data = {"username": "******", "password": "******"}
    token = cache.get(cachename)
    # prepare request input

    if token is None:
        # do request
        req = call_client(request)
        res = req.post('/login', json=data)

        # store respons
        res_json = json.loads(res.data)

        logging.warning('RESULT: %s', res_json)

        # assert / compare with expected result
        assert res.status_code == 200

        # save token into cache
        cache.set(cachename, res_json['token'], timeout=60)

        # return, bcz it usefull for other test
        return res_json['token']
    else:
        return token
コード例 #18
0
def create_token_internal():
    token = cache.get('test-token')
    if token is None:
        # prepare request input
        data = {
            'phone_number': '085735950340',
            'password': '******',
        }

        # do request
        req = call_client(request)
        res = req.get('/login',
                      query_string=data,
                      content_type='application/json')

        # store response
        res_json = json.loads(res.data)

        app.logger.warning('RESULT : %s', res_json)

        # assert / compare with expected result
        assert res.status_code == 200

        # save token into cache
        cache.set('test-token', res_json['token'], timeout=60)

        # return, because it usefull for other test
        return res_json['token']
    else:
        return token
コード例 #19
0
    def get_coverart(self, album):
        path = "app/static/media/"
        filename = "%s.jpg" % album.id

        musicbrainzngs.set_useragent("python-musicplayer-flask", "0.1",
                                     "*****@*****.**")
        covers = cache.get('covers')
        if album.id in covers:
            return

        covers.append(album.id)
        cache.set("covers", covers)

        if not album.musicbrainz_albumid or album.coverimage:
            return
            #raise NameError('musicbrainz_albumid not set')
        try:
            data = musicbrainzngs.get_image_list(album.musicbrainz_albumid)
        except Exception as e:
            return e

        if len(data['images']) == 0:
            raise NameError('No images returned from service')

        urllib.request.urlretrieve(data['images'][0]['image'],
                                   "%s%s" % (path, filename))
        ci = open("%s%s" % (path, filename), 'rb')
        album.coverimage.put(ci, content_type='image/jpeg')

        return
コード例 #20
0
ファイル: back_user.py プロジェクト: Little-Frog-233/myBlog
 def get(self):
     '''
     获取用户信息
     '''
     parser = reqparse.RequestParser()
     parser.add_argument('token', type=str)
     args = parser.parse_args()
     token = args['token']
     if not token:
         return {
             'status_code': 400,
             'message': ''
         }, 400
     user_message = cache.get(token) ### 从缓存中获取用户信息
     if user_message is None:
         return {
         'status_code': 400,
         'message': '登陆已过期'
     }, 400
     cache.set(token, user_message, timeout=10080)
     return {
         'status_code': 200,
         'messaga': '',
         'data': {
             'user_message': user_message
         }
     }
コード例 #21
0
ファイル: tasks.py プロジェクト: naiquevin/logan
def url_hits():
    patterns = fetch_dynamic_patterns(app.config["URL_PATTERNS_FILE"])
    logs = fetch_logs(app.config["LOG_FILE_TO_ANALYZE"])
    urlhits = sorted(
        [(k[1], v) for k, v in logan.dynamic_urls(logs, patterns).iteritems()], key=lambda x: x[1], reverse=True
    )[:20]
    cache.set("url_hits", dict(urlhits), timeout=60 * 60)
コード例 #22
0
ファイル: __init__.py プロジェクト: daffa99/teesignr-backend
def create_token(punya_toko=False):
    if punya_toko:
        cachename = 'test-punya-toko-token'
        data = {'email': '*****@*****.**', 'password': '******'}
    else:
        cachename = 'test-token'
        data = {'email': '*****@*****.**', 'password': '******'}
    token = cache.get(cachename)
    if token is None:
        #prepare request input
        #do request
        req = call_client(request)
        res = req.post('/auth/login', json=data)

        #store response
        res_json = json.loads(res.data)
        logging.warning('RESULT : %s', res_json)

        ## assert / compare with expected result
        assert res.status_code == 200
        ## save token into cache
        cache.set(cachename, res_json['token'], timeout=60)
        ## return, because it useful for other test
        return res_json['token']
    else:
        return token
コード例 #23
0
def create_token(isinternal=True):
    if isinternal:
        cachename = 'test-internal-token'
        data = {'client_name': 'admin', 'client_password': '******'}
    else:
        cachename = 'test-noninternal-token'
        data = {'client_name': 'non-admin', 'client_password': '******'}

    token = cache.get(cachename)

    if token is None:
        # data={
        #     'client_name':'admin',
        #     'client_password':'******'
        # }
        req = app.test_client(request)
        res = req.get('/login', query_string=data)

        res_json = json.loads(res.data)
        logging.warning('RESULT: %s', res_json)

        if res.status_code == 200:
            assert res.status_code == 200
            cache.set(cachename, res_json['token'], timeout=60)
            return res_json['token']
        else:
            pass
    else:
        return token
コード例 #24
0
ファイル: __init__.py プロジェクト: ammar2621/HappyTrashFlask
def createTokenUser():
    token = cache.get('token-user')
    if token is None:
        # prepare request input
        data = {'email': '*****@*****.**', 'password': '******'}

        # do request
        req = call_client(request)
        res = req.post('/v1/auth',
                       data=json.dumps(data),
                       content_type='application/json')

        # store response
        res_json = json.loads(res.data)

        logging.warning('RESULT : %s', res_json)

        # assert / compare with expected result
        assert res.status_code == 200

        # save token into cache
        cache.set('token-user', res_json['token'], timeout=60)

        # return because it useful for other test
        return res_json['token']
    else:
        return token
コード例 #25
0
def index(key):
    """Confirm with the user that the requested action is to be performed."""
    message = cache.get('{0}/message'.format(key))
    agreement = cache.get('{0}/agreement'.format(key))
    severity = cache.get('{0}/severity'.format(key))
    backward = cache.get('{0}/previous'.format(key))
    forward = cache.get('{0}/next'.format(key))

    form = ConfirmationForm()

    if form.validate_on_submit():
        if form.confirmed.data:
            cache.set(forward, True)
            return redirect(forward)
        else:
            return redirect(backward)

    form.confirmed.label.text = agreement
    flash(message, severity)
    page_vars = {
        'title': 'Confirm Action',
        'form': form,
        'cancel_path': backward
    }
    return render_template('confirm/index.html', **page_vars)
コード例 #26
0
    def getData(self, collection_id):
        from app import cache
        cache_key = 'collection_' + str(collection_id)
        collection_data = cache.get(cache_key)
        if collection_data:
            return collection_data

        cursor = mysql.connect().cursor()
        cursor.execute(
            """SELECT c.*, 
            (select group_concat(ci.item_id order by ci.sort_order asc separator ',') from collections_items ci 
            where ci.collection_id = c.collection_id) as item_ids,
            (select group_concat(concat(cm.meta_key,":",cm.meta_value) separator '&') from collections_metadata cm 
            where cm.collection_id = c.collection_id) as metadata
            FROM collections c WHERE c.collection_id = %s""",
            (collection_id, ))
        data = Utils.fetchOneAssoc(cursor)

        if data['metadata']:
            collections_metadata_raw = data['metadata']
            data['metadata'] = {}
            for props in collections_metadata_raw.split('&'):
                props_formatted = props.split(':')
                data['metadata'][props_formatted[0]] = props_formatted[1]

        if data['item_ids']:
            data['item_ids'] = [int(_) for _ in data['item_ids'].split(',')]
            data['items'] = Search().getById(data['item_ids'])
        else:
            data['items'] = []

        if not data:
            data = {}
        cache.set(cache_key, data)
        return data
コード例 #27
0
def create_token(role):
    if role == 'officer':
        cache_user = "******"
    elif role == 'surveyor':
        cache_user = "******"
    else:
        cache_user = "******"
    token = cache.get(cache_user)
    if token is None:
        # prepare request input
        if role == 'officer':
            data = {"nip": "P2001", "pin": "11223344"}
        elif role == 'surveyor':
            data = {"nip": "P2002", "pin": "11223344"}
        else:
            data = {"npwpd": "P1002", "pin": "11223344"}
        # do request
        req = call_user(request)
        res = req.post("/login/", json=data)
        # store response
        res_json = json.loads(res.data)
        logging.warning("RESULT: %s", res_json)
        # compare with expected result
        assert res.status_code == 200
        assert res_json["message"] == "Token is successfully created"
        # save token into cache
        cache.set(cache_user, res_json["token"], timeout=30)
        # return
        return res_json["token"]
    return token
コード例 #28
0
def create_token(role):
    if role == "user":
        cachename = 'test-token-user'
        data = {
            'username': '******',
            'password': "******"
        }
    elif role == "agent":
        cachename = 'test-token-agent'
        data = {
            'username': '******',
            'password': "******"
        }
    elif role == "seller":
        cachename = 'test-token-seller'
        data = {
            'username': '******',
            'password': "******"
        }
    elif role == "ok":
        cachename = 'test-token-admin'
        data = {
            'username': '******',
            'password': "******"
        }
    token = cache.get(cachename)
    if token is not None:
        return token
    req = call_client(request)
    res = req.get('/login', query_string=data)
    resjson = json.loads(res.data)
    logging.warning('RESULT: %s', resjson)
    assert res.status_code==200
    cache.set(cachename, resjson['token'], timeout=60)
    return resjson['token']
コード例 #29
0
def create_token_noninternal():
    token = cache.get('test-token-noninternal')

    if token is None:
        ##prepare request input
        data = {'client_id': 'testusername', 'client_secret': 'testpassword'}
        # do request

        req = call_client(request)
        res = req.post('/login',
                       data=json.dumps(data),
                       content_type='application/json')

        ## store responese
        res_json = json.loads(res.data)

        logging.warning('RESULT : %s', res_json)

        # assert /compare with expected result
        assert res.status_code == 200

        ## save token into cache
        cache.set('test-token-noninternal', res_json['token'], timeout=60)

        ## return, because it useful for other test
        return res_json['token']
    else:
        return token
コード例 #30
0
def create_token_noninternal():
    token = cache.get('test-token-noninternal')

    if token is None:
        ##prepare request input
        data = {'client_key': 'CLIENT01', 'client_secret': 'SECRET01'}
        # do request

        req = call_client(request)
        res = req.get('/token', query_string=data)

        ## store responese
        res_json = json.loads(res.data)

        logging.warning('RESULT : %s', res_json)

        # assert /compare with expected result
        assert res.status_code == 200

        ## save token into cache
        cache.set('test-token-noninternal', res_json['token'], timeout=60)

        ## return, because it useful for other test
        return res_json['token']
    else:
        return token
コード例 #31
0
ファイル: views.py プロジェクト: smallmeet/websth.com
def show_tech_json(title, page=1, pagesize=app.config['PAGE_SIZE']):
    result = cache.get('tech_' + title + '_website_' + str(page) + '_' +
                       str(pagesize))

    if not result:
        websites = Website.query\
                    .filter(Website.technologies.any(Technology.title == title))\
                    .order_by(Website.frequency.desc())\
                    .paginate(page, pagesize, True)

        websites.items = filter_website(websites.items)
        result = []

        for i in websites.items:
            techs = []
            for t in i.technologies:
                if t.title != 'Unknown':
                    techs.append({'title': t.title, 'detail': t.detail})
            result.append({
                'hostname': i.hostname,
                'port': i.port,
                'technologies': techs
            })

        cache.set('tech_' + title + '_website_' + str(page) + '_' +
                  str(pagesize),
                  result,
                  timeout=app.config['SQL_CACHE_TIMEOUT'])

    return jsonify(status='ok', page=page, pagesize=pagesize, websites=result)
コード例 #32
0
ファイル: views.py プロジェクト: smallmeet/websth.com
def get_top_technology(category, order='DESC', limit=5):
    """获取最高使用率的不同种类的技术类型"""
    result = cache.get('top_' + category + '_item_' + order)
    if result is None:

        rs = db.session.execute(
            'select technology.title, count(website.id) from website \
                                left join website_tech on website_tech.website_id = website.id \
                                left join technology on technology.id = website_tech.tech_id \
                                and technology.title in (\
                                    select distinct technology.title from technology \
                                    where technology.category = \'' +
            category + '\' \
                                    and technology.title != \'Unknown\') \
                                group by technology.title \
                                order by count(website.id) ' + order +
            ' limit 1,' + str(limit))

        # 添加网站总数
        result = []
        for i in rs:
            if i[0] and i[0] != 'Unknown':
                result.append({'title': i[0], 'total': i[1]})
        cache.set('top_' + category + '_item_' + order,
                  result,
                  timeout=app.config['SQL_CACHE_TIMEOUT'])
    return result
コード例 #33
0
ファイル: column_views.py プロジェクト: nciefeiniu/PBlog
def set_article_cache(column_id, column_url, id):
    """设置专栏文章缓存"""
    articles = get_all_articles_cache(column_id, 'column_' + column_url)

    article = Article.query.get_or_404(id)
    # I don't even know what I did.
    _data = {
        'id': article.id,
        'title': article.title,
        'secrecy': article.secrecy
    }
    prev_article = next_article = None
    if articles[0] != _data:
        prev_article = articles[int(articles.index(_data)) - 1]
    if articles[-1] != _data:
        next_article = articles[int(articles.index(_data)) + 1]
    data = article.to_dict()
    data['next_article'] = {
        'id': next_article['id'],
        'title': next_article['title']
    } if next_article else None
    data['prev_article'] = {
        'id': prev_article['id'],
        'title': prev_article['title']
    } if prev_article else None
    cache_key = '_'.join(['article', column_url, str(id)])
    cache.set(cache_key, data, timeout=60 * 60 * 24 * 30)
    return data
コード例 #34
0
ファイル: __init__.py プロジェクト: zulyanor/project_rest_api
def create_token_internal():
    token = cache.get('token-internal')
    if token is None:
        ## prepare request input
        data = {
            'client_key': 'aul',
            'client_secret': '123'
        }

        ## do request
        req = call_client(request)
        res = req.get('/login',
                        query_string=data) # seperti nembak API luar (contoh weather.io)

        ## store response
        res_json = json.loads(res.data)

        logging.warning('RESULT : %s', res_json)

        ## assert / compare with expected result
        assert res.status_code == 200

        ## save token into cache
        cache.set('token-internal', res_json['token'], timeout=60)

        ## return because it useful for other test
        return res_json['token']
    else:
        return token
        
            
コード例 #35
0
    def get(self, params):
        # 查询首页顶部用户
        if params["position"] == 1:
            return self.home_top_user_request(params)

        # 查询首页下部推荐用户中的活跃用户
        active_user_list = []

        # 查询所有缓存的活跃用户
        if params["refresh"] == 0 and (params["last_id"] != 0
                                       or params["offset"] != 0):
            cache_user_list = cache.get(self.home_active_user_cache_key)
            if cache_user_list:
                active_user_list = cache_user_list

        # 如果没有缓存的活跃用户,则查询数据库,并重新缓存结果
        if not active_user_list and params["refresh"] == 0:
            active_user_list = HomeRecommendModel.query_home_active_users(
                24, params)
            if active_user_list:
                cache.set(self.home_active_user_cache_key, active_user_list,
                          self.home_active_user_cache_time)

        # 从缓存的活跃用户中分页获取要显示的用户列表
        offset = params["offset"]
        if offset == 0:
            result_list = active_user_list[params["last_id"]:offset +
                                           self.per_page]
            if not result_list:
                result_list = []
        else:
            result_list = []

        # 如果缓存用户不足一页,则从home_recommend表中随机查询其它的用户
        if result_list and len(result_list) < self.per_page:
            params["active_ids"] = array_column(result_list, "user_id")

        params["limit"] = self.per_page - len(result_list)
        if params["limit"] > 0:
            params["active_list"] = array_column(active_user_list, "user_id")

            if not params["offset"]:
                db_count = db.session.query(func.count(
                    HomeRecommendModel.id)).scalar()
                params["offset"] = randint(1, db_count) if db_count else 0
                params["last_id"] = 0

            result_list_add = HomeRecommendModel.query_home_random_users(
                params)
        else:
            result_list_add = []

        # 合并活跃用户和普通用户
        home_recommend = result_list + result_list_add

        if not home_recommend:
            return json_success_response([])

        return json_success_response(
            HomeRecommendHandler.format_home_users(home_recommend))
コード例 #36
0
ファイル: user_black.py プロジェクト: Eastwu5788/heron
    def query_black_people(user_id, refresh=False):
        """
        查询被我拉黑或我拉黑的用户的列表
        :param user_id: 查询用户id
        :param refresh: 是否刷新缓存
        """
        cache_key = cache_black_key + str(user_id)
        if not refresh:
            result = cache.get(cache_key)
            if result:
                return result

        black_model_list = UserBlackModel.query.filter_by(user_id=user_id, status=1).all()
        if not black_model_list:
            black_model_list = []

        black_id_list = array_column(black_model_list, "black_user_id")

        be_black_model_list = UserBlackModel.query.filter_by(black_user_id=user_id, status=1).all()
        if not be_black_model_list:
            be_black_model_list = []

        be_black_id_list = array_column(be_black_model_list, "user_id")

        id_list = list(set(black_id_list).union(set(be_black_id_list)))
        if id_list:
            cache.set(cache_key, id_list)

        return id_list
コード例 #37
0
def create_token_admin_non_super():
    token = cache.get('token-non-super')
    if token is None:
        ## prepare request input
        data = {"username": "******", "password": "******"}

        ## do request
        req = call_client(request)
        res = req.post('/api/login/admin',
                       data=json.dumps(data),
                       content_type='application/json'
                       )  # seperti nembak API luar (contoh weather.io)

        ## store response
        res_json = json.loads(res.data)

        logging.warning('RESULT : %s', res_json)

        ## assert / compare with expected result
        assert res.status_code == 200

        ## save token into cache
        cache.set('token-non-internal', res_json['token'], timeout=60)

        ## return because it useful for other test
        return res_json['token']
    else:
        return token
コード例 #38
0
ファイル: utils.py プロジェクト: PlagueMen/Compact
 def wrapper(*args, **kwargs):
     key = 'memo' + request.path + str(request.form.values())
     key = key.translate(dict.fromkeys(range(33)))
     output = cache.get(key)
     if output is None:
         output = func(*args, **kwargs)
         cache.set(key, output, 3600)
     return output
コード例 #39
0
ファイル: routes.py プロジェクト: schlosser/go-to-sleep
def get_home_page(commits):
    page = cache.get('homepage')
    if page is None:
        users = User.objects()
        page = render_template("home.html", users=users, commits=commits)
        cache.set('homepage', page, timeout=60)
        print 'rendered homepage'
    return page
コード例 #40
0
ファイル: cache.py プロジェクト: mmcnickle/peps
 def decorated_function(*args, **kwargs):
     cache_key = key % request.path
     rv = cache.get(cache_key)
     if rv is not None:
         return rv
     rv = f(*args, **kwargs)
     cache.set(cache_key, rv, timeout=timeout)
     return rv
コード例 #41
0
ファイル: views.py プロジェクト: chungs1/HackerNet
def view(ip):
    cached = cache.get(ip+"page")
    if cached:
        return cached
    else:
        output = urllib2.urlopen("http://"+ip+":1337/profile").read().replace("^url_placeholder^", ip)
        cache.set(ip+"page", output)
        return output
コード例 #42
0
ファイル: music.py プロジェクト: hdavidzhu/wh2_music
def get_playlist():
    current = cache.get('current')
    playlist = cache.get('playlist')
    if playlist == None:
        playlist = []
        cache.set('playlist', playlist)
        #playlist = []
    return current, playlist
コード例 #43
0
ファイル: views.py プロジェクト: jreiher2003/Composite
def top_users(update=False):
    key = "all_uses"
    all_users = cache.get(key)
    if all_users is None or update:
        logging.error("Users DB QUERY")
        all_users = Users.query.all()
        all_users = list(all_users)
        cache.set(key, all_users)
    return all_users 
コード例 #44
0
ファイル: music.py プロジェクト: allevitan/wh2music
def get_playlist():
    """Get the primary keys of the songs in the current playlist"""
    current = cache.get("current")
    playlist = cache.get("playlist")
    if playlist == None:
        playlist = []
        cache.set("playlist", playlist)
        # playlist = []
    return current, playlist
コード例 #45
0
ファイル: views.py プロジェクト: jreiher2003/Composite
def top_arts(update=False):
    key = "top"
    all_art = cache.get(key)
    if all_art is None or update:
        logging.error("DB QUERY")
        all_art = AsciiArt.query.order_by(AsciiArt.id.desc()).all()
        all_art = list(all_art)
        cache.set(key, all_art)
    return all_art
コード例 #46
0
ファイル: views.py プロジェクト: ccp0101/xssreport
def send_script(uri):
    compiled = cache.get(uri)
    if compiled is None:
        try:
            s = Script.get(Script.uri == uri)
            compiled = s.compiled
        except Script.DoesNotExist:
            abort(404)
        cache.set(uri, compiled, timeout=CACHE_TIMEOUT)
    return Response(compiled, status=200, content_type='application/javascript')
コード例 #47
0
ファイル: models.py プロジェクト: kaninfod/musicplayer
def add_collection(path):

    covers = []
    cache.set("covers", covers)
    for file in mp3_files(path):
        try:
            mp3_obj = mp3_file(file)
            #print("%s    %s   -   %s" % (time.strftime("%I:%M:%S"), mp3_obj.song.songtitle, mp3_obj.artist.albumartist))
        except Exception as e:
            print(e)
            print("Something's up with this file %s" % file)
コード例 #48
0
ファイル: views.py プロジェクト: chungs1/HackerNet
def introduce_reply(loc, name):
    ip_dict = cache.get('ip_dict')
    ip_dict[request.remote_addr] = {'name':name, 'location':loc}
    cache.set('ip_dict', ip_dict)

    try:
        pickled = pickle.load(open('pickledUser.p', 'rb'))
    except Exception:
        pickled = {'name': "error", 'location': "error"}
    infodict = {'name':pickled['name'], 'location':pickled['location']}
    return json.dumps(infodict)
コード例 #49
0
ファイル: login.py プロジェクト: ZeusWPI/slotmachien
def request_user_slack(user_id):
    identifier = 'slack_id/%s' % user_id
    username = cache.get(identifier)
    if username is None:
        username = request_username_slack(user_id)
        if username is not None:
            cache.set(identifier, username)
    if username is not None:
        user = User.query.filter_by(username=username.lower()).first()
        return user
    return None
コード例 #50
0
ファイル: user.py プロジェクト: CubexX/confstat-web
    def get(uid):
        cached = cache.get('web_user_{}'.format(uid))

        if cached:
            return cached
        else:
            user = User.where('uid', uid).get()[0]
            if user:
                cache.set('web_user_{}'.format(uid), user)
                return user
            else:
                return False
コード例 #51
0
ファイル: chat.py プロジェクト: CubexX/confstat-web
    def get(cid):
        cached = cache.get("web_chat_{}".format(cid))

        if cached:
            return cached
        else:
            chat = Chat.where("cid", cid).get()[0]
            if chat:
                cache.set("web_chat_{}".format(cid), chat)
                return chat
            else:
                return False
コード例 #52
0
ファイル: music.py プロジェクト: hdavidzhu/wh2_music
def append_song_to_playlist(song):
    global sleeper
    current, playlist = get_playlist()
    if not playlist and not current:
        path = get_path_from_song(song)
        player.loadfile(path)
        song.plays += 1
        current = song.id
        sleeper = start_sleeper(song.length)
    else:
        playlist = playlist + [song.id]
    cache.set('playlist', playlist)
    cache.set('current', current)
    return current, playlist
コード例 #53
0
ファイル: music.py プロジェクト: allevitan/wh2music
def append_song_to_playlist(song):
    """Append a song to the playlist and play it if the playlist is empty."""
    global sleeper
    current, playlist = get_playlist()
    if not playlist and not current:
        path = get_path_from_song(song)
        player.loadfile(path)
        song.plays += 1
        current = song.id
        sleeper = start_sleeper(song.length)
    else:
        playlist = playlist + [song.id]
    cache.set("playlist", playlist)
    cache.set("current", current)
    return current, playlist
コード例 #54
0
def stamps_ranking(page=1, limit=5):
    key = 'stamps/ranking.v1.%s.%s' % (page, limit)
    obj = cache.get(key)

    if obj is None:
        posts, total = Feed.ranking(page=page, limit=limit)

        obj = render_template('main/stamp/partials/_ranking.html',
                              posts=posts,
                              page=page,
                              limit=limit,
                              total=total)

        cache.set(key, obj, 3600)
    return obj
コード例 #55
0
def stamps_welcome(page=1, limit=20):
    key = 'stamps/welcome.v1.%s.%s' % (page, limit)
    obj = cache.get(key)

    if obj is None:
        posts, total = Feed.posts(page=page, limit=limit)

        obj = render_template('main/stamp/partials/_index.html',
                              posts=posts,
                              page=page,
                              limit=limit,
                              total=total)

        cache.set(key, obj, 3600)
    return obj
コード例 #56
0
ファイル: auth.py プロジェクト: daixm/wechat-admin
def get_access_token():
    token = cache.get(TOKEN_KEY)
    token_expired_at = cache.get(TOKEN_EXPIRED_AT_KEY)
    if token:
        return token, token_expired_at
    b = WechatBasic(
        appid=settings.APP_ID,
        appsecret=settings.SECRET)
    print 'get_access_token at:', datetime.datetime.now()
    d = b.get_access_token()
    token = d['access_token']
    expired_at = d['access_token_expires_at']
    cache.set(TOKEN_KEY, token, int(expired_at - time.time())*60)
    cache.set(TOKEN_EXPIRED_AT_KEY, expired_at, int(expired_at - time.time())*60)
    return token, expired_at
コード例 #57
0
ファイル: index.py プロジェクト: CubexX/confstat-web
def index():
    stats = cache.get('web_stats')

    if not stats:
        stats = {
            'users_count': User.all().count(),
            'chats_count': Chat.all().count(),
            'messages_count': sum(u.msg_count for u in UserStat.all())
        }
        cache.set('web_stats', stats, 300)

    return render_template('index.html',
                           page_title='Confstat',
                           users_count=stats['users_count'],
                           chats_count=stats['chats_count'],
                           messgaes_count=stats['messages_count'])
コード例 #58
0
def stamps_category(category, page=1, limit=20):
    key = 'stamps/category.v1.%s.%s.%s' % (category.id, page, limit)
    obj = cache.get(key)

    if obj is None:
        posts, total = Feed.category(category, page=page, limit=limit)

        obj = render_template('main/stamp/partials/_category.html',
                              category=category,
                              posts=posts,
                              page=page,
                              limit=limit,
                              total=total)

        cache.set(key, obj, 3600)
    return obj
コード例 #59
0
ファイル: music.py プロジェクト: hdavidzhu/wh2_music
def next_song():
    global sleeper
    old_sleeper = sleeper
    current, playlist = get_playlist()
    try:
        current = playlist.pop(0)
        song = Song.query.filter_by(id=current).first()
        song.plays += 1
        path = get_path_from_song(song)
        player.loadfile(path)
        db.session.commit()
        sleeper = start_sleeper(song.length)
    except:
        current = None;
        player.stop();
    cache.set('current',current)
    cache.set('playlist', playlist)
    sockets.UpdateNamespace.broadcast('update', {'current':current, 'playlist':playlist})
    old_sleeper.kill()
コード例 #60
0
ファイル: music.py プロジェクト: allevitan/wh2music
def next_song():
    """Start the next song playing and update the playlist."""
    global sleeper
    old_sleeper = sleeper
    current, playlist = get_playlist()
    try:
        current = playlist.pop(0)
        song = Song.query.filter_by(id=current).first()
        song.plays += 1
        path = get_path_from_song(song)
        player.loadfile(path)
        db.session.commit()
        sleeper = start_sleeper(song.length)
    except:
        current = None
        player.stop()
    cache.set("current", current)
    cache.set("playlist", playlist)
    sockets.UpdateNamespace.broadcast("update", {"current": current, "playlist": playlist})
    old_sleeper.kill()