def to_json_fields(self):
        json = {}
        for attribute in self.get_attributes():
            value = self.__getattribute__(attribute.name)
            json.update({attribute.name: value})

        return json
예제 #2
0
파일: api.py 프로젝트: Schibum/sndlatr
 def _encode_send_job(self, job):
     json = self._encode_base_job(job)
     json.update({
         'subject': job.subject,
         'messageId': job.message_id
     })
     return json
예제 #3
0
def get_homework(user_name):
    homeworks = Homeworks.query.filter_by(user_name=user_name).all()

    json = {"user_name": str(user_name)}

    count = 0
    for homework in homeworks:
        class_info = Classes.query.filter_by(
            class_id=homework.class_id).first()
        hw_json = {
            "homework_" + str(count): [{
                "homeworks_id":
                str(homework.homeworks_id),
                "Title":
                str(homework.homework_title),
                "Class":
                str(class_info.class_name),
                "Due":
                homework.homework_due_date.strftime("%d/%m/%y"),
            }]
        }
        json.update(hw_json)
        count += count

    return json, 200
예제 #4
0
    def salt_api_cmd(self, **kwargs):

        try:
            timeout = kwargs["timeout"]
        except KeyError:
            timeout = 15

        salt_timeout = timeout + 2

        json = {
            "client": "local",
            "tgt": self.client.salt_id,
            "fun": kwargs["func"],
            "timeout": salt_timeout,
            "username": settings.SALT_USERNAME,
            "password": settings.SALT_PASSWORD,
            "eauth": "pam",
        }

        if "arg" in kwargs:
            json.update({"arg": kwargs["arg"]})
        if "kwargs" in kwargs:
            json.update({"kwarg": kwargs["kwargs"]})

        try:
            resp = requests.post(
                "http://" + settings.SALT_HOST + ":8123/run",
                json=[json],
                timeout=timeout,
            )
        except Exception:
            return "error"
        else:
            return resp
예제 #5
0
def do_create(self, email, password, fields=None):

    json = {'email': email, 'password': password}

    if fields is not None: json.update(fields)

    r = session.post('{0}/api/profile/signup'.format(api_url),
                     json=json,
                     verify=api_verify_ssl)

    if r.status_code == 409:
        return None

    if r.status_code != 201:
        # not created and not exists
        return None

    #print("headers: ", r.headers)

    self.assertEqual(r.status_code, 201)
    res = r.json()

    self.assertTrue(isinstance(res, dict))

    profile_id = res.get('profile_id')
    self.assertTrue(isinstance(profile_id, int))

    return profile_id
예제 #6
0
 def _build_auth_request(self, verify=False, **kwargs):
     """
     Build the authentication request to SMC
     """
     json = {
         'domain': self.domain
     }
     
     params = {}
     if self.credential.provider_name.startswith('lms'):
         params = self.credential.get_credentials()
     else:
         json.update(authenticationkey=self.credential._api_key)
     
     if kwargs:
         json.update(**kwargs)
         self._extra_args.update(**kwargs) # Store in case we need to rebuild later
     
     request = dict(
         url=self.credential.get_provider_entry_point(self.url, self.api_version),
         json=json,
         params=params,
         headers={'content-type': 'application/json'},
         verify=verify)
     
     return request
예제 #7
0
def update_json(json, keys, new_value):
    for key, value in json.items():
        if keys[0] in key:
            if keys[0] in json and isinstance(value, dict) == False:
                json.update({keys[0]: new_value})
                break
            update_json(value, keys[1:], new_value)
예제 #8
0
파일: option.py 프로젝트: ritksm/polaris
 def json(self):
     json = {
         'trigger': self.trigger,
     }
     if self._kwargs:
         json.update(self._kwargs)
     return json
예제 #9
0
 def json(self):
     json = {
         'trigger': self.trigger,
     }
     if self._kwargs:
         json.update(self._kwargs)
     return json
예제 #10
0
    def get_json(self):
        """Create JSON data for PCI card element.

        :returns: JSON data for PCI card.
        Data for onboard card is as follows:

            {
                "@OnboardControllerIdx":1,
                "LANAdapter":{
                },
                "CNAAdapter":{
                }
            }

        Data for add-on card is as follows:

            {
                "@AddOnCardIdx":1,
                "LANAdapter":{
                },
                "FCAdapter":{
                },
                "CNAAdapter":{
                }
            }
        """
        json = {self.INDEX_KEY: self.card_idx}
        json.update(self.adapter.get_json())
        return json
예제 #11
0
    def toJSON(self):
        json = {
            "__type__": self.__class__.__name__,
        }
        json.update(self.__dict__)

        return json
예제 #12
0
def feedbackFunc(folder_path, camera, channel, model, nonConce, average, json):
    latest_folder = latest_filePath(folder_path + str(camera) + '/')
    _, images = dataRead(latest_folder + '/')
    counter = 0
    highResult_total = 0

    for image in images:
        t = int(time.mktime(datetime.datetime.now().timetuple()))
        #predict
        highResult, lowResult, highResult_idx, lowResult_idx = predict_result(
            image, channel, model)
        if highResult_idx == 1:
            counter += 1
            highResult_total += highResult

    nonConce_rate = counter / len(images)
    average_nonConce = (lambda a, b: b == 0 and 1 or a / b)(highResult_total,
                                                            counter)
    each_jsonData = {
        "time": t,
        "rate": nonConce_rate,
        "value": average_nonConce
    }

    nonConce.append(nonConce_rate)
    average.append(average_nonConce)
    json.update(each_jsonData)

    return
예제 #13
0
파일: host.py 프로젝트: LaCodda/Laser
	def new (self, **kwargs):
		if kwargs['tech'] != 'none':
			techClass = LoadClass ('lib', 'tech', kwargs['tech'], kwargs['tech'], serverName=kwargs['serverName'], serverAlias=kwargs['serverAlias'])
			if techClass:
				techClass.hello ()
				pathDict = self.createHostDirs (kwargs['serverName'])
				if pathDict != False and os.path.exists (pathDict['config']):
					json = Json (ClassAttr (techClass), CreatePath (pathDict['config'], Config.configFile))
					json.update ()
					print ('Хост "{}" был успешно создан с использованием шаблона "{}"'.format (kwargs['serverName'], kwargs['tech']))
					if kwargs['load'].lower () == 'yes':
						techClass.load ()
					if kwargs['adminer'].lower () == 'yes':
						techAdminerClass = LoadClass ('lib', 'tech', 'adminer', 'adminer', serverName=kwargs['serverName'], destinationFile='adminer.php')
						if techAdminerClass:
							techAdminerClass.load ()
			else:
				print ('Tехнологического шаблона "{}" не существует! Укажите правильный шаблон. (к примеру: --tech=php)'.format (kwargs['tech']))
		else:
			print ('Укажите технологический шаблон хоста (к примеру: --tech=php)')
		if kwargs['db'] != 'none':
			dbClass = LoadClass ('lib', 'db', kwargs['db'], kwargs['db'], serverName=kwargs['serverName'], dbname=kwargs['dbname'])
			if dbClass:
				dbClass.createDb ()
				json = Json (ClassAttr (dbClass), CreatePath (Config.serverRoot, kwargs['serverName'], Config.serverDirs['config'], Config.configFile))
				json.update ()
			else:
				print ('Шаблонa баз данных "{}" не существует! Укажите правильный шаблон. (к примеру: --db=mysql)'.format (kwargs['tech']))
예제 #14
0
 def json(self):
     json = {'type': self.type, 'data': self.data}
     if self.name:
         json['name'] = self.name
     if self._kwargs:
         json.update(self._kwargs)
     return json
예제 #15
0
    def json(self):
        """JSON format data."""
        json = {
            'title': self.title,
            'series': list(map(dict, self.series)),
        }

        if self.axis:
            json['xAxis'] = list(map(dict, self.x_axis)) or [{}]
            json['yAxis'] = list(map(dict, self.y_axis)) or [{}]

        if hasattr(self, 'legend'):
            json['legend'] = self.legend.json
        if hasattr(self, 'tooltip'):
            json['tooltip'] = self.tooltip.json
        if hasattr(self, 'toolbox'):
            json['toolbox'] = self.toolbox.json
        if hasattr(self, 'visualMap'):
            json['visualMap'] = list(map(dict, self.visualMap)) or [{}]
        if hasattr(self, 'dataZoom'):
            json['dataZoom'] = list(map(dict, self.dataZoom)) or [{}]
        if hasattr(self, 'grid'):
            json['grid'] = list(map(dict, self.grid)) or [{}]
        if hasattr(self, 'axisPointer'):
            json['axisPointer'] = self.axisPointer.json

        json.update(self.kwargs)
        return json
예제 #16
0
def get_json_releases(json, all, fchannels):
    """Returns release info in JSON format"""
    name = json['Package']

    if all:
        json.update(Releases={})
        for channel in fchannels.items():
            releases = get_releases(channel, name)
            if channel[0] == "Pypi":
                json['Releases'].update({channel[0]: releases})
            elif channel[0] == "Github":
                json['Releases'].update({
                    channel[0]: [
                        dict(
                            zip([x['name'] for x in releases],
                                [x['tarball_url'] for x in releases]))
                    ]
                })
            else:
                json['Releases'].update({
                    channel[0]: [
                        dict(
                            zip([x['version'] for x in releases],
                                [x['build'] for x in releases]))
                    ]
                })
    else:
        releases = get_latest_releases(fchannels, name)
        json.update(Latest_Releases=releases)

    return json
예제 #17
0
파일: option.py 프로젝트: yanyan130111/cjc
 def json(self):
     """JSON format data."""
     json = {
         'trigger': self.trigger,
     }
     if self._kwargs:
         json.update(self._kwargs)
     return json
예제 #18
0
 def json(self):
     """JSON format data"""
     json = {
         "link": self.link,
     }
     if self._kwargs:
         json.update(self._kwargs)
     return json
예제 #19
0
 def json(self):
     """JSON format data"""
     json = {
         "type": self.type,
     }
     if self._kwargs:
         json.update(self._kwargs)
     return json
예제 #20
0
def flattenDict(jDict, json):
    for item in jDict:
        if isinstance(jDict[item], (str, unicode)):
            json.update({item: jDict[item]})
        elif isinstance(jDict[item], dict):
            flattenDict(jDict[item], json)
        elif isinstance(jDict[item], list):
            flattenList(jDict[item], json)
예제 #21
0
 async def get(self, request):
     local_id = request.path_params['id']
     body = await get_db(request).read_local(local_id)
     if not body:
         return JSONResp(DOC_NOT_FOUND, 404)
     json = {'_id': f'_local/{local_id}', '_rev': '0-1'}
     json.update(body)
     return JSONResp(json)
def flattenList(jList, json):
    for item in range(len(jList)):
        if isinstance(jList[item], (str, unicode)):
            json.update({item: jList[item]})
        elif isinstance(jList[item], list):
            flattenList(jList[item], json)
        elif isinstance(jList[item], dict):
            flattenDict(jList[item], json)
예제 #23
0
 def genJson(self):
     node_list = self.db.getNodeList()
     json = {}
     for node in node_list:
         temp = {}
         temp['name'] = node['hostname']
         json.update({self.calcMAC(node['mac'].lower()): temp})
     return json
예제 #24
0
 def to_json(self) -> dict:
     """
     Convert object into JSON representation.
     """
     json = self.contract.to_json()
     # because NEO C# returns a string from "method" instead of sticking to a standard interface
     json.update({'methods': self.methods.to_json()['wildcard']})
     return json
예제 #25
0
 def json(self):
     """JSON format data."""
     json = {
         'trigger': self.trigger,
     }
     if self._kwargs:
         json.update(self._kwargs)
     return json
예제 #26
0
def addToList(name, hash):
    '''
    Actualiza la lista de canciones descargadas con el
    nombre y hash de la nueva cancion.
    '''
    json = jsonRead()
    json.update({hash: name})
    return json
 def genJson(self):
     node_list = self.db.getNodeList()
     json = {}
     for node in node_list:
         temp = {}
         temp['name'] = node['hostname']
         json.update({self.calcMAC(node['mac'].lower()): temp})
     return json
예제 #28
0
 def to_json(self, **kwargs):
     json = Object.to_json(self, **kwargs)
     items = [
         item.to_json() if isinstance(item, Object) else item
         for item in self.items
     ]
     json.update({"items": items})
     return json
예제 #29
0
 def json(self):
     """JSON format data."""
     json = {
         'code': self.code,
         'msg': self.msg,
         'result': self.result,
     }
     json.update(self.kwargs)
     return json
예제 #30
0
파일: option.py 프로젝트: yanyan130111/cjc
    def json(self):
        """JSON format data."""
        json = dict(type=self.type, position=self.position, data=self.data)
        if self.name:
            json['name'] = self.name

        if self._kwargs:
            json.update(self._kwargs)
        return json
예제 #31
0
파일: option.py 프로젝트: ritksm/polaris
 def json(self):
     json = {
         'type': self.type,
         'data': self.data
     }
     if self.name is not None:
         json['name'] = self.name
     if self._kwargs:
         json.update(self._kwargs)
     return json
예제 #32
0
 def json(self):
     """JSON format data."""
     json = {
         'orient': self.orient,
         'x': self.position[0],
         'y': self.position[1]
     }
     if self._kwargs:
         json.update(self._kwargs)
     return json
예제 #33
0
 def json_error(status_code, error_class, message, **extra):
     json = {
         'status': status_code,
         'error_class': error_class,
         'message': message,
     }
     json.update(extra)
     response = jsonify(json)
     response.status_code = status_code
     return response
예제 #34
0
    def json(self):
        """JSON format data."""
        json = {
            'top': 150,
            'bottom': 100,
        }

        if self._kwargs:
            json.update(self._kwargs)
        return json
예제 #35
0
파일: api.py 프로젝트: mouedhen/sndlatr
 def _encode_remind_job(self, job):
     json = self._encode_base_job(job)
     json.update({
         'subject': job.subject,
         'threadId': job.thread_id,
         'knownMessageIds': job.known_message_ids,
         'onlyIfNoreply': job.only_if_noreply,
         'disabledReply': job.disabled_reply
     })
     return json
예제 #36
0
파일: git-deps.py 프로젝트: eddyp/git-deps
 def json_error(status_code, error_class, message, **extra):
     json = {
         'status': status_code,
         'error_class': error_class,
         'message': message,
     }
     json.update(extra)
     response = jsonify(json)
     response.status_code = status_code
     return response
예제 #37
0
 def json(self):
     """JSON format data"""
     json = {
         "type": self.type,
         'min': self.min,
         'max': self.max
     }
     if self._kwargs:
         json.update(self._kwargs)
     return json
예제 #38
0
파일: api.py 프로젝트: Schibum/sndlatr
 def _encode_remind_job(self, job):
     json = self._encode_base_job(job)
     json.update({
         'subject': job.subject,
         'threadId': job.thread_id,
         'knownMessageIds': job.known_message_ids,
         'onlyIfNoreply': job.only_if_noreply,
         'disabledReply': job.disabled_reply
     })
     return json
예제 #39
0
파일: option.py 프로젝트: yanyan130111/cjc
 def json(self):
     """JSON format data."""
     json = {
         'orient': self.orient,
         'x': self.position[0],
         'y': self.position[1]
     }
     if self._kwargs:
         json.update(self._kwargs)
     return json
예제 #40
0
    def json(self):
        """JSON format data."""
        json = {
            'data': self.data,
            'orient': self.orient,
            'top': 50,
        }

        if self._kwargs:
            json.update(self._kwargs)
        return json
예제 #41
0
 def json(self):
     """JSON format data."""
     json = {
         'type': self.type,
         'data': self.data
     }
     if self.name:
         json['name'] = self.name
     if self._kwargs:
         json.update(self._kwargs)
     return json
예제 #42
0
    def json(self):
        """JSON format data."""
        json = {
            self.relation: {self.key: self.value}
        }

        if hasattr(self, 'key'):
            json['key'] = self.key
        if hasattr(self, 'key'):
            json['key'] = self.key
        json.update(self.kwargs)
        return json
예제 #43
0
    def json(self):
        """JSON format data."""
        json = dict(
            type=self.type,
            position=self.position,
            data=self.data
        )
        if self.name:
            json['name'] = self.name

        if self._kwargs:
            json.update(self._kwargs)
        return json
예제 #44
0
파일: views.py 프로젝트: hljxuege/gateway
def response_json(**kwargs):
    json = { "statusCode":"200", 
            "message":"success", 
            "navTabId":"",#"method-list", 
            "rel":"", 
            "callbackType":"",#"closeCurrent", 
            "forwardUrl":"http://www.baidu.com", 
            "confirmMsg":"hello" }
    if kwargs:
        json.update(kwargs)
        if kwargs.has_key('message'):
            json.update({'statusCode':"300"})
    
    return json
예제 #45
0
def _ajax_result(request, form, action, comment=None):
    # Based on django-ajaxcomments, BSD licensed.
    # Copyright (c) 2009 Brandon Konkle and individual contributors.
    #
    # This code was extracted out of django-ajaxcomments because
    # django-ajaxcomments is not threadsafe, and it was refactored afterwards.

    success = True
    json_errors = {}

    if form.errors:
        for field_name in form.errors:
            field = form[field_name]
            json_errors[field_name] = _render_errors(field)
        success = False

    json = {
        'success': success,
        'action': action,
        'errors': json_errors,
    }

    if comment is not None:
        context = {
            'comment': comment,
            'action': action,
            'preview': (action == 'preview'),
            'USE_THREADEDCOMMENTS': appsettings.USE_THREADEDCOMMENTS,
        }
        comment_html = render_to_string('comments/comment.html', context, context_instance=RequestContext(request))

        json.update({
            'html': comment_html,
            'comment_id': comment.id,
            'parent_id': None,
            'is_moderated': not comment.is_public,   # is_public flags changes in comment_will_be_posted
        })
        if appsettings.USE_THREADEDCOMMENTS:
            json['parent_id'] = comment.parent_id

    json_response = json.dumps(json)
    return HttpResponse(json_response, mimetype="application/json")
예제 #46
0
    def json(self):
        """JSON format data."""
        json = {
            'title': self.title,
            'series': list(map(dict, self.series)),
        }

        if self.axis:
            json['xAxis'] = list(map(dict, self.x_axis)) or [{}]
            json['yAxis'] = list(map(dict, self.y_axis)) or [{}]

        if hasattr(self, 'legend'):
            json['legend'] = self.legend.json
        if hasattr(self, 'tooltip'):
            json['tooltip'] = self.tooltip.json
        if hasattr(self, 'toolbox'):
            json['toolbox'] = self.toolbox.json
        if hasattr(self, 'visualMap'):
            json['visualMap'] = self.visualMap.json

        json.update(self.kwargs)
        return json
예제 #47
0
def get_id3_genre_id(genre_name):
    scriptpath = os.path.dirname(os.path.realpath(__file__))
    genre_id = None
    with open(scriptpath + "/genre_ids.json") as genre_ids_file:
        try:
            genre_ids
        except:
            genre_ids = json.load(genre_ids_file)
        else:
            genre_ids = json.update(json.load(genre_ids_file))

    if genre_name in genre_ids.keys():
        genre_id = genre_ids[genre_name]
    elif '/' in genre_name:
        genre_array = genre_name.split('/')
        if genre_array[0] in genre_ids.keys():
            genre_id = genre_ids[genre_array[0]]
        elif genre_array[1] in genre_ids.keys():
            genre_id = genre_ids[genre_array[1]]

    return genre_id
예제 #48
0
파일: pbf.py 프로젝트: dimagi/WBNigeria
 def _get_json(comment):  # Add whether or not the comment has been viewed.
     json = comment.json()
     json.update({'viewed': comment.pk in views if user else None})
     return json
예제 #49
0
파일: JSAGparser.py 프로젝트: kavod/JSAG3
	def cliChange(self,json):
		self.validate(json)
		# Object
		########
		if self.getType() == 'object':
			choices = []
			width = len(max([i['title'] for i in self['properties'].values()], key=len))
			properties = sorted(self['properties'].iteritems(),key=lambda k:k[1]['order'] if 'order' in k[1].keys() else 0)
			for key,item in properties:
				if item.getType() in SIMPLE_TYPES:
					line = item.display(json[key],width=width,ident='')
				elif item.getType() == 'array':
					item_count = unicode(len(json[key])) if key in json.keys() else "0"
					value = '{0} managed'.format(item_count)
					line = ("{0:" + unicode(width)+"} - {1}").format(item['title'],value)
				elif item.getType() == 'hidden':
					continue
				else:
					value = 'Managed'
					line = ("{0:" + unicode(width)+"} - {1}").format(item['title'],value)
				choices.append(line)
			reponse = Prompt.promptChoice(unicode(self['title']),choices,warning='',selected=[],default = None,mandatory=True,multi=False)
		
			changed_item = properties[reponse][1]
			result = changed_item.cliChange(json[properties[reponse][0]])
			json.update({properties[reponse][0]:result})
			return json

		# array
		########
		elif self.getType() == 'array':
			lines = self.display(json)
			warning = '\n'.join(lines)
			choices = ['Add','Delete','Reset all']
			reponse = Prompt.promptChoice('** Managed {0}'.format(self['title']),choices,warning=warning,selected=[],default = None,mandatory=True,multi=False)
			if reponse == 0: # Add
				element = self['items'].cliCreate()
				if element is not None:
					json.append(element)
				return json
			elif reponse == 1: # Delete
				result = Prompt.promptSingle(
						'Which {0} must be deleted?'.format(self['items']['title']),
						choix=[self['items'].display(item) for item in json],
						password=False,
						mandatory=True,
						default=None,
						warning=''
						)
				del json[result]
				return json
			elif reponse == 2: # Reset all
				del json
				return []
		# Field
		########
		elif self.getType() in SIMPLE_TYPES:
			result = self.cliCreate()
			Prompt.print_question(self['title'] + ' changed!')
			return result
		
		# Hidden
		#########
		elif self.getType() == 'hidden':
			return self['default']