简体   繁体   English

使用pyArango重命名集合

[英]Rename collection with pyArango

I'm trying to rename a ArangoDB collection using pyArango . 我正在尝试使用pyArango重命名ArangoDB集合。 This is what I have so far: 这是我到目前为止的内容:

connection = pyArango.Connection('http://random-address', username='random-username', password='random-password')
test_db = Database(connection, 'test-db')
collection = test_db["new"]
collection.action("PUT", "rename", name="newname")

The code fails in line 4: 该代码在第4行中失败:

{'error': True, 'code': 400, 'errorNum': 1208, 'errorMessage': 'name must be non-empty'} {“错误”:True,“代码”:400,“错误编号”:1208,“错误消息”:“名称必须为非空”}

I'm probably using the action method incorrectly but the documentation does not provide any examples. 我可能使用了错误的action方法,但文档未提供任何示例。 Anybody got an idea? 有人知道吗?

A JSON object {"name": "newname"} needs to be passed as request body. 需要将JSON对象{"name": "newname"}作为请求主体传递。 The new name can not be passed as URL path parameter. 新名称不能作为URL路径参数传递。 The problem is the implementation of collection.action() : 问题是collection.action()的实现:

def action(self, method, action, **params) :
    "a generic fct for interacting everything that doesn't have an assigned fct"
    fct = getattr(self.connection.session, method.lower())
    r = fct(self.URL + "/" + action, params = params)
    return r.json()

The keyword arguments end up as dict called params . 关键字参数最终以称为params dict结束。 This object is passed to the request function fct() as named parameter params . 该对象作为命名参数params传递给请求函数fct() This parameter receives the dict and converts it to URL path parameters, eg ?name=newname which is not supported by the HTTP API of the server. 该参数接收字典并将其转换为URL路径参数,例如,服务器的HTTP API不支持的?name=newname

There is unfortunately no way to pass a payload via action() . 不幸的是,没有办法通过action()传递有效负载。 You can write some custom code however: 您可以编写一些自定义代码:

from pyArango.connection import *
connection = Connection('http://localhost:8529', username='root', password='')

try:
    connection.createDatabase('test-db')
except CreationError:
    pass
test_db = Database(connection, 'test-db')

try:
    test_db.createCollection(name='new')
except CreationError:
    pass
collection = test_db['new']

r = connection.session.put(collection.URL + '/rename', data='{"name":"newname"}')
print(r.text)
collection = test_db['newname']

You can also use a dict for the payload and transform it to JSON if you want: 如果需要,还可以对有效负载使用字典并将其转换为JSON:

import json
...put(..., data=json.dumps({"name": "newname"}))

I've fixed it like this: 我已经将其固定为:

def rename_collection(arango_uri, username, password, database, collection, new_name):
    url = '{}/_db/{}/_api/collection/{}/rename'.format(arango_uri, database, collection)
    params = {"name": new_name}
    response = requests.put(url, data=json.dumps(params), auth=HTTPBasicAuth(username, password))
    return response

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM