我想调用hdfs restapi来上传一个文件

dvtswwa3  于 2021-06-03  发布在  Hadoop
关注(0)|答案(1)|浏览(451)

我想调用hdfs restapi来上传一个文件 httplib .
我的程序创建了该文件,但其中没有内容。

这是我的密码:

import httplib

conn=httplib.HTTPConnection("localhost:50070")
conn.request("PUT","/webhdfs/v1/levi/4?op=CREATE")
res=conn.getresponse()
print res.status,res.reason
conn.close()

conn=httplib.HTTPConnection("localhost:50075")
conn.connect()
conn.putrequest("PUT","/webhdfs/v1/levi/4?op=CREATE&user.name=levi")
conn.endheaders()
a_file=open("/home/levi/4","rb")
a_file.seek(0)
data=a_file.read()
conn.send(data)
res=conn.getresponse()
print res.status,res.reason
conn.close()

==================================================
这是回报:
307临时\u重定向201已创建

好的,文件已经创建,但是没有发送内容。
当我评论 #conn.send(data) ,结果是一样的,还是没有内容。
可能文件读取或发送错误,不确定。
你知道这是怎么发生的吗?

k7fdbhmy

k7fdbhmy1#

看起来您的代码没有在第二个put请求中使用307中的“location”头。
我一直在研究一个可能有用的python webhdfs Package 器的分支,您可以在这里看到完整的代码:https://github.com/carlosmarin/webhdfs-py/blob/master/webhdfs/webhdfs.py
您感兴趣的方法是:

def copyfromlocal(self, source_path, target_path, replication=1, overwrite=True):
    url_path = WEBHDFS_CONTEXT_ROOT + target_path + '?op=CREATE&overwrite=' + 'true' if overwrite else 'false'

    with _NameNodeHTTPClient('PUT', url_path, self.namenode_host, self.namenode_port, self.username) as response:
        logger.debug("HTTP Response: %d, %s" % (response.status, response.reason))
        redirect_location = response.msg["location"]
        logger.debug("HTTP Location: %s" % redirect_location)
        (redirect_host, redirect_port, redirect_path, query) = self.parse_url(redirect_location)

        # Bug in WebHDFS 0.20.205 => requires param otherwise a NullPointerException is thrown
        redirect_path = redirect_path + "?" + query + "&replication=" + str(replication)

        logger.debug("Redirect: host: %s, port: %s, path: %s " % (redirect_host, redirect_port, redirect_path))
        fileUploadClient = HTTPConnection(redirect_host, redirect_port, timeout=600)

        # This requires currently Python 2.6 or higher
        fileUploadClient.request('PUT', redirect_path, open(source_path, "r").read(), headers={})
        response = fileUploadClient.getresponse()
        logger.debug("HTTP Response: %d, %s" % (response.status, response.reason))
        fileUploadClient.close()

        return json.loads(response.read())

相关问题