Пример #1
0
    def setUpTestData(cls):

        sites = (
            Site(name='Test Site 1', slug='test-site-1'),
            Site(name='Test Site 2', slug='test-site-2'),
            Site(name='Test Site 3', slug='test-site-3'),
        )
        Site.objects.bulk_create(sites)

        circuit_types = (
            CircuitType(name='Test Circuit Type 1', slug='test-circuit-type-1'),
        )
        CircuitType.objects.bulk_create(circuit_types)

        providers = (
            Provider(name='Provider 1', slug='provider-1'),
        )
        Provider.objects.bulk_create(providers)

        circuits = (
            Circuit(provider=providers[0], type=circuit_types[0], cid='Test Circuit 1'),
            Circuit(provider=providers[0], type=circuit_types[0], cid='Test Circuit 2'),
            Circuit(provider=providers[0], type=circuit_types[0], cid='Test Circuit 3'),
        )
        Circuit.objects.bulk_create(circuits)

        circuit_terminations = ((
            CircuitTermination(circuit=circuits[0], site=sites[0], term_side='A', port_speed=1000, upstream_speed=1000, xconnect_id='ABC'),
            CircuitTermination(circuit=circuits[0], site=sites[1], term_side='Z', port_speed=1000, upstream_speed=1000, xconnect_id='DEF'),
            CircuitTermination(circuit=circuits[1], site=sites[1], term_side='A', port_speed=2000, upstream_speed=2000, xconnect_id='GHI'),
            CircuitTermination(circuit=circuits[1], site=sites[2], term_side='Z', port_speed=2000, upstream_speed=2000, xconnect_id='JKL'),
            CircuitTermination(circuit=circuits[2], site=sites[2], term_side='A', port_speed=3000, upstream_speed=3000, xconnect_id='MNO'),
            CircuitTermination(circuit=circuits[2], site=sites[0], term_side='Z', port_speed=3000, upstream_speed=3000, xconnect_id='PQR'),
        ))
        CircuitTermination.objects.bulk_create(circuit_terminations)
Пример #2
0
def test_recsys(request, gmac_slug=None):
    """
    Testing recsys view
    """
    from recsys.circuits.circuit_recsys import CircuitRecsys

    # Find GMAC
    gmacs = None
    gmac_id = None
    gmac_get_short_formatted_name = None
    filtered_circuits = None
    if gmac_slug is not None:
        try:
            gmacs = GMAC.objects.filter(slug=gmac_slug)
            filtered_circuits = Circuit.filter_by_gmacs(gmacs)
            gmac_get_short_formatted_name = gmacs[0].get_short_formatted_name()
            gmac_id = gmacs[0].pk
        except GMAC.DoesNotExist:
            pass
        except IndexError:
            pass
    
    categories = circuit_category_list()

    if request.user.is_authenticated():
        # Recsys functionallity
        recsys = CircuitRecsys(request.user.pk)
        if gmac_id is None:
            gmac_id = request.session.get('gmac_id', None)
        if gmac_id is not None:
            recsys.Set_gmac(gmac_id)
        circuits_ids = recsys.Give_me_the_fun(top_n=15)
        circuits = Circuit.objects.filter(id__in=circuits_ids).\
            filter(published=True)

        if filtered_circuits is not None : 
            circuits = [val for val in filtered_circuits if val in circuits]

    else:
        if gmac_id is not None:
            gmac = GMAC.objects.get(pk=gmac_id)
            circuits = Circuit.filter_by_gmac(gmac)
        else:
            # case when gmac is not detected
            cpp = circuit_settings.DEFAULT_CIRCUITS_LIMIT
            circuits=Circuit.objects.all()[:cpp]

    return render(request,
        'circuits/recommendations.html',
        {
            'categories': categories,
            'circuits': circuits,
            'topbar_item': 'explore',
            'page_type': 'recommendation',
            'GOOGLE_API_KEY': settings.GOOGLE_API_KEY,
            'gmac_slug': gmac_slug,
            'gmacs': gmacs,
            'gmac_get_short_formatted_name': gmac_get_short_formatted_name,
        },
    )
Пример #3
0
    def run(self, new_users=None):

        if new_users == None:
            #SELECT id, circuits_to_create FROM users
            #WHERE circuits_to_create > 0;
            all_users = SimUser.objects.filter(circuits_to_create__gt=0)
        else:
            #all_users = SimUser.objects.order_by((SimUser.id).desc()).limit(new_users)
            pass

        cct_name = 'circuit_'
        cct_count = 0
        new_circuits = 0

        session_counter = 0
        print colored.white("Generating circuits:")
        for usuario in progress.bar(all_users):
            for i_circuit in xrange(usuario.circuits_to_create):

                circuit = Circuit(name=cct_name + str(cct_count),
                                  author=usuario.user,
                                  rating=0,
                                  category=random.randint(0, 25))

                cct_count += 1
                session_counter += 1
                circuit.save()
                new_circuits += 1

                if session_counter >= 5000:
                    session_counter = 0
                    transaction.commit()

        transaction.commit()
Пример #4
0
    def setUpTestData(cls):

        providers = (
            Provider(name='Provider 1', slug='provider-1', asn=65001),
            Provider(name='Provider 2', slug='provider-2', asn=65002),
        )
        Provider.objects.bulk_create(providers)

        circuittypes = (
            CircuitType(name='Circuit Type 1', slug='circuit-type-1'),
            CircuitType(name='Circuit Type 2', slug='circuit-type-2'),
        )
        CircuitType.objects.bulk_create(circuittypes)

        Circuit.objects.bulk_create([
            Circuit(cid='Circuit 1',
                    provider=providers[0],
                    type=circuittypes[0]),
            Circuit(cid='Circuit 2',
                    provider=providers[0],
                    type=circuittypes[0]),
            Circuit(cid='Circuit 3',
                    provider=providers[0],
                    type=circuittypes[0]),
        ])

        tags = cls.create_tags('Alpha', 'Bravo', 'Charlie')

        cls.form_data = {
            'cid': 'Circuit X',
            'provider': providers[1].pk,
            'type': circuittypes[1].pk,
            'status': CircuitStatusChoices.STATUS_DECOMMISSIONED,
            'tenant': None,
            'install_date': datetime.date(2020, 1, 1),
            'commit_rate': 1000,
            'description': 'A new circuit',
            'comments': 'Some comments',
            'tags': [t.pk for t in tags],
        }

        cls.csv_data = (
            "cid,provider,type",
            "Circuit 4,Provider 1,Circuit Type 1",
            "Circuit 5,Provider 1,Circuit Type 1",
            "Circuit 6,Provider 1,Circuit Type 1",
        )

        cls.bulk_edit_data = {
            'provider': providers[1].pk,
            'type': circuittypes[1].pk,
            'status': CircuitStatusChoices.STATUS_DECOMMISSIONED,
            'tenant': None,
            'commit_rate': 2000,
            'description': 'New description',
            'comments': 'New comments',
        }
Пример #5
0
    def setUpTestData(cls):
        SIDE_A = CircuitTerminationSideChoices.SIDE_A
        SIDE_Z = CircuitTerminationSideChoices.SIDE_Z

        sites = (
            Site(name='Site 1', slug='site-1'),
            Site(name='Site 2', slug='site-2'),
        )
        Site.objects.bulk_create(sites)

        provider = Provider.objects.create(name='Provider 1',
                                           slug='provider-1')
        circuit_type = CircuitType.objects.create(name='Circuit Type 1',
                                                  slug='circuit-type-1')

        circuits = (
            Circuit(cid='Circuit 1', provider=provider, type=circuit_type),
            Circuit(cid='Circuit 2', provider=provider, type=circuit_type),
            Circuit(cid='Circuit 3', provider=provider, type=circuit_type),
        )
        Circuit.objects.bulk_create(circuits)

        circuit_terminations = (
            CircuitTermination(circuit=circuits[0],
                               site=sites[0],
                               port_speed=100000,
                               term_side=SIDE_A),
            CircuitTermination(circuit=circuits[0],
                               site=sites[1],
                               port_speed=100000,
                               term_side=SIDE_Z),
            CircuitTermination(circuit=circuits[1],
                               site=sites[0],
                               port_speed=100000,
                               term_side=SIDE_A),
            CircuitTermination(circuit=circuits[1],
                               site=sites[1],
                               port_speed=100000,
                               term_side=SIDE_Z),
        )
        CircuitTermination.objects.bulk_create(circuit_terminations)

        cls.create_data = [
            {
                'circuit': circuits[2].pk,
                'term_side': SIDE_A,
                'site': sites[1].pk,
                'port_speed': 200000,
            },
            {
                'circuit': circuits[2].pk,
                'term_side': SIDE_Z,
                'site': sites[1].pk,
                'port_speed': 200000,
            },
        ]
Пример #6
0
    def setUp(self):

        self.client = Client()

        provider = Provider(name='Provider 1', slug='provider-1', asn=65001)
        provider.save()

        circuittype = CircuitType(name='Circuit Type 1', slug='circuit-type-1')
        circuittype.save()

        Circuit.objects.bulk_create([
            Circuit(cid='Circuit 1', provider=provider, type=circuittype),
            Circuit(cid='Circuit 2', provider=provider, type=circuittype),
            Circuit(cid='Circuit 3', provider=provider, type=circuittype),
        ])
Пример #7
0
    def setUp(self):
        user = create_test_user(permissions=['circuits.view_circuit'])
        self.client = Client()
        self.client.force_login(user)

        provider = Provider(name='Provider 1', slug='provider-1', asn=65001)
        provider.save()

        circuittype = CircuitType(name='Circuit Type 1', slug='circuit-type-1')
        circuittype.save()

        Circuit.objects.bulk_create([
            Circuit(cid='Circuit 1', provider=provider, type=circuittype),
            Circuit(cid='Circuit 2', provider=provider, type=circuittype),
            Circuit(cid='Circuit 3', provider=provider, type=circuittype),
        ])
Пример #8
0
    def Filter_circuits(self):
        """
        Returns a dictionary with all the circuits that are able
        to be recommended to user
        """
        R = RedisQuery(self.user)
        #Get circuits ids user has visited
        #vis_cts_ids = R.user_visited_circuits()

        # Get possibly recommended circuits
        if self.has_gmac:
            # TODO: @mathiasbc , improve with Redis dont query to DB
            all_gmacs_ids = GMAC.get_id_list_from_redis(self.gmac.pk)
            all_gmacs = GMAC.objects.filter(pk__in=all_gmacs_ids)
            circuits = Circuit.filter_by_gmacs(all_gmacs)
            all_circuits = []
            for ct in circuits:
                if ct.pk not in all_circuits:
                    all_circuits.append(ct.pk)
        else:
            all_circuits = R.all_circuits()

        # Initiate scores dict with posible recommendation circuits
        for i in all_circuits:
            #if i not in vis_cts_ids:
            self.scores[i] = 0
Пример #9
0
    def setUpTestData(cls):

        providers = (
            Provider(name='Provider 1', slug='provider-1'),
            Provider(name='Provider 2', slug='provider-2'),
        )
        Provider.objects.bulk_create(providers)

        circuit_types = (
            CircuitType(name='Circuit Type 1', slug='circuit-type-1'),
            CircuitType(name='Circuit Type 2', slug='circuit-type-2'),
        )
        CircuitType.objects.bulk_create(circuit_types)

        circuits = (
            Circuit(cid='Circuit 1',
                    provider=providers[0],
                    type=circuit_types[0]),
            Circuit(cid='Circuit 2',
                    provider=providers[0],
                    type=circuit_types[0]),
            Circuit(cid='Circuit 3',
                    provider=providers[0],
                    type=circuit_types[0]),
        )
        Circuit.objects.bulk_create(circuits)

        cls.create_data = [
            {
                'cid': 'Circuit 4',
                'provider': providers[1].pk,
                'type': circuit_types[1].pk,
            },
            {
                'cid': 'Circuit 5',
                'provider': providers[1].pk,
                'type': circuit_types[1].pk,
            },
            {
                'cid': 'Circuit 6',
                'provider': providers[1].pk,
                'type': circuit_types[1].pk,
            },
        ]
Пример #10
0
    def mutate_and_get_payload(cls, input, context, info):
        provider = input.get('provider')
        type = input.get('type')
        tenant = input.get('tenant')

        temp = Circuit()

        if not_none(provider):
            temp.provider = Provider.objects.get(
                pk=from_global_id(provider)[1])
        if not_none(type):
            temp.type = CircuitType.objects.get(pk=from_global_id(type)[1])
        if not_none(tenant):
            temp.tenant = Tenant.objects.get(pk=from_global_id(tenant)[1])

        fields = [
            'cid', 'install_date', 'commit_rate', 'description', 'comments',
            'custom_field_values'
        ]
        return NewCircuit(circuit=set_and_save(fields, input, temp))
Пример #11
0
    def setUpTestData(cls):

        providers = (
            Provider(name='Provider 1', slug='provider-1', asn=65001, account='1234'),
            Provider(name='Provider 2', slug='provider-2', asn=65002, account='2345'),
            Provider(name='Provider 3', slug='provider-3', asn=65003, account='3456'),
            Provider(name='Provider 4', slug='provider-4', asn=65004, account='4567'),
            Provider(name='Provider 5', slug='provider-5', asn=65005, account='5678'),
        )
        Provider.objects.bulk_create(providers)

        regions = (
            Region(name='Test Region 1', slug='test-region-1'),
            Region(name='Test Region 2', slug='test-region-2'),
        )
        # Can't use bulk_create for models with MPTT fields
        for r in regions:
            r.save()

        sites = (
            Site(name='Test Site 1', slug='test-site-1', region=regions[0]),
            Site(name='Test Site 2', slug='test-site-2', region=regions[1]),
        )
        Site.objects.bulk_create(sites)

        circuit_types = (
            CircuitType(name='Test Circuit Type 1', slug='test-circuit-type-1'),
            CircuitType(name='Test Circuit Type 2', slug='test-circuit-type-2'),
        )
        CircuitType.objects.bulk_create(circuit_types)

        circuits = (
            Circuit(provider=providers[0], type=circuit_types[0], cid='Test Circuit 1'),
            Circuit(provider=providers[1], type=circuit_types[1], cid='Test Circuit 1'),
        )
        Circuit.objects.bulk_create(circuits)

        CircuitTermination.objects.bulk_create((
            CircuitTermination(circuit=circuits[0], site=sites[0], term_side='A', port_speed=1000),
            CircuitTermination(circuit=circuits[1], site=sites[0], term_side='A', port_speed=1000),
        ))
Пример #12
0
    def setUpTestData(cls):

        regions = (
            Region(name='Test Region 1', slug='test-region-1'),
            Region(name='Test Region 2', slug='test-region-2'),
            Region(name='Test Region 3', slug='test-region-3'),
        )
        # Can't use bulk_create for models with MPTT fields
        for r in regions:
            r.save()

        sites = (
            Site(name='Test Site 1', slug='test-site-1', region=regions[0]),
            Site(name='Test Site 2', slug='test-site-2', region=regions[1]),
            Site(name='Test Site 3', slug='test-site-3', region=regions[2]),
        )
        Site.objects.bulk_create(sites)

        tenant_groups = (
            TenantGroup(name='Tenant group 1', slug='tenant-group-1'),
            TenantGroup(name='Tenant group 2', slug='tenant-group-2'),
            TenantGroup(name='Tenant group 3', slug='tenant-group-3'),
        )
        TenantGroup.objects.bulk_create(tenant_groups)

        tenants = (
            Tenant(name='Tenant 1', slug='tenant-1', group=tenant_groups[0]),
            Tenant(name='Tenant 2', slug='tenant-2', group=tenant_groups[1]),
            Tenant(name='Tenant 3', slug='tenant-3', group=tenant_groups[2]),
        )
        Tenant.objects.bulk_create(tenants)

        circuit_types = (
            CircuitType(name='Test Circuit Type 1', slug='test-circuit-type-1'),
            CircuitType(name='Test Circuit Type 2', slug='test-circuit-type-2'),
        )
        CircuitType.objects.bulk_create(circuit_types)

        providers = (
            Provider(name='Provider 1', slug='provider-1'),
            Provider(name='Provider 2', slug='provider-2'),
        )
        Provider.objects.bulk_create(providers)

        circuits = (
            Circuit(provider=providers[0], tenant=tenants[0], type=circuit_types[0], cid='Test Circuit 1', install_date='2020-01-01', commit_rate=1000, status=CircuitStatusChoices.STATUS_ACTIVE),
            Circuit(provider=providers[0], tenant=tenants[0], type=circuit_types[0], cid='Test Circuit 2', install_date='2020-01-02', commit_rate=2000, status=CircuitStatusChoices.STATUS_ACTIVE),
            Circuit(provider=providers[0], tenant=tenants[1], type=circuit_types[0], cid='Test Circuit 3', install_date='2020-01-03', commit_rate=3000, status=CircuitStatusChoices.STATUS_PLANNED),
            Circuit(provider=providers[1], tenant=tenants[1], type=circuit_types[1], cid='Test Circuit 4', install_date='2020-01-04', commit_rate=4000, status=CircuitStatusChoices.STATUS_PLANNED),
            Circuit(provider=providers[1], tenant=tenants[2], type=circuit_types[1], cid='Test Circuit 5', install_date='2020-01-05', commit_rate=5000, status=CircuitStatusChoices.STATUS_OFFLINE),
            Circuit(provider=providers[1], tenant=tenants[2], type=circuit_types[1], cid='Test Circuit 6', install_date='2020-01-06', commit_rate=6000, status=CircuitStatusChoices.STATUS_OFFLINE),
        )
        Circuit.objects.bulk_create(circuits)

        circuit_terminations = ((
            CircuitTermination(circuit=circuits[0], site=sites[0], term_side='A', port_speed=1000),
            CircuitTermination(circuit=circuits[1], site=sites[1], term_side='A', port_speed=1000),
            CircuitTermination(circuit=circuits[2], site=sites[2], term_side='A', port_speed=1000),
        ))
        CircuitTermination.objects.bulk_create(circuit_terminations)
Пример #13
0
    def process_objects(self, author):
        # Circuit
        circuit = Circuit(
            name=self.cleaned_data.get('name', ''),
            category=self.cleaned_data.get('category', ''),
            description=self.clean_description(),
            author=author,
            adult_content=self.cleaned_data['adult_content']
        )

        circuit.save()
        # Topics
        new_topics = []
        all_topics = []
        topic_names = Topic.parse_names(self.cleaned_data('topics', []))
        for tn in topic_names:
            if not Topic.exists(tn):
                topic = Topic.get_or_create(tn)
                new_topics.append(topic)
            else:
                topic = Topic.get_by_name(tn)
            all_topics.append(topic)
        multiple = False
        if len(new_topics) > 0:
            multiple = True
        # Add topics to circuit
        for topic in all_topics:
            circuit.topics.add(topic)
        circuit.save()
        return {
            'circuit': circuit,
            'all_topics': all_topics,
            'new_topics': new_topics,
            'multiple': multiple
        }
Пример #14
0
    def get_circuits(self):
        """
        Returns a Queryset containing the circuits to display on
        CircuitCollection
        """
        limit = self.cleaned_data.get('limit')
        offset = self.cleaned_data.get('offset')
        category = self.cleaned_data.get('category')
        gmac_id = self.cleaned_data.get('gmac_id')
        gmac_slug = self.cleaned_data.get('gmac_slug')

        if limit is None:
            limit = constants.API_DEFAULT_CIRCUITS_LIMIT
        if offset is None:
            offset = constants.API_DEFAULT_CIRCUITS_OFFSET

        # try to filter circuit by GMAC
        if gmac_id is not None:
            gmac = GMAC.objects.get(pk=gmac_id)
            circuits = Circuit.filter_by_gmac(gmac)

        # try to filter by gmac_slug
        elif gmac_slug is not None:
            gmacs = GMAC.objects.filter(slug=gmac_slug)
            circuits = Circuit.filter_by_gmacs(gmacs)
        # if not filtered by GMAC then filter by any other criteria
        else:
            circuits = Circuit.objects.all()
            circuits = circuits.order_by('-created')

        if category is not None and len(category)>0:

            if self.category_is_alphanumeric():
                category = CircuitCategory(category)
                category = category.get_value()

            circuits = circuits.filter(category=category)

        return circuits[offset:offset + limit]
Пример #15
0
def test_recsys(request, gmac_slug=None):
    """
    Testing recsys view
    """
    from recsys.circuits.circuit_recsys import CircuitRecsys

    # Find GMAC
    gmacs = None
    gmac_id = None
    gmac_get_short_formatted_name = None
    filtered_circuits = None
    if gmac_slug is not None:
        try:
            gmacs = GMAC.objects.filter(slug=gmac_slug)
            filtered_circuits = Circuit.filter_by_gmacs(gmacs)
            gmac_get_short_formatted_name = gmacs[0].get_short_formatted_name()
            gmac_id = gmacs[0].pk
        except GMAC.DoesNotExist:
            pass
        except IndexError:
            pass
    
    categories = circuit_category_list()

    circuits = Circuit.objects.filter(**params)
    circuits = circuits.filter(published=True)
    circuits = circuits.select_related(depth=3).order_by(
        '-highlighted', '-modified'
    )[:cpp]

    return render(request,
        'circuits/recommendations.html',
        {
            'categories': categories,
            'circuits': circuits,
            'topbar_item': 'explore',
            'page_type': 'recommendation',
            'STATIC_MAPS_ROOT': settings.STATIC_MAPS_ROOT,
            'GOOGLE_API_KEY': settings.GOOGLE_API_KEY,
            'gmac_slug': gmac_slug,
            'gmacs': gmacs,
            'gmac_get_short_formatted_name': gmac_get_short_formatted_name,
        },
    )
Пример #16
0
    def process_objects(self, author):
        name = self.cleaned_data.get('name', u'')
        category = self.cleaned_data.get('category',
                                         constants.DEFAULT_CIRCUIT_CATEGORY)
        description = self.cleaned_data.get('description', u'')

        # Trimming more than one 2 linebreaks to one
        line_breaks = re.search('.*?(\s{2,}).*?', description)
        if line_breaks is not None:
            trimmed_description = description
            for line_break in line_breaks.groups():
                trimmed_description = description.replace(line_break, u'\r\n')
            description = trimmed_description

        # Circuit
        circuit = Circuit(name=name,
                          category=category,
                          description=description,
                          author=author,
                          adult_content=self.cleaned_data.get(
                              'adult_content', False))
        circuit.save()

        # Topics
        new_topics = []
        all_topics = []
        topic_names = Topic.parse_names(self.cleaned_data.get('topics', []))
        for tn in topic_names:
            if not Topic.exists(tn):
                topic = Topic.get_or_create(tn)
                new_topics.append(topic)
            else:
                topic = Topic.get_by_name(tn)
            all_topics.append(topic)

        multiple = False
        if len(new_topics) > 0:
            multiple = True

        # Add topics to circuit
        for topic in all_topics:
            circuit.topics.add(topic)

        circuit.save()

        return {
            'circuit': circuit,
            'all_topics': all_topics,
            'new_topics': new_topics,
            'multiple': multiple
        }
Пример #17
0
def show_home(request, gmac_slug=None):

    # Find GMAC
    gmacs = None
    if gmac_slug is not None:
        try:
            gmacs = GMAC.objects.filter(slug=gmac_slug)
        except GMAC.DoesNotExist:
            pass

    params = {}

    gmac_get_short_formatted_name = None
    if gmacs is not None:
        params['pk__in'] = [c.pk for c in Circuit.filter_by_gmacs(gmacs)]
        gmac_get_short_formatted_name = gmacs[0].get_short_formatted_name()

    cpp = circuit_settings.DEFAULT_CIRCUITS_LIMIT

    if request.is_ajax():
        page = request.POST.get('page', None)
        if page is not None:
            page = int(page)
        else:
            error_doc = OrderedDict()
            error_doc['error'] = unicode(strings.MISSING_PAGE_PARAM_ERROR)
            return HttpResponse(
                content=render_as_json(error_doc),
                content_type='application/json'
            )

        response = {
            'page': int(page) + 1
        }

        circuits = Circuit.objects.filter(**params)
        circuits = circuits.filter(published=True).order_by(
            '-highlighted', '-modified'
        )[page * cpp: cpp * (page + 1)]

        if circuits:
            html_response = u''

            for circuit in circuits:
                html_response += render_to_string(
                    'circuits/circuit_list_item.html',
                    {'circuit': circuit, 'user': request.user})
            response['raw_html'] = html_response
        else:
            response['hide_button'] = True

        return HttpResponse(
            json.dumps(response),
            mimetype='application/json'
        )

    categories = circuit_category_list()

    # Circuits that are not flagged as 18+
    circuits = Circuit.objects.filter(adult_content=False)
    circuits = circuits.filter(published=True).order_by('?')[:cpp]

    return render(request,
        'circuits/recommendations.html',
        {
            'categories': categories,
            'circuits': circuits,
            'topbar_item': 'explore',
            'page_type': 'recommendation',
            'GOOGLE_API_KEY': settings.GOOGLE_API_KEY,
            'gmac_slug': gmac_slug,
            'gmacs': gmacs,
            'gmac_get_short_formatted_name': gmac_get_short_formatted_name,
        },
    )
Пример #18
0
def add_circuits():
    ct = CommunicationsType()
    ct.comm_type = 'Dynamic T1'
    ct.save()
    
    ct2 = CommunicationsType()
    ct2.comm_type = 'EVDO'
    ct2.save()
    
    circuit = Circuit()
    circuit.store = Store.objects.get(pk=2942)
    circuit.primary_vendor = Vendor.objects.all()[0]
    circuit.primary_circuit_id = 'A1awr23'
    circuit.communications_type = CommunicationsType.objects.all()[0]
    circuit.circuit_type = 'P'
    circuit.save()
    
    circuit = Circuit()
    circuit.store = Store.objects.get(pk=2583)
    circuit.primary_vendor = Vendor.objects.all()[0]
    circuit.primary_circuit_id = 'A345-12'
    circuit.communications_type = CommunicationsType.objects.all()[0]
    circuit.circuit_type = 'P'
    circuit.save()
    
    circuit = Circuit()
    circuit.store = Store.objects.get(pk=2811)
    circuit.primary_vendor = Vendor.objects.all()[0]
    circuit.primary_circuit_id = 'A3aer2345'
    circuit.communications_type = CommunicationsType.objects.all()[0]
    circuit.circuit_type = 'P'
    circuit.save()
Пример #19
0
    def read_from_file(self, filename):
        """
        reads places from file
        """
        with open(filename, 'r') as FILE:
            for line in FILE:
                #line = FILE.readline()
                # eliminate \n at end
                line = line.strip()
                self.number_lines += 1
                if line == '@#':
                    guide_title = FILE.next().strip()
                    self.number_lines += 1
                    guide_title = guide_title.replace('-', ' ')
                    guide_author = FILE.next().strip()
                    self.number_lines += 1
                    # returns a user, finding it or creating it
                    author = self.create_or_find_author(guide_author)
                    location = FILE.next().strip()
                    self.number_lines += 1
                    location = location.split('\t')
                    location = location[-1]
                    description = FILE.next().strip().replace('-', ' ')
                    self.number_lines += 1
                    # create circuit
                    # FIXME: decription migth be 'NO-DESCRIPTION' and
                    # category should be somehow matched to a proper category
                    try:
                        new_ct = Circuit.objects.get(
                            name=guide_title,
                            author=author,
                        )
                    except Circuit.DoesNotExist:
                        new_ct = Circuit(
                            name=guide_title,
                            category=4,
                            author=author,
                            description=description[:399],
                            published=True,
                            source=3,
                        )
                    print 'Creating circuit ' + guide_title
                    new_ct.save()
                    # move line 1 position forward so place can read from here
                    line = FILE.next().strip()
                    self.number_lines += 1

                # a place
                fields = line.split('\t')
                place_name = fields[0].replace('-', ' ')
                lat = fields[1]
                lng = fields[2]
                try:
                    desc = fields[3]
                except IndexError:
                    dec = ''
                # invoke process_search and pass fields
                self.process_search(circuit=new_ct,
                                    place_name=place_name,
                                    lat=lat,
                                    lng=lng,
                                    location=location,
                                    description=desc)
Пример #20
0
def circuit_category_listing(request, category_slug, gmac_slug=None):
    """
    Displays the first 10 circuits of a category
    """
    # Find GMAC
    gmacs = None
    if gmac_slug is not None:
        try:
            gmacs = GMAC.objects.filter(slug=gmac_slug)
        except GMAC.DoesNotExist:
            pass

    cpp = circuit_settings.DEFAULT_CIRCUITS_LIMIT

    try:
        category_value = CIRCUIT_CATEGORY_CHOICES.get_value(
            category_slug.upper())
    except KeyError:
        raise Http404

    categories = circuit_category_list()
    category = CircuitCategory(category_value)

    params = {}

    params['category'] = category_value

    gmac_get_short_formatted_name = None
    if gmacs is not None:
        params['pk__in'] = [c.pk for c in Circuit.filter_by_gmacs(gmacs)]
        gmac_get_short_formatted_name = gmacs[0].get_short_formatted_name()

    if request.is_ajax():
        page = request.POST.get('page', None)
        if page is not None:
            page = int(page)
        else:
            error_doc = OrderedDict()
            error_doc['error'] = 'Missing POST parameter: page'
            return HttpResponse(content=render_as_json(error_doc),
                                content_type='application/json')

        response = {'page': int(page) + 1}

        circuits = Circuit.objects.available().filter(
            **params).order_by('-modified')[page * cpp:(page + 1) * cpp]

        if circuits:
            html_response = u''

            for circuit in circuits:
                html_response += render_to_string(
                    'circuits/circuit_list_item.html', {
                        'circuit': circuit,
                        'user': request.user
                    })
            response['raw_html'] = html_response

        else:
            response['hide_button'] = True

        return HttpResponse(content=json.dumps(response),
                            content_type='application/json')

    # FIXME circuits filter should also include location of user
    circuits = Circuit.objects.available().filter(
        **params).order_by('-modified')[:cpp]

    return render(
        request,
        'circuits/categories.html',
        {
            'categories': categories,
            'category': category,
            'selected_category': category_value,
            'category_slug': category_slug,
            'is_preferred_category': category.is_followed(request.user),
            'circuits': circuits,
            'topbar_item': 'explore',
            'page_type': 'category',
            'gmacs': gmacs,
            'gmac_slug': gmac_slug,
            'STATIC_MAPS_ROOT': settings.STATIC_MAPS_ROOT,
            'GOOGLE_API_KEY': settings.GOOGLE_API_KEY,
            'gmac_get_short_formatted_name': gmac_get_short_formatted_name,
        },
    )