コード例 #1
0
ファイル: site.py プロジェクト: zicoapp/phoscc
def catit():
    request_cat_ids = request.form['cats'].split(',')
    photoid = request.form['photoid']
    
    photo = Query(Photo).get(photoid)
    print photo.get('name')
    cat_relation = photo.relation('category')
    previousCats = cat_relation.query().find()

    # Remove previous category
    for cat in previousCats:
        cat_relation.remove(cat)
    
    # Set new category
    for catid in request_cat_ids:
        cat = Query(Category).get(catid)
        print cat.get('name')
        if cat:
            cat_relation.add(cat)

    # photo.set('featured', True if (featured == 'true') else False)

    photo.save()

    alreadyCategorizedCount = Query.do_cloud_query('select count(*) from Photo where category != null').count
    
    return json.dumps({'status':'OK', 'count': alreadyCategorizedCount, 'photoid': photoid});
コード例 #2
0
def _getModelByTag_from_db(algo_type, model_tag):
    '''
    根据tag挑出model,如果tag下的eventType有重复的,选择最新的model.

    Parameters
    ----------
    algo_type: string
      model's name
    tag: string
      model's tag

    Returns
    -------
    recent_models_list: list
      list of model objs
    '''
    logger.debug('[_getModelByTag_from_db] algo_type=%s, model_tag=%s MODELS not in Memory' % (algo_type, model_tag))
    result = Query.do_cloud_query('select * from Model where algoType="%s" and tag="%s"' % (algo_type, model_tag))
    results = result.results

    # get most recent models
    models_label_set = set()
    for model in results:
        models_label_set.add(model.get('eventType'))

    threads = []
    for label in models_label_set:
        # gevent for asyc request
        threads.append(gevent.spawn(async_get_model_by_tag_once, algo_type, model_tag, label))
    gevent.joinall(threads)

    recent_models_list = [thread.value for thread in threads]

    return recent_models_list
コード例 #3
0
 def async_get_model_by_tag_once(algo_type, model_tag, label):
     '''func for gevent
     '''
     result = Query.do_cloud_query('select * from %s where tag="%s" and eventLabel="%s" limit 1 order by -updatedAt'
                                   % (algo_type, model_tag, label))
     results = result.results
     return results[0]
コード例 #4
0
def get_model_by_tag_lable(algo_type, tag, label):
    '''根据tag和label挑出model,如果tag下的label有重复的,选择最新的model.

    Parameters
    ----------
    algo_type: string
      model's name
    tag: string
      model's tag
    label: string
      model's label

    Returns
    -------
    recent_model: Obj
      model obj
    '''
    result = Query.do_cloud_query('select * from %s where tag="%s" and eventLabel="%s" limit 1 order by -updatedAt'
                                  % (algo_type, tag, label))
    results = result.results
    try:
        recent_model = results[0]
    except IndexError, e:
        logger.exception('[get_model_by_tag_label] algo_type=%s, tag=%s, label=%s\n err_msg=%s'
                         % (algo_type, tag, label, str(e)))
        raise IndexError('[IndexError] from func - get_model_by_tag_label, err_msg=%s' % (str(e)))
コード例 #5
0
ファイル: site.py プロジェクト: zicoapp/phoscc
def index():
    total = Query.do_cloud_query('select count(*) from Photo')
    print total.count
    try:
        query = Query(Photo).descending('createdAt').skip(randint(0, total.count))
        cover = query.first()
    except LeanCloudError, e:
        raise e
コード例 #6
0
def async_get_model_by_tag_once(algo_type, model_tag, label):
    '''wrapper func for gevent
    '''
    result = Query.do_cloud_query(
        'select * from Model where algoType="%s" and tag="%s" and eventType="%s" limit 1 order by -updatedAt'
        % (algo_type, model_tag, label))
    results = result.results
    return results[0]
コード例 #7
0
ファイル: test_query.py プロジェクト: JasonSam/python-sdk
def test_cloud_query():
    q = Query(GameScore)
    result = q.do_cloud_query('select count(*), * from GameScore where score<11', ['score'])
#     results = result.results
#     assert all(obj in game_scores for obj in results)
#     assert all(obj in results for obj in game_scores)
    assert result.count == 10
    assert result.class_name == 'GameScore'
コード例 #8
0
 def load_stationDataForUserId(self,userId):
     queryResult = Query.do_cloud_query('select * from StationData where userId = ?',userId)
     resultObjests = queryResult.results
     stationData_list = []
     for object in resultObjests:
         stationData_list.append((object.id, object.get('stationNumber'), object.get('stationName'), object.get('stationAddress'), object.get('stationCode'), object.get('positionData'), object.get('userId')))
     station_key = ('objectId', 'stationNumber', 'stationName', 'stationAddress','stationCode', 'positionData', 'userId')
     resultDic = map(lambda x: dict(zip(station_key, x)), stationData_list)
     return resultDic
コード例 #9
0
ファイル: test_query.py プロジェクト: JasonSam/python-sdk
def test_cloud_query():
    q = Query(GameScore)
    result = q.do_cloud_query(
        'select count(*), * from GameScore where score<11', ['score'])
    #     results = result.results
    #     assert all(obj in game_scores for obj in results)
    #     assert all(obj in results for obj in game_scores)
    assert result.count == 10
    assert result.class_name == 'GameScore'
コード例 #10
0
ファイル: site.py プロジェクト: zicoapp/phoscc
def cat():
    photos = Query(Photo).does_not_exists('category').ascending('createdAt').limit(10).find()
    alreadyCategorizedCount = Query.do_cloud_query('select count(*) from Photo where category != null').count
    # havenotCategorizedCount = Query.do_cloud_query('select count(*) from Photo where category = null').count
    # print havenotCategorizedCount
    jsonresult = json.dumps([o.dump() for o in photos])

    categories = Query(Category).ascending('order').find()

    return render_template('site/manage/catit.html', current_photo=photos[0],
            coming_photos=jsonresult, categories=categories, alreadyCategorizedCount=alreadyCategorizedCount)
コード例 #11
0
ファイル: site.py プロジェクト: zicoapp/phoscc
def next_cover():
    data = {}
    total = Query.do_cloud_query('select count(*) from Photo')
    try:
        query = Query(Photo).descending('createdAt').skip(randint(0, total.count))
        cover = query.first()
        data['cover'] = cover.get('url') + '?imageView2/2/w/1920/interlace/1'
        data['original'] = cover.get('url') + '?download'
    except LeanCloudError, e:
        if e.code == 101:  # 服务端对应的 Class 还没创建
            data = {}
        else:
            raise e
コード例 #12
0
 def update_stationDataForOid(self,objectId,newStationName,newStationAddress,newStationCode,newPositionData):
     #根据Oid查询目前值
     funResult = self.search_stationDataForOid(objectId)
     resultDic = funResult[0]
     if funResult != '101':
         #判断新站点名称是否改变
         if resultDic['stationName'] != newStationName:
             #如果改变进行更新
             queryResult = Query.do_cloud_query('update StationData set stationName = ?  where objectId = ?',newStationName,objectId)
         #判断新站点地址是否改变
         if resultDic['stationAddress'] != newStationAddress:
             #如果改变进行更新
             queryResult = Query.do_cloud_query('update StationData set stationAddress = ?  where objectId = ?',newStationAddress,objectId)
         #更新站点编码
         queryResult = Query.do_cloud_query('update StationData set stationCode = ?  where objectId = ?',newStationCode, objectId)
         #更新地图坐标
         queryResult = Query.do_cloud_query('update StationData set positionData = ?  where objectId = ?',newPositionData,objectId)
         funResult = self.search_stationDataForOid(objectId)
         #返回更新后的值
         return funResult
     else:
         #找不到Oid
         return '101'
コード例 #13
0
 def search_stationDataForOid(self,objectId):
     #使用CQL语句查询
     queryResult = Query.do_cloud_query('select * from StationData where objectId = ?',objectId)
     #接收查询结果
     resultObjests = queryResult.results
     #如果结果存在
     if resultObjests:
         #将结果保存至resultDic
         stationData_list = []
         for object in resultObjests:
             stationData_list.append((object.id, object.get('stationNumber'), object.get('stationName'), object.get('stationAddress'), object.get('userId')))
         station_key = ('objectId', 'stationNumber', 'stationName', 'stationAddress', 'userId')
         resultDic = map(lambda x: dict(zip(station_key, x)), stationData_list)
         return resultDic
     else:
         return '101'
コード例 #14
0
ファイル: site.py プロジェクト: zicoapp/phoscc
def tag():
    """Tag Photo"""
    form = MultiTagForm()
    if form.validate_on_submit():
        tags = form.data['tags'].split(',')

        photo = Query(Photo).get(form.data['photoid'])
        relation = photo.relation('tags')

        for tag in tags:
            # Obtain existed tag by name
            results = Query(Tag).equal_to('name', tag).find()
            if len(results) != 0:
                avostag = results[0]
                avostag.increment('count', 1)
            else:
                avostag = Tag()
                avostag.set('name', tag)
                avostag.save()
            contributors = avostag.relation('contributors')
            contributors.add(g.user)
            avostag.save()
            # Add relation to photo
            relation.add(avostag)
        photo.save()

        query = Relation.reverse_query('Tag', 'contributors', g.user)
        count = query.count()
        return render_template('site/tag/done.html', user_tag_count=count)
    else:
        total = Query.do_cloud_query('select count(*) from Photo')
        try:
            # query = Query(Photo).descending('createdAt').skip(randint(0, total.count))
            # item = query.first()
            query = Query(Photo).descending('createdAt').skip(randint(0, total.count)).limit(5)
            results = query.find()

            jsonresult = json.dumps([o.dump() for o in results])

            query = Relation.reverse_query('PhotoTag', 'contributors', g.user)
            count = query.count()

            categories = Query(Category).find()
            return render_template('site/tag/tag.html', current_photo=results[0],
                coming_photos=jsonresult, utagcount=count, categories=categories, form=form)
        except LeanCloudError, e:
            return redirect(url_for('site.about'))
コード例 #15
0
 def search_stationDataForBlurryFromUserId(self,stationName,userId):
     #使用CQL语句查询
     #queryResult = Query.do_cloud_query('select * from StationData where stationName like "%?%"', stationName)
     queryResult = Query.do_cloud_query('select * from StationData where userId = ? and stationName like "%'+ stationName +'%"', userId)
     #接收查询结果
     resultObjests = queryResult.results
     #如果结果存在
     if resultObjests:
         #将结果保存至resultDic
         stationData_list = []
         for object in resultObjests:
             stationData_list.append((object.id, object.get('stationNumber'), object.get('stationName'), object.get('stationAddress'),object.get('stationCode'), object.get('positionData'), object.get('userId')))
         station_key = ('objectId', 'stationNumber', 'stationName', 'stationAddress', 'stationCode','positionData', 'userId')
         resultDic = map(lambda x: dict(zip(station_key, x)), stationData_list)
         return resultDic
     else:
         return '101'
コード例 #16
0
 def del_stationDataForOid(self,objectId):
     #搜索oId是否存在
     funResult = self.search_stationDataForOid(objectId)
     #!=101代表search_stationDataForOid方法搜索有结果
     if funResult != '101':
         #删除该对象
         resultData = Query.do_cloud_query('delete from StationData where objectId = ?',objectId)
         #删除后再次搜索
         funResult = self.search_stationDataForOid(objectId)
         #如果搜索无结果
         if funResult is '101':
             #返回删除成功
             return '100'#成功,搜索无结果
         else:
             return '102'#失败,搜索有结果
     else:
         #objectId没有找到
         return '101'
コード例 #17
0
 def load_stationData(self,stationName,userId):
     queryResult = Query.do_cloud_query('select * from StationData')
     # 接收查询结果
     resultObjests = queryResult.results
     # 如果结果存在
     if resultObjests:
         # 将结果保存至resultDic
         stationData_list = []
         for object in resultObjests:
             stationData_list.append((object.id, object.get('stationNumber'), object.get('stationName'),
                                      object.get('stationAddress'), object.get('stationCode'),
                                      object.get('positionData'), object.get('userId')))
         station_key = (
         'objectId', 'stationNumber', 'stationName', 'stationAddress', 'stationCode', 'positionData', 'userId')
         resultDic = map(lambda x: dict(zip(station_key, x)), stationData_list)
         return resultDic
     else:
         return '101'
コード例 #18
0
def query_config(config_name='pois_type'):
    '''
    query config related to poi

    Parameters
    ----------
    config_name: string

    Returns
    -------
    poi_configs: dict
    '''
    result = Query.do_cloud_query('select value from config where name="%s"' % (config_name))
    results = result.results

    if len(results) == 0:
        return {}

    poi_configs = results[0].get('value')
    return poi_configs
コード例 #19
0
ファイル: site.py プロジェクト: zicoapp/phoscc
def next4tag():
    data = {}
    total = Query.do_cloud_query('select count(*) from Photo')
    try:
        query = Query(Photo).descending('createdAt').skip(randint(0, total.count)).limit(5)
        results = query.find()

        jsonresult = json.dumps([o.dump() for o in results])

        return jsonify(result=jsonresult)
        # data['photo_id'] = photo.id
        # data['photo_url'] = photo.get('url')
        # tags_relation = photo.relation('tags')
        # tags_count = tags_relation.query().count()
        # data['tags_count'] = tags_count
    except LeanCloudError, e:
        if e.code == 101:  # 服务端对应的 Class 还没创建
            data = {}
        else:
            raise e
コード例 #20
0
def add_mark():
    data = json.loads(request.data.decode('utf-8'))
    name = data['name']
    content = data['content']
    lines = data['lines']
    query.equal_to("name", name)
    if query.find():
        mark = query.find()[0]
        name = mark.id
        cql = 'update Mark set content = ?, lines = ? where objectId = ?'
        result = Query.do_cloud_query(cql, content, lines, name)
    else:
        mark = Mark(content=content, name=name, lines=lines)
        try:
            mark.save()
        except LeanCloudError as e:
            return e.error, 502
    response = json.dumps({
        "status": 200,
    })
    return response
コード例 #21
0
def query_config(config_name='pois_type'):
    '''
    query config related to poi

    Parameters
    ----------
    config_name: string

    Returns
    -------
    poi_configs: dict
    '''
    result = Query.do_cloud_query('select value from config where name="%s"' %
                                  (config_name))
    results = result.results

    if len(results) == 0:
        return {}

    poi_configs = results[0].get('value')
    return poi_configs
コード例 #22
0
def _getModelByTag_from_db(algo_type, model_tag):
    '''
    根据tag挑出model,如果tag下的eventType有重复的,选择最新的model.

    Parameters
    ----------
    algo_type: string
      model's name
    tag: string
      model's tag

    Returns
    -------
    recent_models_list: list
      list of model objs
    '''
    logger.debug(
        '[_getModelByTag_from_db] algo_type=%s, model_tag=%s MODELS not in Memory'
        % (algo_type, model_tag))
    result = Query.do_cloud_query(
        'select * from Model where algoType="%s" and tag="%s"' %
        (algo_type, model_tag))
    results = result.results

    # get most recent models
    models_label_set = set()
    for model in results:
        models_label_set.add(model.get('eventType'))

    threads = []
    for label in models_label_set:
        # gevent for asyc request
        threads.append(
            gevent.spawn(async_get_model_by_tag_once, algo_type, model_tag,
                         label))
    gevent.joinall(threads)

    recent_models_list = [thread.value for thread in threads]

    return recent_models_list
コード例 #23
0
def get_model_by_tag(algo_type, tag):
    '''
    根据tag挑出model,如果tag下的label有重复的,选择最新的model.

    Parameters
    ----------
    algo_type: string
      model's name
    tag: string
      model's tag

    Returns
    -------
    recent_models_list: list
      list of model objs
    '''
    #TODO: Algo 扔到外面
    Algo = Object.extend(algo_type)
    query = Query(Algo)
    query.equal_to("tag", tag)
    results = _find(query)

    # get most recent models
    models_label_set = set()
    for model in results:
        models_label_set.add(model.get('eventLabel'))

    recent_models_list = []
    for label in models_label_set:
        #TODO: 性能问题,有时间改
        result = Query.do_cloud_query(
            'select * from %s where tag="%s" and eventLabel="%s" limit 1 order by -updatedAt'
            % (algo_type, tag, label))
        results = result.results
        recent_models_list.append(results[0])

    return recent_models_list
コード例 #24
0
def get_model_by_tag_lable(algo_type, tag, label):
    '''根据tag和label挑出model,如果tag下的label有重复的,选择最新的model.

    Parameters
    ----------
    algo_type: string
      model's name
    tag: string
      model's tag
    label: string
      model's label

    Returns
    -------
    recent_model: Obj
      model obj
    '''
    result = Query.do_cloud_query(
        'select * from %s where tag="%s" and eventLabel="%s" limit 1 order by -updatedAt'
        % (algo_type, tag, label))
    results = result.results
    recent_model = results[0]

    return recent_model
コード例 #25
0
ファイル: test_query.py プロジェクト: leancloud/python-sdk
def test_cloud_query(): # type: () -> None
    q = Query(GameScore)
    result = q.do_cloud_query('select count(*), * from GameScore where score<11', ['score'])
    assert result.count == 10
    assert result.class_name == 'GameScore'
コード例 #26
0
def saveData(price, title, introduce):
  #init leancloud
  leancloud.init('IRLv1lvUGypwG5XCKF248SiG-gzGzoHsz', '2lRAArUswyFeFTtIXl2wC6b5')
  #sql
  Query.do_cloud_query("insert into table_prjList(price, title, introduce) values(?, ?, ?)", price, title, introduce)
コード例 #27
0
ファイル: test_query.py プロジェクト: rickyfunfun/python-sdk
def test_cloud_query():  # type: () -> None
    q = Query(GameScore)
    result = q.do_cloud_query(
        'select count(*), * from GameScore where score<11', ['score'])
    assert result.count == 10
    assert result.class_name == 'GameScore'
コード例 #28
0
def test_cloud_query():  # type: () -> None
    q = Query(GameScore)
    result = q.do_cloud_query(
        "select count(*), * from GameScore where score<11", ["score"])
    assert result.count == 10
    assert result.class_name == "GameScore"