• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python posixpath.ujoin函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中posixpath.ujoin函数的典型用法代码示例。如果您正苦于以下问题:Python ujoin函数的具体用法?Python ujoin怎么用?Python ujoin使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了ujoin函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: setUp

 def setUp(self):
     super(CommonFileSystemTest, self).setUp()
     self.local_setup()
     self.foo_path = URI(self.baseurl) / 'foo'
     self.existing_dir = ujoin(self.baseurl, 'foo')
     self.existing_file = ujoin(self.baseurl, 'foo', 'foo.txt')
     self.non_existing_file = ujoin(self.baseurl, 'bar.txt')
开发者ID:AbletonAG,项目名称:abl.vpath,代码行数:7,代码来源:test_fs.py


示例2: put

    def put(self, path_or_tuple, folder_id='me/skydrive', overwrite=True):
        """Upload a file (object), possibly overwriting (default behavior)
            a file with the same "name" attribute, if it exists.

            First argument can be either path to a local file or tuple
             of "(name, file)", where "file" can be either a file-like object
             or just a string of bytes.

            overwrite option can be set to False to allow two identically-named
             files or "ChooseNewName" to let OneDrive derive some similar
             unique name. Behavior of this option mimics underlying API."""

        if overwrite is not None:
            if overwrite is False:
                overwrite = 'false'
            elif overwrite in ('true', True):
                overwrite = None  # don't pass it
            elif overwrite != 'ChooseNewName':
                raise ValueError('overwrite parameter'
                                 ' must be True, False or "ChooseNewName".')
        name, src = (basename(path_or_tuple), open(path_or_tuple, 'rb')) \
            if isinstance(path_or_tuple, types.StringTypes) \
            else (path_or_tuple[0], path_or_tuple[1])

        return self(ujoin(folder_id, 'files'), dict(overwrite=overwrite),
                    method='post', files=dict(file=(name, src)))
开发者ID:enchanter,项目名称:python-onedrive,代码行数:26,代码来源:api_v5.py


示例3: get

	def get(self, obj_id, byte_range=None):
		'''Download and return a file object or a specified byte_range from it.
			See HTTP Range header (rfc2616) for possible byte_range formats,
			Examples: "0-499" - byte offsets 0-499 (inclusive), "-500" - final 500 bytes.'''
		kwz = dict()
		if byte_range: kwz['headers'] = dict(Range='bytes={}'.format(byte_range))
		return self(ujoin(obj_id, 'content'), dict(download='true'), raw=True, **kwz)
开发者ID:sjakthol,项目名称:python-onedrive,代码行数:7,代码来源:api_v5.py


示例4: link

	def link(self, obj_id, link_type='shared_read_link'):
		'''Return a preauthenticated (usable by anyone) link to a
				specified object. Object will be considered "shared" by OneDrive,
				even if link is never actually used.
			link_type can be either "embed" (returns html), "shared_read_link" or "shared_edit_link".'''
		assert link_type in ['embed', 'shared_read_link', 'shared_edit_link']
		return self(ujoin(obj_id, link_type), method='get')
开发者ID:sjakthol,项目名称:python-onedrive,代码行数:7,代码来源:api_v5.py


示例5: stor

def stor(*subpaths):
    MANTA_USER = os.environ["MANTA_USER"]
    if not subpaths:
        return "/%s/stor" % MANTA_USER
    subpath = ujoin(*subpaths)
    if subpath.startswith("/"):
        subpath = subpath[1:]
    return "/%s/stor/%s" % (MANTA_USER, subpath)
开发者ID:pombredanne,项目名称:python-manta,代码行数:8,代码来源:common.py


示例6: setUp

 def setUp(self):
     self.client = self.get_client()
     self.base = b = ujoin(TDIR, "manyfiles")
     # If this dir exists already, then save time, don't rebuild it (i.e.
     # presuming all the files were left in place).
     if self.client.type(stor(b)) != "directory":
         self.client.mkdirp(stor(b))
         for i in range(1100):
             self.client.put(stor(b, "f%05d" % i), "index %d" % i)
开发者ID:bitmotive,项目名称:python-manta,代码行数:9,代码来源:test_mantaclient.py


示例7: setUp

 def setUp(self):
     self.client = self.get_client()
     self.base = b = ujoin(TDIR, 'ls')
     self.client.mkdirp(stor(b, "a1"))
     self.client.put(stor(b, "a1/a2.txt"), "this is a1/a2.txt")
     self.client.mkdirp(stor(b, "a1/b2"))
     self.client.put(stor(b, "a1/b2/a3.txt"), "this is a1/b2/a3.txt")
     self.client.mkdirp(stor(b, "b1"))
     self.client.put(stor(b, "c1.txt"), "this is c1.txt")
开发者ID:kitdallege,项目名称:python-manta,代码行数:9,代码来源:test_mantash.py


示例8: get

 def get(self, obj_id, byte_range=None):
     """Download and return a file object or a specified byte_range from it.
         See HTTP Range header (rfc2616) for possible byte_range formats,
         Examples: "0-499" - byte offsets 0-499 (inclusive),
                   "-500" - final 500 bytes."""
     kwz = dict()
     if byte_range:
         kwz["headers"] = dict(Range="bytes={}".format(byte_range))
     return self(ujoin(obj_id, "content"), dict(download="true"), raw=True, **kwz)
开发者ID:Mondego,项目名称:pyreco,代码行数:9,代码来源:allPythonContent.py


示例9: put

	def put( self, path_or_tuple, folder_id='me/skydrive',
			overwrite=None, downsize=None, bits_api_fallback=True ):
		'''Upload a file (object), possibly overwriting (default behavior)
				a file with the same "name" attribute, if it exists.

			First argument can be either path to a local file or tuple
				of "(name, file)", where "file" can be either a file-like object
				or just a string of bytes.

			overwrite option can be set to False to allow two identically-named
				files or "ChooseNewName" to let OneDrive derive some similar
				unique name. Behavior of this option mimics underlying API.

			downsize is a true/false API flag, similar to overwrite.

			bits_api_fallback can be either True/False or an integer (number of
				bytes), and determines whether method will fall back to using BITS API
				(as implemented by "put_bits" method) for large files. Default "True"
				(bool) value will use non-BITS file size limit (api_put_max_bytes, ~100 MiB)
				as a fallback threshold, passing False will force using single-request uploads.'''
		api_overwrite = self._translate_api_flag(overwrite, 'overwrite', ['ChooseNewName'])
		api_downsize = self._translate_api_flag(downsize, 'downsize')
		name, src = self._process_upload_source(path_or_tuple)

		if not isinstance(bits_api_fallback, (int, float, long)):
			bits_api_fallback = bool(bits_api_fallback)
		if bits_api_fallback is not False:
			if bits_api_fallback is True: bits_api_fallback = self.api_put_max_bytes
			src.seek(0, os.SEEK_END)
			if src.tell() > bits_api_fallback:
				log.info(
					'Falling-back to using BITS API due to file size (%.1f MiB > %.1f MiB)',
					*((float(v) / 2**20) for v in [src.tell(), bits_api_fallback]) )
				if overwrite is not None and api_overwrite != 'true':
					raise NoAPISupportError( 'Passed "overwrite" flag (value: {!r})'
						' is not supported by the BITS API (always "true" there)'.format(overwrite) )
				if downsize is not None:
					log.warn( 'Passed "downsize" flag (value: %r) will not'
						' be used with BITS API, as it is not supported there', downsize )
				file_id = self.put_bits(path_or_tuple, folder_id=folder_id) # XXX: overwrite/downsize
				return self.info(file_id)

		return self( ujoin(folder_id, 'files', name),
			dict(overwrite=api_overwrite, downsize_photo_uploads=api_downsize),
			data=src, method='put', auth_header=True )
开发者ID:sjakthol,项目名称:python-onedrive,代码行数:45,代码来源:api_v5.py


示例10: put

    def put(self, path_or_tuple, folder_id='me/skydrive', overwrite=None, downsize=None):
        """Upload a file (object), possibly overwriting (default behavior)
            a file with the same "name" attribute, if it exists.

            First argument can be either path to a local file or tuple
             of "(name, file)", where "file" can be either a file-like object
             or just a string of bytes.

            overwrite option can be set to False to allow two identically-named
             files or "ChooseNewName" to let OneDrive derive some similar
             unique name. Behavior of this option mimics underlying API.

            downsize is a true/false API flag, similar to overwrite."""

        overwrite = self._translate_api_flag(overwrite, 'overwrite', ['ChooseNewName'])
        downsize = self._translate_api_flag(downsize, 'downsize')

        name, src = (basename(path_or_tuple), open(path_or_tuple, 'rb')) \
            if isinstance(path_or_tuple, types.StringTypes) \
            else (path_or_tuple[0], path_or_tuple[1])

        return self(ujoin(folder_id, 'files', name),
                    dict(downsize_photo_uploads=downsize, overwrite=overwrite),
                    data=src, method='put', auth_header=True)
开发者ID:dgoon,项目名称:python-onedrive,代码行数:24,代码来源:api_v5.py


示例11: listdir

	def listdir(self, folder_id='me/skydrive', limit=None, offset=None):
		'Get OneDrive object representing list of objects in a folder.'
		return self(ujoin(folder_id, 'files'), dict(limit=limit, offset=offset))
开发者ID:sjakthol,项目名称:python-onedrive,代码行数:3,代码来源:api_v5.py


示例12: resolve_path

        xres = api.info_update(
            resolve_path(optz.object), json.loads(optz.data))
    elif optz.call == 'link':
        res = api.link(resolve_path(optz.object), optz.type)
    elif optz.call == 'comments':
        res = api.comments(resolve_path(optz.object))
    elif optz.call == 'comment_add':
        res = api.comment_add(resolve_path(optz.object), optz.message)
    elif optz.call == 'comment_delete':
        res = api.comment_delete(optz.comment_id)

    elif optz.call == 'mkdir':
        name, path = optz.name.replace('\\', '/'), optz.folder
        if '/' in name:
            name, path_ext = ubasename(name), udirname(name)
            path = ujoin(path, path_ext.strip('/')) if path else path_ext
        xres = api.mkdir(name=name, folder_id=resolve_path(path),
                         metadata=optz.metadata and json.loads(optz.metadata) or dict())

    elif optz.call == 'get':
        contents = api.get(resolve_path(optz.file), byte_range=optz.byte_range)
        if optz.file_dst:
            dst_dir = dirname(abspath(optz.file_dst))
            if not isdir(dst_dir):
                os.makedirs(dst_dir)
            with open(optz.file_dst, "wb") as dst:
                dst.write(contents)
        else:
            sys.stdout.write(contents)
            sys.stdout.flush()
开发者ID:ofortin,项目名称:python-onedrive,代码行数:30,代码来源:cli_tool.py


示例13: listdir

 def listdir(self, folder_id='me/skydrive', limit=None):
     """Get OneDrive object, representing list of objects in a folder."""
     return self(ujoin(folder_id, 'files'), dict(limit=limit))
开发者ID:cyberatz,项目名称:python-onedrive,代码行数:3,代码来源:api_v5.py


示例14: put_bits

	def put_bits( self, path_or_tuple,
			folder_id=None, folder_path=None, frag_bytes=None,
			raw_id=False, chunk_callback=None ):
		'''Upload a file (object) using BITS API (via several http requests), possibly
				overwriting (default behavior) a file with the same "name" attribute, if it exists.

			Unlike "put" method, uploads to "folder_path" (instead of folder_id) are
				supported here. Either folder path or id can be specified, but not both.

			Passed "chunk_callback" function (if any) will be called after each
				uploaded chunk with keyword parameters corresponding to
				upload state and BITS session info required to resume it, if necessary.

			Returns id of the uploaded file, as retured by the API
				if raw_id=True is passed, otherwise in a consistent (with other calls)
				"file.{user_id}.{file_id}" format (default).'''
		# XXX: overwrite/downsize are not documented/supported here (yet?)
		name, src = self._process_upload_source(path_or_tuple)

		if folder_id is not None and folder_path is not None:
			raise ValueError('Either "folder_id" or "folder_path" can be specified, but not both.')
		if folder_id is None and folder_path is None: folder_id = 'me/skydrive'
		if folder_id and re.search(r'^me(/.*)$', folder_id): folder_id = self.info(folder_id)['id']
		if not frag_bytes: frag_bytes = self.api_bits_default_frag_bytes

		user_id = self.get_user_id()
		if folder_id: # workaround for API-ids inconsistency between BITS and regular API
			match = re.search( r'^(?i)folder.[a-f0-9]+.'
				'(?P<user_id>[a-f0-9]+(?P<folder_n>!\d+)?)$', folder_id )
			if match and not match.group('folder_n'):
				# root folder is a special case and can't seem to be accessed by id
				folder_id, folder_path = None, ''
			else:
				if not match:
					raise ValueError('Failed to process folder_id for BITS API: {!r}'.format(folder_id))
				folder_id = match.group('user_id')

		if folder_id:
			url = self.api_bits_url_by_id.format(folder_id=folder_id, user_id=user_id, filename=name)
		else:
			url = self.api_bits_url_by_path.format(
				folder_id=folder_id, user_id=user_id, file_path=ujoin(folder_path, name).lstrip('/') )

		code, headers, body = self(
			url, method='post', auth_header=True, raw_all=True,
			headers={
				'X-Http-Method-Override': 'BITS_POST',
				'BITS-Packet-Type': 'Create-Session',
				'BITS-Supported-Protocols': self.api_bits_protocol_id })

		h = lambda k,hs=dict((k.lower(), v) for k,v in headers.viewitems()): hs.get(k, '')
		checks = [ code == 201,
			h('bits-packet-type').lower() == 'ack',
			h('bits-protocol').lower() == self.api_bits_protocol_id.lower(),
			h('bits-session-id') ]
		if not all(checks):
			raise ProtocolError(code, 'Invalid BITS Create-Session response', headers, body, checks)
		bits_sid = h('bits-session-id')

		src.seek(0, os.SEEK_END)
		c, src_len = 0, src.tell()
		cn = src_len / frag_bytes
		if frag_bytes * cn != src_len: cn += 1
		src.seek(0)
		for n in xrange(1, cn+1):
			log.debug( 'Uploading BITS fragment'
				' %s / %s (max-size: %.2f MiB)', n, cn, frag_bytes / float(2**20) )
			frag = BITSFragment(src, frag_bytes)
			c1 = c + frag_bytes
			self(
				url, method='post', raw=True, data=frag,
				headers={
					'X-Http-Method-Override': 'BITS_POST',
					'BITS-Packet-Type': 'Fragment',
					'BITS-Session-Id': bits_sid,
					'Content-Range': 'bytes {}-{}/{}'.format(c, min(c1, src_len)-1, src_len) })
			c = c1

			if chunk_callback:
				chunk_callback(
					bytes_transferred=c, bytes_total=src_len,
					chunks_transferred=n, chunks_total=cn,
					bits_session_id=bits_sid )

		if self.api_bits_auth_refresh_before_commit_hack:
			# As per #39 and comments under the gist with the spec,
			#  apparently this trick fixes occasional http-5XX errors from the API
			self.auth_get_token()

		code, headers, body = self(
			url, method='post', auth_header=True, raw_all=True,
			headers={
				'X-Http-Method-Override': 'BITS_POST',
				'BITS-Packet-Type': 'Close-Session',
				'BITS-Session-Id': bits_sid })
		h = lambda k,hs=dict((k.lower(), v) for k,v in headers.viewitems()): hs.get(k, '')
		checks = [code in [200, 201], h('bits-packet-type').lower() == 'ack' ]
			# int(h('bits-received-content-range') or 0) == src_len -- documented, but missing
			# h('bits-session-id') == bits_sid -- documented, but missing
		if not all(checks):
#.........这里部分代码省略.........
开发者ID:knobtviker,项目名称:python-onedrive,代码行数:101,代码来源:api_v5.py


示例15: main


#.........这里部分代码省略.........
			api.auth_get_token()
			print('API authorization was completed successfully.')

	elif optz.call == 'auth_refresh':
		xres = dict(scope_granted=api.auth_get_token())

	elif optz.call == 'quota':
		df, ds = map(size_units, api.get_quota())
		res = dict(free='{:.1f}{}'.format(*df), quota='{:.1f}{}'.format(*ds))
	elif optz.call == 'user':
		res = api.get_user_data()
	elif optz.call == 'recent':
		res = api('me/skydrive/recent_docs')['data']

	elif optz.call == 'ls':
		offset = limit = None
		if optz.range:
			span = re.search(r'^(\d+)?[-:](\d+)?$', optz.range)
			try:
				if not span: limit = int(optz.range)
				else: offset, limit = map(int, span.groups())
			except ValueError:
				parser.error(
					'--range argument must be in the "[offset]-[limit]"'
						' or just "limit" format, with integers as both offset and'
						' limit (if not omitted). Provided: {}'.format(optz.range) )
		res = sorted(
			api.listdir(resolve_path(optz.folder), offset=offset, limit=limit),
			key=op.itemgetter('name') )
		if not optz.objects: res = map(op.itemgetter('name'), res)

	elif optz.call == 'info':
		res = api.info(resolve_path(optz.object))
	elif optz.call == 'info_set':
		xres = api.info_update(resolve_path(optz.object), json.loads(optz.data))
	elif optz.call == 'link':
		res = api.link(resolve_path(optz.object), optz.type)
	elif optz.call == 'comments':
		res = api.comments(resolve_path(optz.object))
	elif optz.call == 'comment_add':
		res = api.comment_add(resolve_path(optz.object), optz.message)
	elif optz.call == 'comment_delete':
		res = api.comment_delete(optz.comment_id)

	elif optz.call == 'mkdir':
		name, path = optz.name.replace('\\', '/'), optz.folder
		if '/' in name:
			name, path_ext = ubasename(name), udirname(name)
			path = ujoin(path, path_ext.strip('/')) if path else path_ext
		xres = api.mkdir( name=name, folder_id=resolve_path(path),
			metadata=optz.metadata and json.loads(optz.metadata) or dict() )

	elif optz.call == 'get':
		contents = api.get(resolve_path(optz.file), byte_range=optz.byte_range)
		if optz.file_dst:
			dst_dir = dirname(abspath(optz.file_dst))
			if not isdir(dst_dir): os.makedirs(dst_dir)
			with open(optz.file_dst, "wb") as dst: dst.write(contents)
		else:
			sys.stdout.write(contents)
			sys.stdout.flush()

	elif optz.call == 'put':
		dst = optz.folder
		if optz.bits_do_auth_refresh_before_commit_hack:
			api.api_bits_auth_refresh_before_commit_hack = True
		if optz.bits_frag_bytes > 0: api.api_bits_default_frag_bytes = optz.bits_frag_bytes
		if dst is not None:
			xres = api.put( optz.file, resolve_path(dst),
				bits_api_fallback=0 if optz.bits else True, # 0 = "always use BITS"
				overwrite=optz.no_overwrite and False, downsize=optz.no_downsize and False )

	elif optz.call in ['cp', 'mv']:
		argz = map(resolve_path, [optz.file, optz.folder])
		xres = (api.move if optz.call == 'mv' else api.copy)(*argz)

	elif optz.call == 'rm':
		for obj in it.imap(resolve_path, optz.object): xres = api.delete(obj)

	elif optz.call == 'tree':
		def recurse(obj_id):
			node = tree_node()
			for obj in api.listdir(obj_id):
				# Make sure to dump files as lists with -o,
				#  not dicts, to make them distinguishable from dirs
				res = obj['type'] if not optz.objects else [obj['type'], obj]
				node[obj['name']] = recurse(obj['id']) \
					if obj['type'] in ['folder', 'album'] else res
			return node
		root_id = resolve_path(optz.folder)
		res = {api.info(root_id)['name']: recurse(root_id)}

	else:
		parser.error('Unrecognized command: {}'.format(optz.call))

	if res is not None: print_result(res, tpl=optz.object_key, file=sys.stdout)
	if optz.debug and xres is not None:
		buff = io.StringIO()
		print_result(xres, file=buff)
		log.debug('Call result:\n{0}\n{1}{0}'.format('-' * 20, buff.getvalue()))
开发者ID:hxhlb,项目名称:python-onedrive,代码行数:101,代码来源:cli_tool.py


示例16: comments

	def comments(self, obj_id):
		'Get OneDrive object representing a list of comments for an object.'
		return self(ujoin(obj_id, 'comments'))
开发者ID:sjakthol,项目名称:python-onedrive,代码行数:3,代码来源:api_v5.py


示例17: put_bits

	def put_bits( self, path_or_tuple,
			folder_id=None, folder_path=None, frag_bytes=None, raw_id=False ):
		'''Upload a file (object) using BITS API (via several http requests), possibly
				overwriting (default behavior) a file with the same "name" attribute, if it exists.

			Unlike "put" method, uploads to "folder_path" (instead of folder_id) are
				supported here. Either folder path or id can be specified, but not both.

			Returns id of the uploaded file, as retured by the API
				if raw_id=True is passed, otherwise in a consistent (with other calls)
				"file.{user_id}.{file_id}" format (default).'''
		# XXX: overwrite/downsize are not documented/supported here yet
		name, src = self._process_upload_source(path_or_tuple)

		if folder_id is not None and folder_path is not None:
			raise ValueError('Either "folder_id" or "folder_path" can be specified, but not both.')
		if folder_id is None and folder_path is None: folder_id = 'me/skydrive'
		if folder_id and re.search(r'^me(/.*)$', folder_id): folder_id = self.info(folder_id)['id']
		if not frag_bytes: frag_bytes = self.api_bits_default_frag_bytes

		user_id = self.get_user_id()
		get_url = lambda:\
			(self.api_bits_url_by_id if folder_id else self.api_bits_url_by_path).format(
				folder_id=folder_id, folder_path=folder_path, user_id=user_id, filename=name )

		for n in xrange(2):
			url = get_url()
			try:
				code, headers, body = self(
					url, method='post', auth_header=True, raw_all=True,
					raise_for={404: NoAPISupportError},
					headers={
						'X-Http-Method-Override': 'BITS_POST',
						'BITS-Packet-Type': 'Create-Session',
						'BITS-Supported-Protocols': self.api_bits_protocol_id })
			except NoAPISupportError as err:
				if not folder_id: raise ProtocolError(err.code, *err.args)
				else: # XXX: workaround for http-404 on folder-id uploads, should be fixed
					log.info('Assuming that BITS API does not support folder_id'
						' uploads, falling back to manual folder_id -> folder_path conversion')
					folder_path, folder_id_orig = list(), folder_id
					for n in xrange(100): # depth limit to prevent inf-loop
						info = self.info(folder_id)
						folder_id = info['parent_id']
						if not folder_id: break
						folder_path.append(info['name'])
					else:
						raise OneDriveInteractionError(
							'Path recursion depth exceeded', folder_id_orig, folder_path )
					folder_id, folder_path = None, ujoin(*reversed(folder_path))
					log.debug('Resolved folder_id %r into path: %r', folder_id_orig, folder_path)
			else: break

		h = lambda k,hs=dict((k.lower(), v) for k,v in headers.viewitems()): hs.get(k, '')
		checks = [ code == 201,
			h('bits-packet-type').lower() == 'ack',
			h('bits-protocol').lower() == self.api_bits_protocol_id.lower() ]
		if not all(checks):
			raise ProtocolError(code, 'Invalid BITS Create-Session response', headers, body, checks)
		bits_sid = headers['bits-session-id']

		src.seek(0, os.SEEK_END)
		c, src_len = 0, src.tell()
		cn = src_len / frag_bytes
		if c * cn != src_len: cn += 1
		src.seek(0)
		for n in xrange(1, cn+1):
			log.debug( 'Uploading BITS fragment'
				' %s / %s (max-size: %.2f MiB)', n, cn, frag_bytes / float(2**20) )
			frag = BITSFragment(src, frag_bytes)
			c1 = c + frag_bytes
			self(
				url, method='post', raw=True, data=frag,
				headers={
					'X-Http-Method-Override': 'BITS_POST',
					'BITS-Packet-Type': 'Fragment',
					'BITS-Session-Id': bits_sid,
					'Content-Range': 'bytes {}-{}/{}'.format(c, min(c1, src_len)-1, src_len) })
			c = c1

		code, headers, body = self(
			url, method='post', auth_header=True, raw_all=True,
			headers={
				'X-Http-Method-Override': 'BITS_POST',
				'BITS-Packet-Type': 'Close-Session',
				'BITS-Session-Id': bits_sid })
		h = lambda k,hs=dict((k.lower(), v) for k,v in headers.viewitems()): hs.get(k, '')
		checks = [code in [200, 201], h('bits-packet-type').lower() == 'ack' ]
			# int(h('bits-received-content-range') or 0) == src_len -- documented, but missing
			# h('bits-session-id') == bits_sid -- documented, but missing
		if not all(checks):
			raise ProtocolError(code, 'Invalid BITS Close-Session response', headers, body, checks)

		# XXX: workaround for API-ids inconsistency
		file_id = h('x-resource-id')
		if not raw_id: file_id = 'file.{}.{}'.format(user_id, file_id)
		return file_id
开发者ID:sjakthol,项目名称:python-onedrive,代码行数:97,代码来源:api_v5.py


示例18: put_bits

    def put_bits(self, path_or_tuple, folder_id=None, folder_path=None, frag_bytes=None, raw_id=False):
        """Upload a file (object) using BITS API (via several http requests), possibly
				overwriting (default behavior) a file with the same "name" attribute, if it exists.

			Unlike "put" method, uploads to "folder_path" (instead of folder_id) are
				supported here. Either folder path or id can be specified, but not both.

			Returns id of the uploaded file, as retured by the API
				if raw_id=True is passed, otherwise in a consistent (with other calls)
				"file.{user_id}.{file_id}" format (default)."""
        # XXX: overwrite/downsize are not documented/supported here (yet?)
        name, src = self._process_upload_source(path_or_tuple)

        if folder_id is not None and folder_path is not None:
            raise ValueError('Either "folder_id" or "folder_path" can be specified, but not both.')
        if folder_id is None and folder_path is None:
            folder_id = "me/skydrive"
        if folder_id and re.search(r"^me(/.*)$", folder_id):
            folder_id = self.info(folder_id)["id"]
        if not frag_bytes:
            frag_bytes = self.api_bits_default_frag_bytes

        user_id = self.get_user_id()
        if folder_id:  # workaround for API-ids inconsistency between BITS and regular API
            match = re.search(r"^(?i)folder.[a-f0-9]+." "(?P<user_id>[a-f0-9]+(?P<folder_n>!\d+)?)$", folder_id)
            if match and not match.group("folder_n"):
                # root folder is a special case and can't seem to be accessed by id
                folder_id, folder_path = None, ""
            else:
                if not match:
                    raise ValueError("Failed to process folder_id for BITS API: {!r}".format(folder_id))
                folder_id = match.group("user_id")

        if folder_id:
            url = self.api_bits_url_by_id.format(folder_id=folder_id, user_id=user_id, filename=name)
        else:
            url = self.api_bits_url_by_path.format(
                folder_id=folder_id, user_id=user_id, file_path=ujoin(folder_path, name).lstrip("/")
            )

        code, headers, body = self(
            url,
            method="post",
            auth_header=True,
            raw_all=True,
            headers={
                "X-Http-Method-Override": "BITS_POST",
                "BITS-Packet-Type": "Create-Session",
                "BITS-Supported-Protocols": self.api_bits_protocol_id,
            },
        )

        h = lambda k, hs=dict((k.lower(), v) for k, v in headers.viewitems()): hs.get(k, "")
        checks = [
            code == 201,
            h("bits-packet-type").lower() == "ack",
            h("bits-protocol").lower() == self.api_bits_protocol_id.lower(),
        ]
        if not all(checks):
            raise ProtocolError(code, "Invalid BITS Create-Session response", headers, body, checks)
        bits_sid = headers["bits-session-id"]

        src.seek(0, os.SEEK_END)
        c, src_len = 0, src.tell()
        cn = src_len / frag_bytes
        if frag_bytes * cn != src_len:
            cn += 1
        src.seek(0)
        for n in xrange(1, cn + 1):
            log.debug("Uploading BITS fragment" " %s / %s (max-size: %.2f MiB)", n, cn, frag_bytes / float(2 ** 20))
            frag = BITSFragment(src, frag_bytes)
            c1 = c + frag_bytes
            self(
                url,
                method="post",
                raw=True,
                data=frag,
                headers={
                    "X-Http-Method-Override": "BITS_POST",
                    "BITS-Packet-Type": "Fragment",
                    "BITS-Session-Id": bits_sid,
                    "Content-Range": "bytes {}-{}/{}".format(c, min(c1, src_len) - 1, src_len),
                },
            )
            c = c1

        if self.api_bits_auth_refresh_before_commit_hack:
            # As per #39 and comments under the gist with the spec,
            #  apparently this trick fixes occasional http-5XX errors from the API
            self.auth_get_token()

        code, headers, body = self(
            url,
            method="post",
            auth_header=True,
            raw_all=True,
            headers={
                "X-Http-Method-Override": "BITS_POST",
                "BITS-Packet-Type": "Close-Session",
                "BITS-Session-Id": bits_sid,
#.........这里部分代码省略.........
开发者ID:hxhlb,项目名称:python-onedrive,代码行数:101,代码来源:api_v5.py


示例19: _api_url_join

 def _api_url_join(self, *slugs):
     slugs = list(urllib.quote(slug.encode("utf-8") if isinstance(slug, unicode) else slug) for slug in slugs)
     return ujoin(*slugs)
开发者ID:hxhlb,项目名称:python-onedrive,代码行数:3,代码来源:api_v5.py


示例20: comments

 def comments(self, obj_id):
     """Get OneDrive object, representing a list of comments
         for an object."""
     return self(ujoin(obj_id, "comments"))
开发者ID:Mondego,项目名称:pyreco,代码行数:4,代码来源:allPythonContent.py



注:本文中的posixpath.ujoin函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python posixpath.urljoin函数代码示例发布时间:2022-05-25
下一篇:
Python posixpath.splitext函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap