Example #1
0
def deserialize(data, fmcorefile):
    """Loads a json string into the corresponding object."""

    global dir_mdata_path
    global folder_dbase
    global config

    try:
        if fmcorefile == utils.FMCOREFILES.DATABASE:
            descriptor_list = utils.json_decode(json.loads(data))
            for d_dict in descriptor_list:
                try:
                    # generate a DirDescriptor namedtuple from the deserialized dict
                    # NOTE: the field must be in the same order as the namedtuple declaration
                    dir_desc = DirDescriptor(**d_dict)

                    dir_mdata = mdata.MData(dir_desc.dirpath, autoload=False)
                    dir_mdata.override_save_path(dir_mdata_path,
                                                 dir_desc.dir_uuid)
                    dir_mdata.load()

                    folder_dbase[dir_desc.dirpath] = DBaseEntry(
                        descriptor=dir_desc,
                        mdata_list=load_folder_mdatas(dir_desc.dirpath),
                        dir_mdata=dir_mdata)
                except KeyError as ke:
                    log.error(
                        "Unable to generate database entry from descriptor {}. Exception: {}"
                        .format(d_dict, ke))
        elif fmcorefile == utils.FMCOREFILES.CONFIG:
            config = utils.json_decode(json.loads(data))
    except ValueError as v_error:
        log.error("{} deserialization failed for <{}> - {}".format(
            utils.FMCOREFILES.get_name(fmcorefile).capitalize(), dbase_path,
            v_error))
Example #2
0
    def inner(*a, **b):
        raw = False
        method, get, post, user = None, None, None, None
        if len(a) > 0 and isinstance(a[0], HttpRequest):
            req = a[0]
            method = req.method
            get = req.GET
            user = req.user

            if not req.user.is_authenticated():
                return json_return(status=401)

            if not method in ('GET', 'POST', 'PUT', 'DELETE'):
                return json_return(status=501)

            if 'CONTENT_TYPE' in req.META and 'application/json' in req.META[
                    'CONTENT_TYPE']:
                try:
                    post = json_decode(req.raw_post_data)
                except:
                    return json_return(status=400)
        else:
            raw = True
            try:
                method, get, post, user = b.pop('method', None), b.pop(
                    'get', {}), b.pop('post', {}), b.pop('user')
            except:
                return -1
        try:
            ret = func(method, get, post, user, **b)
            return ret if raw else json_return(ret)
        except:
            return -1 if raw else json_return(status=500)
Example #3
0
    def _get_content(self, url, params):
        response = requests.get(url, params=params)
        if response.status_code == 200:
            content_json = response.content
            data = json_decode(content_json)

            return data
    def _get_content(self, url, params):
        response = requests.get(url, params=params)
        if response.status_code == 200:
            content_json = response.content
            data = json_decode(content_json)

            return data
Example #5
0
	def inner(*a, **b):
		raw = False
		method, get, post, user = None, None, None, None
		if len(a) > 0 and isinstance(a[0], HttpRequest):
			req = a[0]
			method = req.method
			get = req.GET
			user = req.user

			if not req.user.is_authenticated():
				return json_return(status=401)

			if not method in ('GET', 'POST', 'PUT', 'DELETE'):
				return json_return(status=501)

			if 'CONTENT_TYPE' in req.META and 'application/json' in req.META['CONTENT_TYPE']:
				try:
					post = json_decode(req.raw_post_data)
				except:
					return json_return(status=400)
		else:
			raw = True
			try:
				method, get, post, user = b.pop('method', None), b.pop('get', {}), b.pop('post', {}), b.pop('user')
			except:
				return -1
		try:
			ret = func(method, get, post, user, **b)
			return ret if raw else json_return(ret)
		except:
			return -1 if raw else json_return(status=500)
Example #6
0
    def deserialize(self, data):
        """Loads a json string into the data section of this MData class."""

        try:
            self.data = utils.json_decode(json.loads(data))
        except ValueError as v_error:
            log.error("Metadata deserialization failed for <{}> - {}".format(
                self.fpath, v_error))
    def _get_content(self, url, params):
        response = requests.get(url, params=params)
        if response.status_code == 200:
            content_json = response.content
            jsonString = content_json.decode("utf-8")
            data = json_decode(jsonString)

            return data
Example #8
0
def main():
    global b_debug
    try:
        if len(sys.argv) >= 3:
            b_debug = True
        if b_debug:
            print json.dumps(
                json_decode(sys.argv[1]), indent=4, ensure_ascii=False)
        params_json = json_decode(sys.argv[1])
        url = params_json['url']
        strategy = params_json['strategy']
        phantomjs_config = params_json['phantomjs_config']
        run_phantomjs(url, strategy, phantomjs_config)
    except:
        if b_debug:
            print traceback.format_exc()
        print(cf.head + json_encode(
            {'error': 'ParmasParse', 'message': traceback.format_exc()}))
Example #9
0
def index(page):
    
    current_page = int(page)
    items = find_page(int(page))[0]
    prev_page = 1
    next_page = 1

    if current_page == 1:
        prev_page = 1
    else:
        prev_page = current_page - 1
    
    if current_page == items[1]:
        next_page = items[1]
    else:
        next_page = current_page + 1
    
    return render_template('index.html', items=json_decode(items), prev_page = prev_page, next_page = next_page)
Example #10
0
	def inner(*a, **b):
		raw = False
		method, get, post, user = None, None, None, None
		if len(a) > 0 and isinstance(a[0], HttpRequest):
			req = a[0]
			method = req.method
			get = req.GET
			user = req.user

			# api 的 basic 认证
			if 'HTTP_AUTHORIZATION' in req.META and req.META['HTTP_AUTHORIZATION'].startswith('Basic '):
				try:
					username, password = req.META['HTTP_AUTHORIZATION'][6:].decode('base64').split(':', 1)
				except:
					return json_return(status=400)

				user = authenticate(username=username, password=password)
				if not user:
					return json_return(status=401)
			elif not req.user.is_authenticated():
				return json_return(status=401)

			if not method in ('GET', 'POST', 'PUT', 'DELETE'):
				return json_return(status=501)

			if 'CONTENT_TYPE' in req.META and 'application/json' in req.META['CONTENT_TYPE']:
				try:
					post = json_decode(req.raw_post_data)
				except:
					return json_return(status=400)
		else:
			raw = True
			try:
				method, get, post, user = b.pop('method', None), b.pop('get', {}), b.pop('post', {}), b.pop('user')
			except:
				return -1
		try:
			ret = func(method, get, post, user, **b)
			return ret if raw else json_return(ret)
		except:
			return -1 if raw else json_return(status=500)
Example #11
0
def restore_term_settings(location, session):
    """
    Returns the terminal settings associated with the given *location* that are
    stored in the user's session directory.
    """
    session_dir = options.session_dir
    session_dir = os.path.join(session_dir, session)
    settings_path = os.path.join(session_dir, 'term_settings.json')
    if not os.path.exists(settings_path):
        return # Nothing to do
    with io.open(settings_path, encoding='utf-8') as f:
        try:
            settings = json_decode(f.read())
        except ValueError:
            # Something wrong with the file.  Remove it
            term_log.error(_(
                "Error decoding {0}.  File will be removed.").format(
                    settings_path))
            os.remove(settings_path)
            return {}
    return settings
Example #12
0
def save_term_settings(term, location, session, settings):
    """
    Saves the *settings* associated with the given *term*, *location*, and
    *session* in the 'term_settings.json' file inside the user's session
    directory.

    When complete the given *callback* will be called (if given).
    """
    term = str(term) # JSON wants strings as keys
    term_settings = RUDict()
    term_settings[location] = {term: settings}
    session_dir = options.session_dir
    session_dir = os.path.join(session_dir, session)
    settings_path = os.path.join(session_dir, 'term_settings.json')
    # First we read in the existing settings and then update them.
    if os.path.exists(settings_path):
        with io.open(settings_path, encoding='utf-8') as f:
            term_settings.update(json_decode(f.read()))
        term_settings[location][term].update(settings)
    with io.open(settings_path, 'w', encoding='utf-8') as f:
        f.write(json_encode(term_settings))
Example #13
0
def restore_term_settings(location, session):
    """
    Returns the terminal settings associated with the given *location* that are
    stored in the user's session directory.
    """
    session_dir = options.session_dir
    session_dir = os.path.join(session_dir, session)
    settings_path = os.path.join(session_dir, 'term_settings.json')
    if not os.path.exists(settings_path):
        return  # Nothing to do
    with io.open(settings_path, encoding='utf-8') as f:
        try:
            settings = json_decode(f.read())
        except ValueError:
            # Something wrong with the file.  Remove it
            term_log.error(
                _("Error decoding {0}.  File will be removed.").format(
                    settings_path))
            os.remove(settings_path)
            return {}
    return settings
Example #14
0
def save_term_settings(term, location, session, settings):
    """
    Saves the *settings* associated with the given *term*, *location*, and
    *session* in the 'term_settings.json' file inside the user's session
    directory.

    When complete the given *callback* will be called (if given).
    """
    term = str(term)  # JSON wants strings as keys
    term_settings = RUDict()
    term_settings[location] = {term: settings}
    session_dir = options.session_dir
    session_dir = os.path.join(session_dir, session)
    settings_path = os.path.join(session_dir, 'term_settings.json')
    # First we read in the existing settings and then update them.
    if os.path.exists(settings_path):
        with io.open(settings_path, encoding='utf-8') as f:
            term_settings.update(json_decode(f.read()))
        term_settings[location][term].update(settings)
    with io.open(settings_path, 'w', encoding='utf-8') as f:
        f.write(json_encode(term_settings))
Example #15
0
 def body(self):
     try:
         return json_decode(self.request.body)
     except ValueError:
         raise tornado.web.HTTPError(400, 'Bad json body')