带字符串值的codernitydb索引

2024-09-28 22:31:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中使用CodernityDB。在

我想创建一个表,其中表中的一个索引将包含字符串而不是整数。在

我该怎么做?在

以下是我正在使用的教程:

#!/usr/bin/env python
from CodernityDB.database import Database
from CodernityDB.hash_index import HashIndex


class WithXIndex(HashIndex):

    def __init__(self, *args, **kwargs):
        kwargs['key_format'] = 'I'
        super(WithXIndex, self).__init__(*args, **kwargs)

    def make_key_value(self, data):
        a_val = data.get("x")
        if a_val is not None:
            return a_val, None
        return None

    def make_key(self, key):
        return key


def main():
    db = Database('/tmp/tut2')
    db.create()
    x_ind = WithXIndex(db.path, 'x')
    db.add_index(x_ind)

    for x in xrange(100):
        db.insert(dict(x=x))

    for y in xrange(100):
        db.insert(dict(y=y))

    print db.get('x', 10, with_doc=True)


if __name__ == '__main__':
    main()

基本上,我想把字符串值放在x中,而不是整数值,当我尝试这样做时,我收到一条错误消息:“Cannot convert argument to integer”。在

我确信这是一件很容易的事,但我在他们的文件中找不到。在

可能我只需要在make_key_value函数中添加一个str转换,但不确定它是否能工作。在


Tags: key字符串fromselfnonedbmakereturn
2条回答

https://bitbucket.org/codernity/codernitydb-demos/src/1bf5ae166fa5/minitwit/?at=default

有一些例子,看看迷你网.py调用数据库_索引.py在

数据库_索引.py: 有一些在键值对中存储数据的方法

在迷你网.py调用它们并插入到数据库中,查看注册函数。在

我自己也在想办法

这是mini-twit函数的浓缩版,我用它来做实验。在

createDB,顾名思义,创建一个数据库并允许您用数据填充它。在

requestDat,有一些对数据库的查询示例。 [如果您提出了更多的查询来缩小实际数据值,比如从id索引plz post]

在创建数据库.py在

from hashlib import md5
from werkzeug import check_password_hash, generate_password_hash
from CodernityDB.database_thread_safe import ThreadSafeDatabase
from CodernityDB.database import RecordNotFound



#indexTypes

from CodernityDB.hash_index import HashIndex
from CodernityDB.tree_index import TreeBasedIndex

class UserIndex(HashIndex):

    def __init__(self, *args, **kwargs):
        kwargs['key_format'] = '16s'
        super(UserIndex, self).__init__(*args, **kwargs)

    def make_key_value(self, data):
        if data['t'] == 'user':
            username = data['username']
            return md5(username).digest(), {'user_id': data['user_id'], 'email': data['email']}

    def make_key(self, key):
        return md5(key).digest()


class UserIDIndex(HashIndex):

    def __init__(self, *args, **kwargs):
        kwargs['key_format'] = 'I'
        super(UserIDIndex, self).__init__(*args, **kwargs)

    def make_key_value(self, data):
        if data['t'] == 'user':
            user_id = data['user_id']
            return user_id, {'username': data['username'], 'email': data['email']}

    def make_key(self, key):
        return key



#Functions
def register(username_input,email_input,password_input):
    """Registers the user."""

    try:
        cdb.get('user', username_input, with_storage=False)
    except RecordNotFound:
        cdb.insert(dict(
                    t='user',
                    user_id=cdb.count(cdb.all, 'user') + 1,  # do not use in production!
                    username=username_input,
                    email=email_input,
                    pw_hash=generate_password_hash(password_input)))
        print('You were successfully registered')
    else:
        print('The username is already taken')





# configuration
DATABASE = 'testDB'
SECRET_KEY = 'development key'
cdb = ThreadSafeDatabase(DATABASE)


#main
def main():
    if cdb.exists():
        cdb.open()
        cdb.reindex()
    else:
        #from database_indexes import UserIndex, MessageAllIndex, MessageUserIndex, FollowerRel1Index, FollowerRel2Index, UserIDIndex, FollowerIndex
        cdb.create()
        cdb.add_index(UserIndex(cdb.path, 'user'))
        cdb.add_index(UserIDIndex(cdb.path, 'user_id'))

    #test insert
    username_input="none"
    print("type 'n' to end database population")
    while username_input != "n":
        username_input = raw_input("new username: ")
        email_input = raw_input("new email: ")
        password_input = raw_input("new password: ")
        register(username_input,email_input,password_input)


#Run Main
if __name__ == '__main__':
    main()

在请求日期.py在

^{pr2}$

相关问题 更多 >