コード例 #1
0
ファイル: base.py プロジェクト: djdduty/mongo
	def to_foreign(self, obj, name, value):
		if value is None and self.generated:
			value = oid()
			
			if name and name[0] not in ('#', '$'):
				setattr(obj, name, value)
			
			return value
		
		return oid(value)
コード例 #2
0
ファイル: test_q.py プロジェクト: marrow/mongo
	def test_equality_op(self, T):
		comb = T.id & T.reply.id
		v = oid()
		q = comb == v
		
		assert q.operations['id'] == v
		assert q.operations['reply.id'] == v
コード例 #3
0
ファイル: test_q.py プロジェクト: bb78657/mongo
    def test_iterable_op(self, T):
        comb = T.id & T.reply.id
        v = oid()
        q = comb.any([v])

        assert q.operations['id']['$in'] == [v]
        assert q.operations['reply.id']['$in'] == [v]
コード例 #4
0
ファイル: test_q.py プロジェクト: bb78657/mongo
    def test_equality_op(self, T):
        comb = T.id & T.reply.id
        v = oid()
        q = comb == v

        assert q.operations['id'] == v
        assert q.operations['reply.id'] == v
コード例 #5
0
ファイル: test_q.py プロジェクト: bb78657/mongo
    def test_basic_op(self, T):
        comb = T.id & T.reply.id
        v = oid()
        q = comb > v

        assert q.operations['id']['$gt'] == v
        assert q.operations['reply.id']['$gt'] == v
コード例 #6
0
ファイル: test_q.py プロジェクト: marrow/mongo
	def test_iterable_op(self, T):
		comb = T.id & T.reply.id
		v = oid()
		q = comb.any([v])
		
		assert q.operations['id']['$in'] == [v]
		assert q.operations['reply.id']['$in'] == [v]
コード例 #7
0
ファイル: test_q.py プロジェクト: marrow/mongo
	def test_basic_op(self, T):
		comb = T.id & T.reply.id
		v = oid()
		q = comb > v
		
		assert q.operations['id']['$gt'] == v
		assert q.operations['reply.id']['$gt'] == v
コード例 #8
0
	def test_foreign_cast_nested(self, Sample):
		class Ref(Document):
			field = Reference(Document, cache=('field.field', ))
		
		val = {'_id': oid('58329b3a927cc647e94153c9'), 'field': {'field': 27}}
		inst = Ref(val)
		
		assert inst.field['field']['field'] == 27
コード例 #9
0
	def test_foreign_cast_string_oid(self, Sample):
		val = '58329b3a927cc647e94153c9'
		
		inst = Sample(field=val)
		
		assert isinstance(inst.field, odict)
		assert inst.field['_id'] == oid(val)
		assert '_cls' not in inst.field
		assert 'foo' not in inst.field
コード例 #10
0
	def test_foreign_cast_dict(self, Sample):
		val = {'_id': oid('58329b3a927cc647e94153c9'), 'foo': 'foo', 'bar': 'bar'}
		
		inst = Sample(field=val)
		
		assert isinstance(inst.field, odict)
		assert inst.field['_id'] == val['_id']
		assert '_cls' not in inst.field
		assert inst.field['foo'] == val['foo']
コード例 #11
0
	def test_foreign_cast_document(self, Sample):
		val = Concrete()
		val['_id'] = oid('58329b3a927cc647e94153c9')
		val.foo = 'foo'
		val.bar = 'bar'
		
		inst = Sample(field=val)
		
		assert isinstance(inst.field, odict)
		assert inst.field['_id'] == val['_id']
		assert inst.field['_cls'] == 'test_reference_cached:Concrete'
		assert inst.field['foo'] == val['foo']
コード例 #12
0
ファイル: pyntrader_site.py プロジェクト: thieman/intrader
def add_group():
    to_add = loads(dict(request.form)['data'][0])

    if to_add['createNew']:
        result = {'name': to_add['group']}
    else:
        q = {'_id': oid(to_add['group'])}
        result = {}

    result['contracts'] = [{'id': x['id'], 'name': x['name']}
                           for x in to_add['contracts']]

    if to_add['createNew']:
        data.contract_groups.insert(result)
    else:
        print q, result
        data.contract_groups.update(q, {'$set': result}, upsert = False)

    return redirect(url_for('settings'), 301)
コード例 #13
0
ファイル: mongo.py プロジェクト: marrow/mongo
	def __get__(self, session, type=None):
		"""Retrieve the session upon first access and cache the result."""
		
		if session is None:
			return self
		
		ctx = session._ctx  # pylint:disable=protected-access
		D = self._Document
		db = ctx.db[self._database]
		docs = db[self._collection]
		project = D.__projection__
		
		result = docs.find_one(D.id == session._id, project)  # pylint:disable=protected-access
		
		if not result:
			result = {'_id': oid(str(session._id))}  # pylint:disable=protected-access
		
		result = session[self.name] = D.from_mongo(result, project.keys())
		
		return result
コード例 #14
0
ファイル: mongo.py プロジェクト: bb78657/mongo
    def __get__(self, session, type=None):
        """Retrieve the session upon first access and cache the result."""

        if session is None:
            return self

        ctx = session._ctx  # pylint:disable=protected-access
        D = self._Document
        db = ctx.db[self._database]
        docs = db[self._collection]
        project = D.__projection__

        result = docs.find_one(D.id == session._id, project)  # pylint:disable=protected-access

        if not result:
            result = {'_id': oid(str(session._id))}  # pylint:disable=protected-access

        result = session[self.name] = D.from_mongo(result, project.keys())

        return result
コード例 #15
0
ファイル: pyntrader_site.py プロジェクト: afcarl/intrader
def add_group():
    to_add = loads(dict(request.form)['data'][0])

    if to_add['createNew']:
        result = {'name': to_add['group']}
    else:
        q = {'_id': oid(to_add['group'])}
        result = {}

    result['contracts'] = [{
        'id': x['id'],
        'name': x['name']
    } for x in to_add['contracts']]

    if to_add['createNew']:
        data.contract_groups.insert(result)
    else:
        print q, result
        data.contract_groups.update(q, {'$set': result}, upsert=False)

    return redirect(url_for('settings'), 301)
コード例 #16
0
ファイル: pyntrader_site.py プロジェクト: afcarl/intrader
def get_contract_names(group_id):
    if group_id == 'no-selection':
        return jsonify(data=[{'id': '', 'name': 'No Group Selected'}])
    rec = data.contract_groups.find_one({'_id': oid(group_id)})
    results = [{'id': x['id'], 'name': x['name']} for x in rec['contracts']]
    return jsonify(data=results)
コード例 #17
0
ファイル: pyntrader_site.py プロジェクト: thieman/intrader
def get_chart_data():

    args = dict(request.args)
    clean_return(args, ['contract-select'])

    group_rec = data.contract_groups.find_one({'_id': oid(args['contract-group'])})

    chart_data = []
    if args['options-order'] == 'both':
        order_types = ['bids', 'offers']
    else:
        order_types = ['bids'] if args['options-order'] == 'bid' else ['offers']

    if args['options-chart'] == 'indiv':

        for contract, order in product(args['contract-select'], order_types):

            this_contract = {'name': ' '.join([[x['name']
                                                for x in group_rec['contracts']
                                                if int(x['id']) == int(contract)][0],
                                               order.title()]),
                             'order': order,
                             'data': []}

            for rec in data.price.find({'contract_id': int(contract)}):

                if rec[order]:
                    this_contract['data'].append([rec['last_update_ts'],
                                                  float(rec[order][0]['price'])])
                else:
                    this_contract['data'].append([rec['last_update_ts'], None])

            chart_data.append(this_contract)
            
    elif args['options-chart'] == 'agg':

        for order in order_types:

            this_agg = {'name': order.title(),
                        'order': order,
                        'data': []}
            latest_prices = {}

            q = {'contract_id': {'$in': [int(x) for x in args['contract-select']]}}
        
            for rec in data.price.find(q,
                                       sort = [['last_update_ts', pymongo.ASCENDING]]):
                
                latest_prices[rec['contract_id']] = float(rec[order][0]['price'])
                
                # add to plot if we have price data for every contract
                if len(latest_prices) == len(args['contract-select']):

                    this_agg['data'].append([rec['last_update_ts'],
                                             sum([x for x
                                                  in latest_prices.itervalues()])])

            chart_data.append(this_agg)

    chart_title = ': '.join([group_rec['name'],
                             'Individual Contracts' if args['options-chart'] == 'indiv'
                             else 'Aggregated Contracts'])

    return jsonify(chart_type = 'stock_default',
                   title = chart_title,
                   data = chart_data)
コード例 #18
0
ファイル: pyntrader_site.py プロジェクト: thieman/intrader
def get_contract_names(group_id):
    if group_id == 'no-selection':
        return jsonify(data = [{'id': '', 'name': 'No Group Selected'}])
    rec = data.contract_groups.find_one({'_id': oid(group_id)})
    results = [{'id': x['id'], 'name': x['name']} for x in rec['contracts']]
    return jsonify(data = results)
コード例 #19
0
ファイル: pyntrader_site.py プロジェクト: thieman/intrader
def delete_group():
    to_delete = dict(request.form)['toDelete'][0]
    data.contract_groups.remove({'_id': oid(to_delete)})
    return redirect(url_for('settings'), 301)
コード例 #20
0
	def test_foreign_cast_numeric_fail(self):
		class Sample(Document):
			field = Reference(Concrete, cache=('foo.1', ))
		
		with pytest.raises(ValueError):
			Sample(oid('58329b3a927cc647e94153c9'))
コード例 #21
0
ファイル: test_objectid.py プロジェクト: bb78657/mongo
	def test_cast_document(self, Sample):
		v = {'_id': oid()}
		inst = Sample(v)
		assert inst.field == v['_id']
コード例 #22
0
ファイル: test_objectid.py プロジェクト: bb78657/mongo
	def test_cast_oid(self, Sample):
		v = oid()
		inst = Sample(v)
		
		assert inst.__data__['field'] is v
コード例 #23
0
ファイル: pyntrader_site.py プロジェクト: afcarl/intrader
def delete_group():
    to_delete = dict(request.form)['toDelete'][0]
    data.contract_groups.remove({'_id': oid(to_delete)})
    return redirect(url_for('settings'), 301)
コード例 #24
0
	def test_foreign_cast_document(self, Sample):
		val = Concrete()
		val['_id'] = oid('58329b3a927cc647e94153c9')
		inst = Sample(val)
		assert isinstance(inst.field, DBRef)
コード例 #25
0
ファイル: pyntrader_site.py プロジェクト: afcarl/intrader
def get_chart_data():

    args = dict(request.args)
    clean_return(args, ['contract-select'])

    group_rec = data.contract_groups.find_one(
        {'_id': oid(args['contract-group'])})

    chart_data = []
    if args['options-order'] == 'both':
        order_types = ['bids', 'offers']
    else:
        order_types = ['bids'
                       ] if args['options-order'] == 'bid' else ['offers']

    if args['options-chart'] == 'indiv':

        for contract, order in product(args['contract-select'], order_types):

            this_contract = {
                'name':
                ' '.join([[
                    x['name'] for x in group_rec['contracts']
                    if int(x['id']) == int(contract)
                ][0],
                          order.title()]),
                'order':
                order,
                'data': []
            }

            for rec in data.price.find({'contract_id': int(contract)}):

                if rec[order]:
                    this_contract['data'].append(
                        [rec['last_update_ts'],
                         float(rec[order][0]['price'])])
                else:
                    this_contract['data'].append([rec['last_update_ts'], None])

            chart_data.append(this_contract)

    elif args['options-chart'] == 'agg':

        for order in order_types:

            this_agg = {'name': order.title(), 'order': order, 'data': []}
            latest_prices = {}

            q = {
                'contract_id': {
                    '$in': [int(x) for x in args['contract-select']]
                }
            }

            for rec in data.price.find(
                    q, sort=[['last_update_ts', pymongo.ASCENDING]]):

                latest_prices[rec['contract_id']] = float(
                    rec[order][0]['price'])

                # add to plot if we have price data for every contract
                if len(latest_prices) == len(args['contract-select']):

                    this_agg['data'].append([
                        rec['last_update_ts'],
                        sum([x for x in latest_prices.itervalues()])
                    ])

            chart_data.append(this_agg)

    chart_title = ': '.join([
        group_rec['name'], 'Individual Contracts'
        if args['options-chart'] == 'indiv' else 'Aggregated Contracts'
    ])

    return jsonify(chart_type='stock_default',
                   title=chart_title,
                   data=chart_data)