Example #1
0
def retrieveEvenCourses(request):
    """
	request : +degreeCode, +degreeType, +branchCode
	"""
    response_data = {}
    list = []
    try:
        C = Course.objects.retrieveEvenCourses(request.GET)
        print(C)
    except Exception as e:
        response_data['success'] = '0'
        response_data['exception'] = str(e)
    else:
        response_data['success'] = '1'
        # for obj in C:
        # dic = {'courseId' : obj.courseId, 'courseName' :obj.courseName}
        # list.append(dic)
        # response_data['courses'] = list
        global data
        try:
            data = serializers.serialize('json', C)
        except Exception as e:
            data = serializers.serialize('json', [C, ])
        response_data["courses"] = json.loads(data)

    return JsonResponse(response_data)
Example #2
0
 def default(self,obj):
     if isinstance(obj,QuerySet):
         """ Queryset实例
         直接使用Django内置的序列化工具进行序列化
         但是如果直接返回serialize('json',obj)
         则在simplejson序列化时会被从当成字符串处理
         则会多出前后的双引号
         因此这里先获得序列化后的对象
         然后再用simplejson反序列化一次
         得到一个标准的字典(dict)对象
         """
         return simplejson.loads(serialize('json',obj))
     if isinstance(obj,models.Model):
         """
         如果传入的是单个对象,区别于QuerySet的就是
         Django不支持序列化单个对象
         因此,首先用单个对象来构造一个只有一个对象的数组
         这是就可以看做是QuerySet对象
         然后此时再用Django来进行序列化
         就如同处理QuerySet一样
         但是由于序列化QuerySet会被'[]'所包围
         因此使用string[1:-1]来去除
         由于序列化QuerySet而带入的'[]'
         """
         jsonstr = simplejson.loads(serialize('json',[obj])[1:-1])
         res = jsonstr.get('fields')
         res["id"]=jsonstr.get("pk")
         return res
     if hasattr(obj, 'isoformat'):
         #处理日期类型
         return obj.isoformat()
     return simplejson.JSONEncoder.default(self,obj)
def applications_detail(request, pk, *args, **kwargs):
    """
    Show resource with GET, update it with PUT, destroy with DELETE
    """
    try:
        resource = MyApplication.objects.filter(user=request.resource_owner).filter(pk=pk).get()
        # hide default Application in the playground
        if resource.pk == 1:
            raise MyApplication.DoesNotExist
    except MyApplication.DoesNotExist:
        return HttpResponseNotFound()

    if request.method == 'GET':
        data = serializers.serialize("json", [resource])
        return HttpResponse(data, content_type='application/json', status=200, *args, **kwargs)
    elif request.method == 'PUT':
        try:
            data = json.loads(request.body)
            for k, v in data.iteritems():
                setattr(resource, k, v)
            resource.save()
            data = serializers.serialize("json", [resource])
            return HttpResponse(data, content_type='application/json')
        except (ValueError, TypeError):
            return HttpResponseBadRequest()
    elif request.method == 'DELETE':
        resource.delete()
        return HttpResponse(status=204)
Example #4
0
def create_game_info(game, forecaster):
    forecast = {}
    stats = {}
    forecast['kievdatetime'] = game.datetime + timedelta(hours=TIME_DIFFERENCE_HOURS)
    forecast['away_streak'], forecast['home_streak'] = get_team_streak(game)
    forecast['game'] = serializers.serialize('python', [game,])[0]
    forecast['away_team'] = serializers.serialize('python', [game.away_team,])[0]
    forecast['home_team'] = serializers.serialize('python', [game.home_team,])[0]
    forecast['num_comments'] = VVComment.objects.filter(object_id = getattr(game, 'pk'), content_type = ContentType.objects.get_for_model(game).id).count()
    #forecast['kievdatetime'] =
    try:
        forecast["forecast"] = Forecast.objects.get(game=game, forecaster=forecaster)
        if forecast["forecast"].winner == 'A':
            stats['span'] = '<img src="' + get_small_logo(game.away_team) + '" alt = "away" />'
        elif forecast["forecast"].winner == 'H':
            stats['span'] = '<img src="' + get_small_logo(game.home_team) + '" alt = "home" />'
        else:
            stats['span'] = _('NONE')
        forecast["forecast"] = serializers.serialize('python', [forecast['forecast'],])[0]
    except ObjectDoesNotExist:
        stats['span'] = _('NONE')
    stats['forecasts'] = Forecast.objects.filter(game=game).count()
    #stats['successes'] = Forecast.objects.filter(game = game, success = True).count()
    forecast['stats'] = stats.copy()
    return forecast
Example #5
0
def export(dest, silent, indent, exclude):
    "Exports core metadata for the Sentry installation."

    if exclude is None:
        exclude = ()
    else:
        exclude = exclude.lower().split(',')

    from django.db.models import get_apps
    from django.core import serializers

    def yield_objects():
        app_list = [(a, None) for a in get_apps()]

        # Collate the objects to be serialized.
        for model in sort_dependencies(app_list):
            if (
                not getattr(model, '__core__', True) or
                model.__name__.lower() in exclude or
                model._meta.proxy
            ):
                if not silent:
                    click.echo(">> Skipping model <%s>" % (model.__name__,), err=True)
                continue

            queryset = model._base_manager.order_by(model._meta.pk.name)
            for obj in queryset.iterator():
                yield obj

    if not silent:
        click.echo('>> Beginning export', err=True)
    serializers.serialize("json", yield_objects(), indent=indent, stream=dest,
                          use_natural_keys=True)
Example #6
0
    def serialize_db_to_string(self):
        """
        Serializes all data in the database into a JSON string.
        Designed only for test runner usage; will not handle large
        amounts of data.
        """
        # Build list of all apps to serialize
        from django.db.migrations.loader import MigrationLoader
        loader = MigrationLoader(self.connection)
        app_list = []
        for app_config in apps.get_app_configs():
            if (
                app_config.models_module is not None and
                app_config.label in loader.migrated_apps and
                app_config.name not in settings.TEST_NON_SERIALIZED_APPS
            ):
                app_list.append((app_config, None))

        # Make a function to iteratively return every object
        def get_objects():
            for model in serializers.sort_dependencies(app_list):
                if (not model._meta.proxy and model._meta.managed and
                        router.allow_migrate(self.connection.alias, model)):
                    queryset = model._default_manager.using(self.connection.alias).order_by(model._meta.pk.name)
                    for obj in queryset.iterator():
                        yield obj
        # Serialize to a string
        out = StringIO()
        serializers.serialize("json", get_objects(), indent=None, stream=out)
        return out.getvalue()
Example #7
0
def getProperties(request, spec_id):
    prop_members = m.PropertyMembership.objects.filter(spec=int(spec_id)).select_related(depth=1)
    return { 
        'prop_members' : serializers.serialize("json", prop_members),
        # TODO this is a workaround of lack support for deep serialization, should we use Piston ?
        'properties'   : serializers.serialize("json", [p.prop for p in prop_members])
    }
Example #8
0
    def export_as_json(model_admin, request, queryset):
        from django.core import serializers

        response = HttpResponse(mimetype="text/javascript")
        serializers.serialize("json", queryset, stream=response, indent=4)

        return response
Example #9
0
def query_suggest(request):
    """
    AutoComplete in search bar, including Topic, URL, User Profile; \
    Return JSON data for autocomplete; \
    URL suggestion is implemented with Solr(Haystack), \
    topic and user suggestion are implemented with SQL queries
    """
    keywords = request.GET['q'].strip().split()  #q is sent by jquery autocomplete
    Qs = []
    for k in keywords:
        Qs.append(Q(name__icontains=k))   #icontains means case-insensitive LIKE %str%
    for i, value in enumerate(Qs):   # | is overloaded @UnusedVariable
        if(i != 0):
            Qs[0] = Qs[0] | Qs[i]
    
    search_results_dic = {}
    
    items = Item.objects.filter(Qs[0])
    # JSON format: 
    # 'pk': 1, 'model':'main.item', 'fields':['name':'item_name', 'url':'item_url']
    search_results_dic['items'] = json.loads(serializers.serialize('json', items[:10], fields=('name'))) 
    
    users = Profile.objects.filter(Qs[0], is_active=True)
    search_results_dic['users'] = json.loads(serializers.serialize('json', users[:10], fields=('name', 'image_small')))
    
    topics = Topic.objects.filter(Q(name__istartswith=request.GET['q'].strip()), deleted=False, merged_to=None)
    search_results_dic['topics'] = json.loads(serializers.serialize('json', topics[:10], fields=('name')))

    return HttpResponse(json.dumps(search_results_dic, ensure_ascii=False))
Example #10
0
def booking(request,id): 
	if not request.user.is_authenticated():
		return HttpResponseRedirect(reverse('login'))
		pass

	#if request.is_ajax() and request.method == 'POST':
	#	filtro='The beatles'
	#	filtro2=request.POST['show']
	#	horarios=ShowHorario.objects.filter(show=filtro2)
	#	return render(request,'show_horario.html',{'show_horarios':horarios})
	#else:
	#	show_list=ShowHorario.objects.all()
	
	show_horario=Horario.objects.get(id=id)
	lugares=HorarioAsiento.objects.filter(horario__id=id)
	asientos=[]
	selected=[]
	for lugar in lugares:
		asientos.append(lugar.asiento)
	data=serializers.serialize('json', asientos)
	try:
		del request.session['cart']

	except KeyError:
		pass
	# if 'cart' in request.session:
	# 	for item in request.session['cart']:
	# 		selected.append(item)

	data2=serializers.serialize('json', selected)
	return render(request,'booking.html',{'show_horario':show_horario,'lugares':lugares,'data':data,'data2':data2})
Example #11
0
def confirm_deletion(request, token):
    key = cache.get(token, None)
    if key:
        cache.delete(token)
        try:
            user = User.objects.get(username=key)
            back_user = serializers.serialize('json', [user])
            ex_profile = ExtendedProfile.objects.filter(user=user)
            back_profile = serializers.serialize('json', ex_profile)
            backup_info = {'user': back_user, 'extended_profile': back_profile}
            deleted_user = DeletedUser()
            deleted_user.identifier = user.email
            deleted_user.user_information = backup_info
            deleted_user.save()
            user.delete()
            messages.success(request, _(u'Tu cuenta ha sido borrada.'))
            auth_logout(request)
        except Exception as e:
            logger.error("Error {e} en borrado de usuario".format(e=e))
            msg = _(u'Tu cuenta no ha sido borrada. Por favor intentar nuevamente')
            messages.error(request, msg)
        return redirect('accounts:profile')
    else:
        msg = _(u'Tu cuenta no ha sido borrada. Por favor intentar nuevamente')
        messages.error(request, msg)
        return redirect('accounts:profile')
Example #12
0
def get_nearest_px(request,id=6):

	# if lat/lon is given find nearest track,trackpoint and offset first
	if request.GET.__contains__('lat') and request.GET.__contains__('lon'):
		lat = request.GET.get('lat')
		lon = request.GET.get('lon')
	else:
		lat = 0
		lon = 0

	query = '''
		select distinct
			id,
			px,
			ST_distance(geom, ST_GeometryFromText('POINT(%s %s)',4326),true) as dist
		from
			riverview_trackpoint
		where track_id = %s
		order by dist		
		limit 1;''' % (lon,lat,id)
			
	tp = TrackPoint.objects.raw(query)
	trackpoint = TrackPoint.objects.get(id=tp[0].id)
	response = HttpResponse()
	serializers.serialize("json", [trackpoint], stream=response)

	cursor = connection.cursor()
	cursor.execute(query)
	track_segment = cursor.fetchall()
	response = HttpResponse(JSONEncoder().encode(track_segment),mimetype="application/json")
		
	return response
Example #13
0
def eps_xfer(request,client_slug=None,show_slug=None):
    """
    Returns all the episodes for a show as json.
    Used to synk public url's with the main conference site.
    """

    client=get_object_or_404(Client,slug=client_slug)
    show=get_object_or_404(Show,client=client,slug=show_slug)
    eps = Episode.objects.filter(show=show)

    fields=['id',
            'location', 'sequence',
            'name', 'slug', 'authors', 'description',
            'start', 'duration', 
            'released', 'license', 'tags',
            'conf_key', 'conf_url',
            'host_url', 'public_url',
        ]
    if request.user.is_authenticated():
        fields.extend(['emails', 'edit_key',])

    response = HttpResponse(mimetype="application/json")
    serializers.serialize("json", eps, fields=fields,  stream=response)

    return response
Example #14
0
File: views.py Project: gabik/OOS
def get_P_profile(request):
	json_data=status.objects.filter(status='ERR',MSG='PD')
	userprofileF = UserProfile.objects.filter(user=request.user)
	if not userprofileF:
		return HttpResponse(serializers.serialize("json", list(status.objects.filter(status='ERR',MSG='NE'))))
	userprofile = userprofileF[0]
	prof_dict = {}
	prof_dict['pk'] = int(request.user.id)
	prof_dict['model'] = "account.profile"
	userdata = {}
	userdata['first_name'] = str(request.user.first_name)
	userdata['last_name'] = str(request.user.last_name)
	userdata['email'] = str(request.user.email)
	userdata['phone_num1'] = str(userprofile.phone_num1)
	userdata['phone_num2'] = str(userprofile.phone_num2)
	userdata['address'] = str(userprofile.address)
	if userprofile.birthday : 
		userdata['birthday'] = str(userprofile.birthday)
	else : 
		userdata['birthday'] = ""
	userdata['area'] = str(userprofile.area_id.name)
	prof_dict['fields'] = userdata
	returnArray = []
	returnArray.append(prof_dict)
	#userdump = str(userdata)
	#json_data = status.objects.filter(status='OK')
	#json_dump = serializers.serialize("json", json_data) + str(list(prof_dict))
	#json_dump += ",[" + userdump + "]]"
	json_dump = serializers.serialize("json", list(status.objects.filter(status='OK'))) + str(list(returnArray))
	return HttpResponse(json_dump.replace('\'','"').replace('][',','))
Example #15
0
def get_meta(request,id):
	track = Track.objects.get(id=id)
	if track.geom != None:
		track.geom = track.geom.simplify(0.0001)
	response = HttpResponse()
	serializers.serialize("json", [track], stream=response)
	return response
Example #16
0
def host_virtual_get(request):
    json_str = request.body
    data = json.loads(json_str)
    token = data['token']
    try:
        result = Token.objects.get(key=token)
        user_id = result.user_id
        request.user = User.objects.get(id=user_id)
    except Token.DoesNotExist:
        result = {'result':'auth failed'}
        response = json.dumps(result)
        return HttpResponse(response)
    try:
        if 'params' in data:
            params = data['params']
            virtuals = HostVirtual.objects.select_related('Manage_IP').filter(**params).order_by('Manage_IP')
            total = virtuals.count()
            physicals = serializers.serialize("json",virtuals,use_natural_keys=True)
            response = '{"result":{"total":%s,"data":%s}}' % (total,physicals)
            return HttpResponse(response)
        else:
            virtuals = HostVirtual.objects.select_related('Manage_IP').all().order_by('Manage_IP')
            total = virtuals.count()
            virtuals = serializers.serialize("json",virtuals,use_natural_keys=True)
            response = '{"result":{"total":%s,"data":%s}}' % (total,virtuals)
            return HttpResponse(response)
            
    except Exception,e:
        result = {'result':{'status':0,'info':str(e)}}
Example #17
0
def application_get(request):
    json_str = request.body
    data = json.loads(json_str)
    token = data['token']
    try:
        result = Token.objects.get(key=token)
        user_id = result.user_id
        request.user = User.objects.get(id=user_id)
    except Token.DoesNotExist:
        result = {'result':'auth failed'}
        response = json.dumps(result)
        return HttpResponse(response)
    try:
        if 'params' in data:
            params = data['params']
            applications = Application.objects.filter(**params)
            total = applications.count()
            applications = serializers.serialize("json",applications)
            response = '{"result":{"total":%s,"data":%s}}' % (total,applications)
            return HttpResponse(response)
        else:
            applications = Application.objects.all()
            total = applications.count()
            applications = serializers.serialize("json",applications,use_natural_keys=True)
            response = '{"result":{"total":%s,"data":%s}}' % (total,applications)
            return HttpResponse(applications)

    except Exception,e:
        result = {'result':{'status':0,'info':str(e)}}
Example #18
0
def retrieveEvidenceTextTopics(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        user_id = data['user_id']

        texts = Text.objects.filter(created_by=user_id)
        serialized_json = serializers.serialize('json', texts)
        texts_json = flattenSerializedJson(serialized_json)

        evidenceCreated = Evidence.objects.filter(created_by=user_id)
        evidenceBookmarks = EvidenceBookmark.objects.filter(user_id=user_id)
        evidenceBookmarkedIds = [eb.evidence.pk for eb in evidenceBookmarks]
        evidenceBookmarked = Evidence.objects.filter(pk__in=evidenceBookmarkedIds)

        evidence = chain(evidenceCreated, evidenceBookmarked)

        serialized_json = serializers.serialize('json', evidence)
        evidence_json = flattenSerializedJson(serialized_json)

        # let's provide topic modeling results in addition to the raw evidence
        output = {}
        output['evidence'] = json.loads(evidence_json)

        contents = [t.content for t in texts]
        textPks = ['t-'+str(t.pk) for t in texts]
        abstracts = [e['abstract'] for e in output['evidence']]
        evidencePks = ['e-'+str(e['id']) for e in output['evidence']]

        if len(evidencePks + textPks) <= 1:
            output['topics'] = []
            output['evidenceTextTopicMap'] = []
        else:
            output['topics'], output['evidenceTextTopicMap'] = getTopicsForDocuments(evidencePks + textPks, abstracts + contents) 
        return HttpResponse(json.dumps(output), status=status.HTTP_201_CREATED)
Example #19
0
def getEvidenceByTopic(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        print data
        collection_id = data['collection_id']
        topic_id = data['topic_id']
        user_id = data['user_id']
        evidence = Evidence.objects.filter(Q(evidencetopic__created_by=collection_id)&Q(evidencetopic__primary_topic=topic_id)).order_by('-evidencetopic__primary_topic_prob').distinct()[:500]
        evidenceBookmarks = EvidenceBookmark.objects.filter(user_id=user_id)
        evidencePersonal = Evidence.objects.filter(Q(created_by=user_id))
        serialized_json = serializers.serialize('json', evidence)
        evidence_json = flattenSerializedJson(serialized_json)
        serialized_json = serializers.serialize('json', evidenceBookmarks)
        evidenceBookmark_json = flattenSerializedJson(serialized_json)
        serialized_json = serializers.serialize('json', evidencePersonal)
        evidencePersonal_json = flattenSerializedJson(serialized_json)   
        evidencePersonal = json.loads(evidencePersonal_json)
        output = {}
        output['evidencePersonal'] = []
        for e in evidencePersonal:
            if len(e['abstract']) > 50:
                name = Collection.objects.get(collection_id=collection_id).collection_name
                topic_dist, primary_topic_terms = TopicModeler.get_document_topics(e['abstract'], name)
                primary_topic_tuple = max(topic_dist, key=lambda x:x[1])
                this_topic = primary_topic_tuple[0]
                if this_topic == topic_id:
                    output['evidencePersonal'].append(e)
        output['evidence'] = json.loads(evidence_json)
        output['evidenceBookmarks'] = json.loads(evidenceBookmark_json)

        return HttpResponse(json.dumps(output), status=status.HTTP_200_OK)
Example #20
0
def json_serialized(queryset, fields=None):
    """Returns a JSON response containing data using the Django serializer."""
    if fields:
        serialized = serializers.serialize('json', queryset, fields=fields)
    else:
        serialized = serializers.serialize('json', queryset)
    return HttpResponse(serialized, content_type='application/json')
Example #21
0
def search_music_tracks(request):  #, *args, **kwargs):#query, search_term):
	query = request.GET.get('q')
	search_term = request.GET.get('search_term')
	#print query, search_term
	if not query or not search_term:
		if query not in ('title', 'genre', 'all'):	
			#print 'Bad parameters'
			context = {
				WARNING : 'Something bad happened',
			}
		#return HttpResponseRedirect(reverse('view_tracklist'))
	elif query == 'title':
		music_tracks = TrackModel.objects.filter(track_title__icontains=search_term)
		music_tracks = serializers.serialize("json", music_tracks)
		context = {
			'tracks' : music_tracks,
		}
	elif query == 'genre':
		music_tracks = TrackModel.objects.filter(track_genre__genre_name__icontains=search_term)
		music_tracks = serializers.serialize("json", music_tracks)
		context = {
			'tracks' : music_tracks,
		}
	else:
		music_tracks = TrackModel.objects.filter(
				Q(track_title__icontains=search_term) | Q(track_genre__genre_name__icontains=search_term))
		music_tracks = serializers.serialize("json", music_tracks)
		context = {
			'tracks' : music_tracks,
		}

	request.session[SESSION_KEY] = context
	return HttpResponseRedirect(reverse('view_tracklist'))
Example #22
0
def GetOrdersForBarWithStatus (request, bar_id=0, status=0):
	if request.method == 'GET':
		#orders = Order.objects.filter(bar=bar_id).filter(current_status=status)

		bartender = BarAdminUser.objects.get(pk=request.user.id)

		if bar_id == 0:
			bar_id = bartender.bar.pk

		drinkOrders = BarDrinkOrdered.objects.select_related("order").order_by("-order__updated").filter(
			order__bar=bar_id).filter(order__current_status=status).reverse()[:50]

		all_orders = []
		from itertools import groupby

		for k, g in groupby(drinkOrders, lambda x: x.order):
			user = json.loads(serializers.serialize('json', [k.appuser, ], relations={
				'user': {'fields': ( 'username', 'first_name', 'last_name', 'email', )},
				'facebook_user': {'fields': ( 'fb_uid', 'fb_email', )}, }))[0]
			order = json.loads(serializers.serialize('json', [k, ]))[0]
			drinkOrders = []
			for item in list(g):
				drinkOrders.append(json.loads(serializers.serialize('json', [item, ]))[0])
			tempOrderDict = {'appuser': user, 'order': order, 'drinks': drinkOrders}
			all_orders.append(tempOrderDict)

		response = json.dumps(all_orders)
		return HttpResponse(response, mimetype="application/json")
Example #23
0
def alta_orden(request):
	form = OrdenForm(request.user)
	conceptoform = ConceptoForm()
	tecnicos_locales = serializers.serialize("json", User.objects.filter(perfil = 'Tecnico local', is_active = True), fields=('username',))
	tecnicos_foraneos = serializers.serialize("json", User.objects.filter(perfil = 'Tecnico foraneo', is_active = True), fields=('username',))
	if request.method == "POST":
		form = OrdenForm(request.user, request.POST)
		if form.is_valid():
			o = form.save(commit = False)
			o.operador = request.user
			o.estatus = 'Nueva'
			o.save()
			conceptoform = ConceptoForm(request.POST)
			if conceptoform.is_valid():
				nombre = conceptoform.cleaned_data.get("nombre", "")
				cantidad = conceptoform.cleaned_data.get("cantidad", "")
				if nombre and cantidad:
					concepto = conceptoform.save(commit = False)
					concepto.orden = o
					concepto.usuario = request.user
					corte = Corte()
					concepto.corte = corte.asignar()
					concepto.save()
			return HttpResponseRedirect(reverse( 'editar_orden', args=[o.folio]))
		else:
			messages.warning(request, 'Algo salió mal, intenta de nuevo.')
	return render(request, 'ordenes/orden_form.html', locals())
Example #24
0
def ModelToJson(obj):
	"""
	模型转成json
	"""
	if isinstance(obj,QuerySet) or isinstance(obj,list):
		result = []
		for item in obj:
			itemjsonsource = json.loads(serialize('json',[item])[1:-1])
			itemjson = itemjsonsource["fields"]
			itemjson["id"] = itemjsonsource["pk"]
			if isinstance(item,BlogText):
				itemjson["gettags"] = item.gettags()
			if isinstance(item,UserDetail):
				itemjson["head_photo"] = item.getheadphotourl()
			result.append(itemjson)
		return result
	else:
		itemjsonsource = json.loads(serialize('json',[obj])[1:-1])
		itemjson = itemjsonsource["fields"]
		itemjson["id"] = itemjsonsource["pk"]
		if isinstance(obj,BlogText):
			itemjson["gettags"] = obj.gettags()
		if isinstance(obj,UserDetail):
			itemjson["head_photo"] = obj.getheadphotourl()
		return itemjson
		
def tacacs_plus_config_handler(op, old_instance, new_instance, modified_fields=None):

    if isinstance(old_instance, TacacsPlusConfig):
        if op == 'DELETE':
            # deleting the config singleton (presumably during shutdown?)
            return

    if isinstance(old_instance, TacacsPlusConfig):
        config_id = old_instance.id
    else:
        config_id = 'tacacs'
    try:
        config = TacacsPlusConfig.objects.get(pk=config_id)
    except TacacsPlusConfig.DoesNotExist:
        # cons up a dummy config object, not necessary to save it
        config = TacacsPlusConfig()

    # get current list of hosts (op==DELETE ignored here)
    ##hosts = TacacsPlusHost.objects.order_by('timestamp')
    def timestampSort(h1, h2):
        return cmp(h1.timestamp, h2.timestamp)
    hosts = sorted(TacacsPlusHost.objects.all(), timestampSort)

    # XXX roth -- config is passed as-is, not as a single-element list
    cj = serializers.serialize("json", [config])
    hj = serializers.serialize("json", hosts)
    print "Calling oswrapper with:", [cj, hj]
    exec_os_wrapper('TacacsPlusConfig', 'set', [cj, hj])
Example #26
0
def alerts_json(request, limit=None):
    limit = request.GET.get('limit')
    if limit:
        alerts = serializers.serialize('json', Alerts.objects.filter(user_id=request.user)[:limit])
    else:
        alerts = serializers.serialize('json', Alerts.objects.filter(user_id=request.user))
    return HttpResponse(alerts, content_type='application/json')
Example #27
0
 def jsonify_models(obj):
     if isinstance(obj, django.db.models.base.Model):
         return simplejson.loads(serialize('json', [obj]))[0]
     elif isinstance(object, QuerySet):
         return simplejson.loads(serialize('json', obj))
     else:
         return obj
Example #28
0
def GetNewOrdersForBarSince (request, bar_id=0, since_time=0, status=0):
	if request.method == 'GET':

		bartender = BarAdminUser.objects.get(pk=request.user.id)

		if bar_id == 0:
			bar_id = bartender.bar.pk

		#CHECK THE LAST FILTER DATETIME COMPARISON
		drinkOrders = BarDrinkOrdered.objects.select_related("order").filter(order__bar=bar_id).filter(
			order__created__gte=datetime.fromtimestamp(float(since_time))).filter(order__current_status=status)

		all_orders = []
		from itertools import groupby

		for k, g in groupby(drinkOrders, lambda x: x.order):
			user = json.loads(serializers.serialize('json', [k.appuser, ], relations={
				'user': {'fields': ( 'username', 'first_name', 'last_name', 'email', )},
				'facebook_user': {'fields': ( 'fb_uid', 'fb_email', )}, }))[0]
			order = json.loads(serializers.serialize('json', [k, ]))[0]
			drinkOrders = []
			for item in list(g):
				drinkOrders.append(json.loads(serializers.serialize('json', [item, ]))[0])
			tempOrderDict = {'appuser': user, 'order': order, 'drinks': drinkOrders}
			all_orders.append(tempOrderDict)

		response = json.dumps(all_orders)
		return HttpResponse(response, mimetype="application/json")
Example #29
0
 def default(self, obj):
     if isinstance(obj, QuerySet):
         return json.loads(serialize('json', obj))
     elif isinstance(obj, Model):
         return json.loads(serialize('json', [obj]))[0]
     else:
         return DjangoJSONEncoder.default(self, obj)
Example #30
0
def GetOrdersForBarWithStatusInTimeRange (request, bar_id=0, status=0, time_start=0, time_end=datetime.today()):
	if request.method == 'GET':

		bartender = BarAdminUser.objects.get(pk=request.user.id)

		if bar_id == 0:
			bar_id = bartender.bar.pk

		#orders = Order.objects.filter(bar=bar_id).filter(current_status=status).filter(update__range=[time_start, time_end])
		time_start = datetime.fromtimestamp(float(time_start))
		time_end = datetime.fromtimestamp(float(time_end))
		drinkOrders = BarDrinkOrdered.objects.select_related("order").filter(order__bar=bar_id).filter(
			order__current_status=status).filter(
			order__updated__range=[datetime.fromtimestamp(float(time_start)), datetime.fromtimestamp(float(time_end))])

		all_orders = []
		from itertools import groupby

		for k, g in groupby(drinkOrders, lambda x: x.order):
			order = json.loads(serializers.serialize('json', [k, ]))[0]
			drinkOrders = []
			for item in list(g):
				drinkOrders.append(json.loads(serializers.serialize('json', [item, ]))[0])
			tempOrderDict = {'order': order, 'drinks': drinkOrders}
			all_orders.append(tempOrderDict)

		response = json.dumps(all_orders)
		return HttpResponse(response, mimetype="application/json")
Example #31
0
    def handle(self, *app_labels, **options):
        format = options.get('format')
        indent = options.get('indent')
        using = options.get('database')
        excludes = options.get('exclude')
        show_traceback = options.get('traceback')
        use_natural_keys = options.get('use_natural_keys')
        if use_natural_keys:
            warnings.warn(
                "``--natural`` is deprecated; use ``--natural-foreign`` instead.",
                PendingDeprecationWarning)
        use_natural_foreign_keys = options.get(
            'use_natural_foreign_keys') or use_natural_keys
        use_natural_primary_keys = options.get('use_natural_primary_keys')
        use_base_manager = options.get('use_base_manager')
        pks = options.get('primary_keys')

        if pks:
            primary_keys = pks.split(',')
        else:
            primary_keys = []

        excluded_apps = set()
        excluded_models = set()
        for exclude in excludes:
            if '.' in exclude:
                try:
                    model = apps.get_model(exclude)
                except LookupError:
                    raise CommandError('Unknown model in excludes: %s' %
                                       exclude)
                excluded_models.add(model)
            else:
                try:
                    app_config = apps.get_app_config(exclude)
                except LookupError:
                    raise CommandError('Unknown app in excludes: %s' % exclude)
                excluded_apps.add(app_config)

        if len(app_labels) == 0:
            if primary_keys:
                raise CommandError(
                    "You can only use --pks option with one model")
            app_list = OrderedDict((app_config, None)
                                   for app_config in apps.get_app_configs()
                                   if app_config.models_module is not None
                                   and app_config not in excluded_apps)
        else:
            if len(app_labels) > 1 and primary_keys:
                raise CommandError(
                    "You can only use --pks option with one model")
            app_list = OrderedDict()
            for label in app_labels:
                try:
                    app_label, model_label = label.split('.')
                    try:
                        app_config = apps.get_app_config(app_label)
                    except LookupError:
                        raise CommandError("Unknown application: %s" %
                                           app_label)
                    if app_config.models_module is None or app_config in excluded_apps:
                        continue
                    try:
                        model = app_config.get_model(model_label)
                    except LookupError:
                        raise CommandError("Unknown model: %s.%s" %
                                           (app_label, model_label))

                    app_list_value = app_list.setdefault(app_config, [])

                    # We may have previously seen a "all-models" request for
                    # this app (no model qualifier was given). In this case
                    # there is no need adding specific models to the list.
                    if app_list_value is not None:
                        if model not in app_list_value:
                            app_list_value.append(model)
                except ValueError:
                    if primary_keys:
                        raise CommandError(
                            "You can only use --pks option with one model")
                    # This is just an app - no model qualifier
                    app_label = label
                    try:
                        app_config = apps.get_app_config(app_label)
                    except LookupError:
                        raise CommandError("Unknown application: %s" %
                                           app_label)
                    if app_config.models_module is None or app_config in excluded_apps:
                        continue
                    app_list[app_config] = None

        # Check that the serialization format exists; this is a shortcut to
        # avoid collating all the objects and _then_ failing.
        if format not in serializers.get_public_serializer_formats():
            try:
                serializers.get_serializer(format)
            except serializers.SerializerDoesNotExist:
                pass

            raise CommandError("Unknown serialization format: %s" % format)

        def get_objects():
            # Collate the objects to be serialized.
            for model in sort_dependencies(app_list.items()):
                if model in excluded_models:
                    continue
                if not model._meta.proxy and router.allow_migrate(
                        using, model):
                    if use_base_manager:
                        objects = model._base_manager
                    else:
                        objects = model._default_manager

                    queryset = objects.using(using).order_by(
                        model._meta.pk.name)
                    if primary_keys:
                        queryset = queryset.filter(pk__in=primary_keys)
                    for obj in queryset.iterator():
                        yield obj

        try:
            self.stdout.ending = None
            serializers.serialize(
                format,
                get_objects(),
                indent=indent,
                use_natural_foreign_keys=use_natural_foreign_keys,
                use_natural_primary_keys=use_natural_primary_keys,
                stream=self.stdout)
        except Exception as e:
            if show_traceback:
                raise
            raise CommandError("Unable to serialize database: %s" % e)
def technologies(request):
    technologies = models.Technology.objects.all()
    return HttpResponse(serializers.serialize("json", technologies))
def getDevTech(request):
    techs = models.DevelopmentTechnology.objects.all()
    return HttpResponse(serializers.serialize("json", techs))
def add_estrategia(request):
    data = json.loads(request.body)
    name = data['name'];
    description = data['description']
    thumbnail = data['thumbnail']
    # getlist('images[]')
    images = data['images']
    type = data['type']
    author = data['author']

    if thumbnail == '':
        thumbnail == None

    itemCode = data['id']

    print 'add_estrategia', itemCode

    if itemCode == '' or itemCode == 0:
        item = Item()
        item.type = int(smart_text(type, encoding='utf-8', strings_only=False, errors='strict'))
    else:
        item = Item.objects.get(item_code=itemCode, version=0, author=author)

    item.name = smart_text(name, encoding='utf-8', strings_only=False, errors='strict')
    item.description = smart_text(description, encoding='utf-8', strings_only=False, errors='strict')
    item.thumbnail = thumbnail
    item.status = '1'
    item.author_id = author

    ob = None

    if type == models.TECHNOLOGY:  # TODO: agregar cosas especificas de cada tipo de item
        ob = models.Technology(
            name=name,
            description = ':V'
        )
        ob.save()
        item.technology = ob
    elif type == models.TOOL:
        devPk = data['subclassId'];
        print "toolPk", devPk

        if devPk == '':
            ob = models.Tool()
        else:
            ob = models.Development.objects.get(pk=devPk)

        ob.name = name
        ob.description = ':v'
        ob.technology = models.Technology.objects.get(pk=data['technology'])
        ob.url = data['toolUrl']
        ob.download_url = data['toolDownloadUrl']
        ob.license_type = data['licenseType']
        ob.use_restrictions = data['useRestrictions']
        ob.integration = data['integration']
        ob.functional_description = data['functionalDescription']
        ob.operating_systems = smart_text(",".join(data['operativeSystems']), encoding='utf-8', strings_only=False,
                                          errors='strict')

        ob.save()
        item.tool = ob

    elif type == models.TUTORIAL:
        devPk = data['subclassId'];
        print "tutorialPk", devPk

        if devPk == '':
            ob = models.Tutorial()
        else:
            ob = models.Tutorial.objects.get(pk=devPk)

        ob.name = name
        ob.url = data['tutorialUrl']
        ob.tool_id = data['tool']

        ob.save()
        item.tutorial = ob
    elif type == models.EXAMPLE:

        devPk = data['subclassId'];
        print "examplePk", devPk

        if devPk == '':
            ob = models.Example()
        else:
            ob = models.Example.objects.get(pk=devPk)

        ob.name = name
        ob.url = data['exampleUrl']
        ob.strategy_id = data['strategy']
        ob.tool_id = data['tool']

        ob.save()
        item.example = ob

    elif type == models.STRATEGY:

        devPk = data['subclassId'];
        print "strategyPk", devPk

        if devPk == '':
            ob = models.Strategy()
        else:
            ob = models.Strategy.objects.get(pk=devPk)

        ob.name = name
        ob.save()
        item.strategy = ob

    elif type == models.DEVELOPMENT:
        devPk = data['subclassId'];
        print "devPk", devPk
        if devPk == '':
            ob = models.Development(
                name=name
            )
            ob.save()
        else:
            ob = models.Development.objects.get(pk=devPk)
            ob.dev_technologies.clear()
            ob.save()

        for tech in data['devTechs']:  # the list of devTechs PK's
            print "tech", tech
            ob.dev_technologies.add(tech)

        ob.save()
        item.development = ob

    elif type == models.DISCIPLINE:
        devPk = data['subclassId']
        print "disciplinePk", devPk

        if devPk == '':
            ob = models.Discipline(
                name=name
            )
            ob.save()
        else:
            ob = models.Discipline.objects.get(pk=devPk)
            ob.tools.clear()
            ob.save()

        for _tool in data['tools']:  # the list of devTechs PK's
            print "tool", _tool
            ob.tools.add(_tool)

        ob.save()
        item.discipline = ob

    for tech in data['devTechs']:  # the list of devTechs PK's
        print "tech", tech
        ob.dev_technologies.add(tech)

    item.save()

    if item.item_code == -1:
        print "Version ", data['version']
        if data['version'] == "2":
            print "Created draft of an aproved item"
            item.item_code = data['item_code']
        else:
            item.item_code = item.pk
        item.save()

    item.images.clear()
    for image in images:
        newImg = models.Image.objects.create(image=image)
        item.images.add(newImg)

    item.save()

    print name, description, thumbnail, images
    _ob = serializers.serialize("json", [ob])
    _item = serializers.serialize("json", [item])

    sendToReview = data['sendToReview'];

    if (sendToReview):
        createReviewVersion(item)

    return JsonResponse({'mensaje': 'ok', 'item': _item, 'strategy': _ob})
def search_item(request):
    name = request.GET['name'];
    type = request.GET['type']
    # type='1'

    authenticated = request.user.is_authenticated()

    if name is not None:
        name = name.strip()

    print('type', name, type)

    query = Item.objects.all()
    if not authenticated: query = query.filter(version='2')

    if name is not None and name != "":

        tech = query.filter(Q(type='1')).filter(name__icontains=name)

        # el nombre contiene name o el nombre de su tecnologia contiene name
        tools = query.filter(type='2').filter(
            Q(name__icontains=name) | Q(tool__technology__id__in=tech.values('technology')))

        # el nombre contiene name , el nombre de su herramienta contiene name, el nombre de su tecnologia contiene name
        tutoriales = query.filter(type='3').filter(
            Q(name__icontains=name) | Q(tutorial__tool__id__in=tools.values('tool')))

        # el nombre contiene name , el nombre de su herramienta contiene name, el nombre de su tecnologia contiene name
        examples = query.filter(type='4').filter(
            Q(name__icontains=name) | Q(example__tool__id__in=tools.values('tool')))

        strategies = query.filter(type='5').filter(Q(name__icontains=name))

        developments = query.filter(type='6').filter(Q(name__icontains=name))


        disciplines = query.filter(type='7').filter(Q(name__icontains=name))



        if type == '1':
            query = tech
        elif type == '2':
            query = tools
        elif type == '3':
            query = tutoriales
        elif type == '4':
            query = examples
        elif type == '5':
            query = strategies
        elif type == '6':
            query = developments
        elif type == '7':
            query = disciplines
        else:
            query = tech.union(tools).union(tutoriales).union(examples).union(strategies).union(developments).union(disciplines)

    else:
        # No escribio un criterio de busqueda pero selecciono un tipo de item
        if type != '-1':
            query = query.filter(type=type)

    return HttpResponse(serializers.serialize("json", query))
Example #36
0
def get_users(request):
    users = User.objects.all()
    json_data = serialize("json", users)
    final_data = json.loads(json_data)
    return JsonResponse(final_data, safe=False)
Example #37
0
def get_data(request):
    vocabulary = Word.objects.all()
    json_data = serialize("json", vocabulary)
    final_data = json.loads(json_data)
    return JsonResponse(final_data, safe=False)
Example #38
0
def getcomments(request):
    #I am not sure of how to pass parameters... hmmmm
    comments=Comments.objects.all()
    comments=serializers.serialize("json",comments)
    return HttpResponse(comments)
Example #39
0
 def get(self, request):
     categoriesJSON = serializers.serialize("json", Category.objects.all())
     responce = HttpResponse(categoriesJSON, content_type="application/json")
     return responce
Example #40
0
    def process_parsed_findings(self,
                                test,
                                parsed_findings,
                                scan_type,
                                user,
                                active,
                                verified,
                                minimum_severity=None,
                                endpoints_to_add=None,
                                push_to_jira=None,
                                group_by=None,
                                now=timezone.now(),
                                service=None,
                                scan_date=None,
                                **kwargs):
        logger.debug('endpoints_to_add: %s', endpoints_to_add)
        new_findings = []
        items = parsed_findings
        logger.debug('starting import of %i items.',
                     len(items) if items else 0)
        i = 0
        for item in items:
            # FIXME hack to remove when all parsers have unit tests for this attribute
            if item.severity.lower().startswith(
                    'info') and item.severity != 'Info':
                item.severity = 'Info'

            item.numerical_severity = Finding.get_numerical_severity(
                item.severity)

            if minimum_severity and (Finding.SEVERITIES[item.severity] >
                                     Finding.SEVERITIES[minimum_severity]):
                # finding's severity is below the configured threshold : ignoring the finding
                continue

            item.test = test
            item.reporter = user if user else get_current_user
            item.last_reviewed = now
            item.last_reviewed_by = user if user else get_current_user

            logger.debug(
                'process_parsed_findings: active from report: %s, verified from report: %s',
                item.active, item.verified)
            # active, verified parameters = parameters from the gui or api call.
            # item.active, item.verified = values from the report / the parser
            # if either value of active (from the parser or from the api/gui) is false, final status is inactive
            #   else final status is active
            # if either value of verified (from the parser or from the api/gui) is false, final status is not verified
            #   else final status is verified
            # Note that:
            #   - the API (active/verified parameters) values default to True if not specified
            #   - the parser values default to true if not set by the parser (as per the default value in models.py)
            #   - there is no "not specified" in the GUI (not ticked means not active/not verified)
            if item.active:
                item.active = active
            if item.verified:
                item.verified = verified

            # if scan_date was provided, override value from parser
            if scan_date:
                item.date = scan_date.date()

            item.service = service

            item.save(dedupe_option=False)

            if settings.FEATURE_FINDING_GROUPS and group_by:
                finding_helper.add_finding_to_auto_group(item, group_by)

            if (hasattr(item, 'unsaved_req_resp')
                    and len(item.unsaved_req_resp) > 0):
                for req_resp in item.unsaved_req_resp:
                    burp_rr = BurpRawRequestResponse(
                        finding=item,
                        burpRequestBase64=base64.b64encode(
                            req_resp["req"].encode("utf-8")),
                        burpResponseBase64=base64.b64encode(
                            req_resp["resp"].encode("utf-8")))
                    burp_rr.clean()
                    burp_rr.save()

            if (item.unsaved_request is not None
                    and item.unsaved_response is not None):
                burp_rr = BurpRawRequestResponse(
                    finding=item,
                    burpRequestBase64=base64.b64encode(
                        item.unsaved_request.encode()),
                    burpResponseBase64=base64.b64encode(
                        item.unsaved_response.encode()))
                burp_rr.clean()
                burp_rr.save()

            if settings.ASYNC_FINDING_IMPORT:
                importer_utils.chunk_endpoints_and_disperse(
                    item, test, item.unsaved_endpoints)
            else:
                importer_utils.add_endpoints_to_unsaved_finding(
                    item, test, item.unsaved_endpoints, sync=True)

            if endpoints_to_add:
                if settings.ASYNC_FINDING_IMPORT:
                    importer_utils.chunk_endpoints_and_disperse(
                        item, test, endpoints_to_add)
                else:
                    importer_utils.add_endpoints_to_unsaved_finding(
                        item, test, endpoints_to_add, sync=True)

            if item.unsaved_tags:
                item.tags = item.unsaved_tags

            if item.unsaved_files:
                for unsaved_file in item.unsaved_files:
                    data = base64.b64decode(unsaved_file.get('data'))
                    title = unsaved_file.get('title', '<No title>')
                    file_upload, file_upload_created = FileUpload.objects.get_or_create(
                        title=title, )
                    file_upload.file.save(title, ContentFile(data))
                    file_upload.save()
                    item.files.add(file_upload)

            new_findings.append(item)
            # to avoid pushing a finding group multiple times, we push those outside of the loop
            if settings.FEATURE_FINDING_GROUPS and item.finding_group:
                item.save()
            else:
                item.save(push_to_jira=push_to_jira)

        if settings.FEATURE_FINDING_GROUPS and push_to_jira:
            for finding_group in set([
                    finding.finding_group for finding in new_findings
                    if finding.finding_group is not None
            ]):
                jira_helper.push_to_jira(finding_group)
        sync = kwargs.get('sync', False)
        if not sync:
            return [
                serializers.serialize('json', [
                    finding,
                ]) for finding in new_findings
            ]
        return new_findings
Example #41
0
 def test_serialize(self):
     """Tests that basic serialization works."""
     serial_str = serializers.serialize(self.serializer_name,
                                        Article.objects.all())
     self.assertTrue(self._validate_output(serial_str))
    def handle(self, *args, **options):
        error_text = ('%s\nTry calling dump_object with --help argument or ' +
                      'use the following arguments:\n %s' % self.args)
        try:
            #verify input is valid
            try:
                (app_label, model_name) = options['model'].split('.')
            except AttributeError:
                raise CommandError("Specify model as `appname.modelname")
            query = options['query']
            ids = options['ids']
            config_name = options['config_name']

            if ids and query:
                raise CommandError(error_text %
                                   'either use query or id list, not both')
            if not (ids or query):
                raise CommandError(error_text %
                                   'must pass list of --ids or a json --query')
        except IndexError:
            raise CommandError(error_text %
                               'No object_class or filter clause supplied.')
        except ValueError:
            raise CommandError(error_text %
                               ("object_class must be provided in"
                                " the following format: app_name.model_name"))
        except AssertionError:
            raise CommandError(error_text % 'No filter argument supplied.')

        dump_me = loading.get_model(app_label, model_name)
        if query:
            objs = dump_me.objects.filter(**json.loads(query))
        else:
            if ids[0] == '*':
                objs = dump_me.objects.all()
            else:
                try:
                    parsers = int, long, str
                except NameError:
                    parsers = int, str
                for parser in parsers:
                    try:
                        objs = dump_me.objects.filter(pk__in=map(parser, ids))
                    except ValueError:
                        pass
                    else:
                        break

        if options.get('kitchensink'):
            if django.VERSION >= (1, 8):
                fields = (
                    f for f in dump_me._meta.get_fields()
                    if (f.one_to_many or f.one_to_one) and f.auto_created)
            else:
                fields = dump_me._meta.get_all_related_objects()

            related_fields = [rel.get_accessor_name() for rel in fields]

            for obj in objs:
                for rel in related_fields:
                    try:
                        if hasattr(getattr(obj, rel), 'all'):
                            add_to_serialize_list(getattr(obj, rel).all())
                        else:
                            add_to_serialize_list([getattr(obj, rel)])
                    except FieldError:
                        pass
                    except ObjectDoesNotExist:
                        pass

        try:
            dump_settings = settings.CUSTOM_DUMPS[config_name]
        except Exception:
            dump_settings = None

        add_to_serialize_list(objs)
        serialize_fully()
        data = serialize(
            options.get('format',
                        'json'), [o for o in serialize_me if o is not None],
            indent=4,
            use_natural_foreign_keys=options.get('natural', False),
            use_natural_primary_keys=options.get('natural', False))

        if dump_settings and dump_settings.get('order', []):
            data = reorder_json(json.loads(data),
                                dump_settings.get('order', []),
                                ordering_cond=dump_settings.get(
                                    'order_cond', {}))
        self.stdout.write(json.dumps(data))
        # Clear the list. Useful for when calling multiple dump_object commands with a single execution of django
        del serialize_me[:]
        seen.clear()
Example #43
0
    def handle(self, *args, **options):
        verbosity = options.get('verbosity')

        if verbosity:
            print('Pulling read info items.')
        pull_recent_read_info_items()
        if verbosity:
            print('Done pulling read info items.')

        authors = Author.objects.all()
        author_data = serializers.serialize("json", authors, indent=2)
        open(os.path.join(settings.INFO_SYNC['DUMP_TO'], 'author.json'),
             'w').write(author_data)

        a_week_ago = timezone.now() - timedelta(days=7)
        start = a_week_ago
        if SyncLog.objects.filter(action='local_to_server').exists():
            last_sync_time = SyncLog.objects.filter(
                action='local_to_server')[0].timestamp
            start = last_sync_time - timedelta(days=1)
        recent_items = Info.objects.filter(
            Q(timestamp__gt=start) | Q(read_at__gte=start))
        recent_contents = Content.objects.filter(info__in=recent_items)

        if verbosity:
            print(('exporting %d items' % (recent_items.count())))
        fields = [f.name for f in Info._meta.fields]
        data = serializers.serialize("json",
                                     recent_items,
                                     indent=2,
                                     fields=fields)
        content_fields = [f.name for f in Content._meta.fields]
        content_data = serializers.serialize("json",
                                             recent_contents,
                                             indent=2,
                                             fields=content_fields)
        open(os.path.join(settings.INFO_SYNC['DUMP_TO'], 'content.json'),
             'w').write(content_data)
        open(os.path.join(settings.INFO_SYNC['DUMP_TO'], 'info.json'),
             'w').write(data)

        reads_items = Read.objects.all()
        if verbosity:
            print(('exporting %d items' % (reads_items.count())))
        fields = [f.name for f in Read._meta.fields]
        data = serializers.serialize("json",
                                     reads_items,
                                     indent=2,
                                     fields=fields)
        open(os.path.join(settings.INFO_SYNC['DUMP_TO'], 'reads.json'),
             'w').write(data)

        cmd = 'rsync -rave ssh {} {}:{}'.format(
            settings.INFO_SYNC['DUMP_TO'], settings.INFO_SYNC['SERVER'],
            settings.INFO_SYNC['LOAD_FROM'])
        if verbosity:
            print(cmd)
        ret = os.system(cmd)

        cmd = 'ssh {} "{}"'.format(settings.INFO_SYNC['SERVER'],
                                   settings.INFO_SYNC['LOAD_CMD'])
        if verbosity:
            print(cmd)
        ret = os.system(cmd)
        logger.info('sync_info completed successfully')

        SyncLog.objects.create(action='local_to_server')
Example #44
0
 def get(self, request):
     productsJSON = serializers.serialize("json", Product.objects.filter(category=request.GET['pk']))
     responce = HttpResponse(productsJSON, content_type="application/json")
     return responce
def frontend_job_details(request):
    nowuser = request.user
    job_id = request.GET.get("job")
    try:
        job = Job.objects.get(id=job_id)  ##查询作业
        uav = UAV.objects.filter(user_id=nowuser.id).filter(
            is_active=True)  ##查询用户的无人机
        count = len(uav)
        district = Nation.objects.get(code=job.nation)
        city = Nation.objects.get(id=district.parent)
        province = Nation.objects.get(id=city.parent)

        if request.method == 'POST':  ###有数据提交时执行
            uav_id = request.POST.get("uav")
            uav_selected = UAV.objects.get(id=uav_id)
            jobdetail_uav = UAV_Job_Detail.objects.filter(uav_id=uav_id)
            jobdetail_job = UAV_Job_Detail.objects.filter(
                job_id=job.id).filter(uav_id=uav_id)
            if jobdetail_job:
                messages.warning(request, '申请失败 与该无人机已申请过该作业')
                logger_apply.warning(
                    '\n' + __name__ + ',' + nowuser.username +
                    ',Apply a UAVJOB Failed. The UAV Already Applied the Job.{ID:'
                    + str(nowuser.id) + ',uav_id:' + str(uav_id) + ',job_id:' +
                    str(job_id) + '}')
            else:
                flag = True
                flag_count = 0
                for u in jobdetail_uav:
                    if job.start_time > u.job.end_time or job.end_time < u.job.start_time:
                        flag_count = flag_count + 1
                    #如果当前作业开始时间 晚于 作业u的结束时间 或者 当前作业结束时间 早于 作业u的开始时间
                    else:
                        flag = False
                if flag == True:
                    job_detail = UAV_Job_Detail()
                    job_detail.uav = uav_selected
                    job_detail.job = job
                    job_detail.confirm = 0
                    job_detail.save()
                    messages.success(request, '申请成功')
                    all_job_apply.delay(nowuser, job)  # 日志
                    logger_apply.info('\n' + __name__ + ',' +
                                      nowuser.username +
                                      ',Apply a UAVJOB Successed.{ID:' +
                                      str(nowuser.id) + ',uav_id:' +
                                      str(job_detail.uav.id) + ',job_id:' +
                                      str(job_detail.job.id) +
                                      ',uav_job_detail_id:' +
                                      str(job_detail.id) + '}')
                else:
                    logger_apply.warning(
                        '\n' + __name__ + ',' + nowuser.username +
                        ',Apply a UAVJOB Failed. Time Conflict.{ID:' +
                        str(nowuser.id) + ',uav_id:' + str(uav_id) +
                        ',job_id:' + str(job_id) + '}')
                    messages.warning(request, '申请失败 与该无人机的其他作业时间冲突')
        else:  ###没有数据提交时执行
            All_Job_View_Details.delay(nowuser, job)  #即查看该作业
    except:
        logger_view_details.error('\n' + __name__ + ',' + nowuser.username +
                                  ',View a Job Details Failed. {ID:' +
                                  str(nowuser.id) + ',job_id:' + str(job_id) +
                                  '}' + '\n%s' % traceback.format_exc())
        messages.warning(request, '数据错误,请联系管理员')
        return HttpResponseRedirect("/alljob/")  #不是则返回

    job_border = Job_Border.objects.filter(job_id=job_id)
    return render_to_response(
        'frontend_job_details.html', {
            'self': nowuser,
            'job': job,
            "province": province,
            "city": city,
            "district": district,
            "uav": uav,
            "count": count,
            "job_border": job_border,
            "job_border_json": serializers.serialize("json", job_border),
        },
        context_instance=RequestContext(request))
 def export_as_json(modeladmin, request, queryset):
     response = HttpResponse(content_type="application/json")
     serializers.serialize("json", queryset, stream=response)
     return response
Example #47
0
 def __init__(self, object, is_iterable=True):
     if is_iterable:
         content = serialize('xml', object)
     else:
         content = object
     super(XMLResponse, self).__init__(content, mimetype='application/xml')
Example #48
0
def get_geojson(data, fields):
    return serialize('geojson', data, geometry_field='mpoly', fields=fields)
Example #49
0
 def invoices(self,request,pk=None):
     invoice_json = json.loads(serial.serialize('json',InvoiceModel.objects.filter(customer_id = pk)))
     print("invoice_json : ",invoice_json)
     return Response(invoice_json,status =200)
Example #50
0
    def post(self, request, code):

        user, profile = user_and_profile(request)

        if code not in ('for', 'new'):
            if not profile.is_crige_admin:
                raise Http404
            fake = None
            jurisdiction = get_object_or_404(Jurisdiction, code=code)
        else:
            if code == 'new' and not profile.is_crige_admin:
                raise Http404
            fake = (code == 'for')
            jurisdiction = None
            code = None

        organisation_pk = request.GET.get('organisation')
        if organisation_pk:
            organisation = get_object_or_404(Organisation, pk=organisation_pk)
        else:
            organisation = None

        form = Form(request.POST, instance=jurisdiction, include={'user': user})

        basemaps = BaseMaps.objects.all()
        communes = serialize(
            'geojson', Commune.objects.all().transform(srid=4326),
            geometry_field='geom')

        context = {
            'basemaps': basemaps,
            'communes': communes,
            'fake': fake,
            'form': form,
            'instance': jurisdiction,
            'organisation': organisation}

        if not form.is_valid():
            return render_with_info_profile(request, self.template, context=context)

        try:
            with transaction.atomic():
                if not code:
                    jurisdiction = Jurisdiction.objects.create(**dict(
                        (item, form.cleaned_data[item])
                        for item in form.Meta.property_fields))
                else:
                    for item in form.Meta.property_fields:
                        setattr(jurisdiction, item, form.cleaned_data[item])
                    jurisdiction.save(old=code)

                JurisdictionCommune.objects \
                    .filter(jurisdiction=jurisdiction) \
                    .exclude(commune__in=form.cleaned_data['communes']) \
                    .delete()

                for commune in form.cleaned_data['communes']:
                    kvp = {'jurisdiction': jurisdiction, 'commune': commune}
                    try:
                        JurisdictionCommune.objects.get(**kvp)
                    except JurisdictionCommune.DoesNotExist:
                        kvp['created_by'] = profile
                        JurisdictionCommune.objects.create(**kvp)
                jurisdiction.set_geom()

                # Ugly time:
                if fake:
                    url = '{}?organisation={}'.format(
                        request.build_absolute_uri(reverse(
                            'idgo_admin:jurisdiction_editor', kwargs={'code': 'new'})),
                        organisation.pk)

                    # E-mail envoyé aux administrateurs
                    send_mail_asking_for_jurisdiction_creation(user, jurisdiction, organisation, url)
                    # E-mail envoyé  à l'utilisateur
                    send_jurisdiction_creation_mail(user, jurisdiction, organisation)

                    raise FakeError('Force atomic to roll back.')

        except ValidationError as e:
            messages.error(request, ' '.join(e))
        except FakeError as e:
            messages.success(request, (
                'Votre demande de création de territoire '
                'de compétence a été envoyée aux administrateurs.'))
        else:
            messages.success(request, (
                'Le territoire de compétence a été '
                '{} avec succès.').format(code and 'mis à jour' or 'créé'))

        if 'save' in request.POST:
            to = '{}#{}'.format(
                reverse('idgo_admin:jurisdictions'), jurisdiction.code)
        else:
            to = reverse(
                'idgo_admin:jurisdiction_editor',
                kwargs={'code': jurisdiction.code})

        if fake:
            # S'il s'agit d'une simple demande on revient
            # toujours sur la liste des organisations
            to = reverse('idgo_admin:all_organisations')

        return HttpResponseRedirect(to)
Example #51
0
 def test_dumping(self):
     for value, serialized in self.test_values:
         with self.subTest(value=value):
             instance = JSONModel(value=value)
             data = serializers.serialize('json', [instance])
             self.assertJSONEqual(data, self.test_data % serialized)
Example #52
0
 def getProductGroupOfEachItem(self,request,pk=None): 
     group_id=request.data['group_id']
     groupName_json = json.loads(serial.serialize('json',ProductGroupModel.objects.filter(group_id = group_id)))[0]['fields']['group_name']
     return Response(groupName_json,status =200)
Example #53
0
def administrasi_datasets(request):
	administrasi = serialize('geojson', Administrasi.objects.all())
	return HttpResponse(administrasi, content_type='json')
Example #54
0
 def products(self,request,pk=None):
     items_json = json.loads(serial.serialize('json',ProductModel.objects.filter(group_id = pk)))
     print("itemsOfGroup ",pk," : ",items_json)
     return Response(items_json,status =200)
Example #55
0
def fetchFuelPrice(request):
    req = request.POST
    city = req['city']
    fuel_type = req['fuel_type']
    state = req['state']

    print("fueltype = ",fuel_type)
    if fuel_type == 'Petrol':
        type = 1
    elif fuel_type == 'Diesel':
        type = 2
    elif fuel_type == "CNG":
        type = 3

    query_set = FuelPrices.objects.filter(city=city, fuel_type=type)

    json_data = serializers.serialize('json',query_set)
    data = json.loads(json_data)

    if data != []:

        print('data = ',data)
        data = data[0]
        mydata = dict()
        mydata['response'] = 'cityFound'
        mydata['id'] = data['pk']
        fields = data['fields']
        mydata['city'] = fields['city']
        mydata['price'] = fields['price']
        fuel_type = fields['fuel_type']
        if fuel_type == 1:
            mydata['fuel_type'] = 'Petrol'
        elif fuel_type == 2:
            mydata['fuel_type'] = 'Diesel'
        else:
            mydata['fuel_type'] = 'CNG'

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

    else: #if city name does not exists -> we'll get empty query set

        query_set = FuelPrices.objects.filter(state= state, fuel_type=type)
        json_data = serializers.serialize('json', query_set)
        data = json.loads(json_data)

        if data != []:

            print('data = ', data)
            mylist = []

            for d in data:
                mydata = dict()
                mydata['id'] = d['pk']
                fields = d['fields']
                mydata['city'] = fields['city']
                mydata['state'] = fields['state']
                mydata['price'] = fields['price']
                if fuel_type == 1:
                    mydata['fuel_type'] = 'Petrol'
                elif fuel_type == 2:
                    mydata['fuel_type'] = 'Diesel'
                else:
                    mydata['fuel_type'] = 'CNG'

                mylist.append(mydata)

            mydata = dict()
            mydata['response'] = 'cityNotFound'
            mydata['cityList'] = mylist

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

        else: #if state name not found -> in case of CNG
            mydata = dict()
            mydata['response'] = 'StateNotFound'

            return HttpResponse(json.dumps(mydata), content_type ='application/json')
Example #56
0
def street_datasets(request):
	street = serialize('geojson', Street.objects.all())
	return HttpResponse(street, content_type='json')
Example #57
0
def leads(request):
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        first_name = data["first_name"]
        last_name = data["last_name"]
        mobile = data["mobile"]
        email = data["email"]
        location_type = data["location_type"]
        location_string = data["location_string"]
        user = Users(first_name=first_name,
                     last_name=last_name,
                     mobile=mobile,
                     email=email,
                     location_type=location_type,
                     location_string=location_string)
        user.save()
        check(mobile)
        return JsonResponse(
            {
                'first_name': first_name,
                'last_name': last_name,
                'mobile': mobile,
                'email': email,
                'location_type': location_type,
                'location_string': location_string,
                'status': 'Created'
            },
            status=201)

    elif HttpResponse.status_code == 400:
        return JsonResponse({"status": "failure", "reason": "Bad Request"})

    if request.method == 'GET':
        id = request.GET.get('id')
        result = Users.objects.get(pk=id)
        data = serializers.serialize('json', [
            result,
        ])
        final_result = json.loads(data)
        final_result = final_result[0]['fields']
        final_result['status'] = 'Created'
        # print(final_result)
        return JsonResponse(final_result)

    elif HttpResponse.status_code == 400:
        return JsonResponse({"status": "failure", "reason": "Bad Request"})

    elif HttpResponse.status_code == 404:
        return JsonResponse({})

    if request.method == 'PUT':
        id = request.GET.get('id')
        data = json.loads(request.body.decode('utf-8'))
        first_name = data["first_name"]
        last_name = data["last_name"]
        mobile = data["mobile"]
        email = data["email"]
        location_type = data["location_type"]
        location_string = data["location_string"]
        Users.objects.filter(pk=id).update(first_name=first_name,
                                           last_name=last_name,
                                           mobile=mobile,
                                           email=email,
                                           location_type=location_type,
                                           location_string=location_string)
        return JsonResponse({'status': 'success'}, status=202)

    elif HttpResponse.status_code == 400:
        return JsonResponse({"status": "failure", "reason": "Bad Request"})

    if request.method == 'DELETE':
        id = request.GET.get('id')
        Users.objects.filter(id=id).delete()
        return JsonResponse({'status': 'success'}, status=200)

    elif HttpResponse.status_code == 400:
        return JsonResponse({"status": "failure", "reason": "Bad Request"})
Example #58
0
def edubuild_datasets(request):
	edubuild = serialize('geojson', EduBuild.objects.all())
	return HttpResponse(edubuild, content_type='json')
Example #59
0
def _encode_address(address):
    return json.loads(serializers.serialize("json",
                                            [address]))[0].get("fields")
Example #60
0
def getdata(request):
    results = Producto.objects.all()
    jsondata = serializers.serialize('json', results)
    return HttpResponse(jsondata)