python 内存数据库与远程服务

需要import的python 内存数据库代码参考下面的链接:

http://blog.csdn.net/ubuntu64fan/article/details/50424683

现在的问题:

创建一个内存数据服务,可以供本地或远程用户连接上来,多个用户同时并发读写

这个内存数据库。

解决的步骤有3:

(1) 创建服务器(memdb_server.py)

(2) 创建客户端(memdb_client.py)

(3) 启动服务器,启动客户端

1 服务器代码:

#!/usr/bin/python
#-*- coding: UTF-8 -*-
# memdb_server.py
#
# Queues are thread and process safe.
# Refer:
#   https://docs.python.org/2/library/multiprocessing.html
#
########################################################################
# The MIT License (MIT)
#    http://opensource.org/licenses/MIT
#
#  Copyright (c) 2015 copyright cheungmine
#
# Permission is hereby granted, free of charge, to any person obtaining
#  a copy of this software and associated documentation files (the
#  "Software"), to deal in the Software without restriction, including
#  without limitation the rights to use, copy, modify, merge, publish,
#  distribute, sublicense, and/or sell copies of the Software, and to
#  permit persons to whom the Software is furnished to do so, subject
#  to the following conditions:
#
# The above copyright notice and this permission notice shall be
#  included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
########################################################################

from multiprocessing.managers import BaseManager
from multiprocessing import RLock

from memdb import MemDB
from memdb import MemDBConnect

# global variables
#
lock = RLock()

memdbConn = MemDBConnect(MemDB())

class MemDBManager(BaseManager): pass

# thread safe class
#
class MemDBConnectProxy(object):
    global memdbConn

    def QueryTables(self):
        return memdbConn.QueryTablesNothrow()

    def QueryTableKeys(self, tablename):
        return memdbConn.QueryTableKeysNothrow(tablename)

    def CreateTable(self, tablename):
        memdbConn.CreateTableNothrow(tablename)
        pass

    def DropTable(self, tablename):
        memdbConn.DropTableNothrow(tablename)
        pass

    def GetValue(self, tablename, key, defaultvalue):
        return memdbConn.GetValueNothrow(tablename, key, defaultvalue)

    def AddValue(self, tablename, key, value):
        return memdbConn.AddValueNothrow(tablename, key, value)

    def DelValue(self, tablename, key):
        memdbConn.DelValueNothrow(tablename, key)

    def AppendValueList(self, tablename, key, value, non_repeated_value):
        memdbConn.AppendValueListNothrow(tablename, key, value, non_repeated_value)

    def AppendValueListMulti(self, tablenames, keys, values, non_repeated_values):
        memdbConn.AppendValueListMultiNothrow(tablenames, keys, values, non_repeated_values)

###########################################################
#
class MemDBManagerServer:
    MemDBManager.register('get_lock', callable=lambda: lock)
    MemDBManager.register('MemDBConnect', MemDBConnectProxy)

    def __init__(self, host, port, passkey):
        self.manager = MemDBManager(address=(host, port), authkey=passkey)
        self.server = self.manager.get_server()
        pass

    def start(self):
        self.server.serve_forever()
        pass

    def stop(self):
        self.server.shutdown()
        self.stop_flag = 1
        pass

###########################################################
# start('', 12345, 'abc')
#
def start(host, port, passkey):
     from memdb_server import MemDBManagerServer

     server = MemDBManagerServer(host, port, passkey)
     server.start()

2 客户端代码:

#!/usr/bin/python
#-*- coding: UTF-8 -*-
# memdb_client.py
#
# Queues are thread and process safe.
#
########################################################################
# The MIT License (MIT)
#    http://opensource.org/licenses/MIT
#
#  Copyright (c) 2015 copyright cheungmine
#
# Permission is hereby granted, free of charge, to any person obtaining
#  a copy of this software and associated documentation files (the
#  "Software"), to deal in the Software without restriction, including
#  without limitation the rights to use, copy, modify, merge, publish,
#  distribute, sublicense, and/or sell copies of the Software, and to
#  permit persons to whom the Software is furnished to do so, subject
#  to the following conditions:
#
# The above copyright notice and this permission notice shall be
#  included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
########################################################################

from multiprocessing.managers import BaseManager
from multiprocessing import RLock
from memdb import *

class MemDBConnectProxy(object): pass

class MemDBManager(BaseManager): pass

class MemDBManagerClient:
    MemDBManager.register('get_lock', callable=lambda: lock)
    MemDBManager.register('MemDBConnect', callable=lambda: MemDBConnectProxy)

    def __init__(self, servhost, servport, authkey):
        self.config = {
            "host": servhost,
            "port": int(servport),
            "authkey": authkey
        }
        self._lock = None
        self.manager = MemDBManager(address=(self.config['host'], self.config['port']), authkey=self.config['authkey'])
        self.manager.connect()
        pass

    def __del__(self):
        self.unlock()
        pass

    def lock(self):
        if not self._lock:
            self._lock = self.manager.get_lock()
            self._lock.acquire()
        pass

    def unlock(self):
        if self._lock:
            l = self._lock
            self._lock = None
            l.release()
        pass

    def getMemDBConnect(self):
        self.memdbConn = self.manager.MemDBConnect()
        return self.memdbConn

###########################################################
# start('', 12345, 'abc')
#
def start(host, port, passkey):
    from memdb_client import MemDBManagerClient

    client = MemDBManagerClient(host, port, passkey)
    print "connect to memdb server success"
    memdbConn = client.getMemDBConnect()

    tables = ["china", "america", "russian"]

    # memdb_server.MemDBConnectProxy
    for t in tables:
        memdbConn.CreateTable(t)
    print memdbConn.QueryTables()

    memdbConn.AddValue("china", "capital", "Beijing")
    memdbConn.AddValue("china", "1-city", "Shanghai")
    memdbConn.AddValue("america", "capital", "Washington")
    memdbConn.AddValue("america", "1-city", "Newyork")
    memdbConn.AddValue("russian", "capital", "Moscow")
    memdbConn.AddValue("russian", "1-city", "Moscow")

    memdbConn.AppendValueListMulti(
        ["china", "america", "russian"],
        ["population", "population", "population"],
        [130000, 30000, 20000],
        [True, True, True])

    for t in tables:
        keys = memdbConn.QueryTableKeys(t)
        for k in keys:
            v = memdbConn.GetValue(t, k, None)
            print "%s: %r=>%r" % (t, k, v)

3 开二个终端,分别启动服务和客户端:

服务端:

Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import memdb_server
>>> memdb_server.start('', 12345, 'abc')

客户端:

Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import memdb_client
>>> memdb_client.start('', 12345, 'abc')
connect to memdb server success
['russian', 'america', 'china']
china: '1-city'=>'Shanghai'
china: 'population'=>[130000]
china: 'capital'=>'Beijing'
america: '1-city'=>'Newyork'
america: 'population'=>[30000]
america: 'capital'=>'Washington'
russian: '1-city'=>'Moscow'
russian: 'population'=>[20000]
russian: 'capital'=>'Moscow'
>>>

python 内存数据库与远程服务的更多相关文章

  1. Python内存数据库/引擎

    1 初探 在平时的开发工作中,我们可能会有这样的需求:我们希望有一个内存数据库或者数据引擎,用比较Pythonic的方式进行数据库的操作(比如说插入和查询). 举个具体的例子,分别向数据库db中插入两 ...

  2. python内存数据库pydblite

    Pure-Python engine 最近由于项目开发中发现python informixDB模块对多线程的支持非常不好,当开启两个线程同时连接informix数据库的时候,数据库会报错,显示SQL ...

  3. 【python】-- Redis简介、命令、示例

    Redis简介 Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-value数据库. Redis 与其他 key - value 缓存产品有以下三个特点: Redis支持数据的持久化 ...

  4. python之redis和memcache操作

    Redis 教程 Redis是一个开源(BSD许可),内存存储的数据结构服务器,可用作数据库,高速缓存和消息队列代理.Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-value数据 ...

  5. [Python] Create a Django project in Pycharm

    From: http://blog.csdn.net/u013088062/article/details/50158239 From: http://blog.csdn.net/u013088062 ...

  6. [Python] Interpreter setting in Pycharm

    From: http://blog.csdn.net/u013088062/article/details/50135135 From: http://blog.csdn.net/u013088062 ...

  7. 在ubunut下使用pycharm和eclipse进行python远程调试

    我比较喜欢Pycharm,因为这个是JetBrains公司出的python IDE工具,该公司下的java IDE工具--IDEA,无论从界面还是操作上都甩eclipse几条街,但项目组里有些人使用e ...

  8. Python爬虫(图片)编写过程中遇到的问题

    最近我突然对网络爬虫开窍了,真正做起来的时候发现并不算太难,都怪我以前有点懒,不过近两年编写了一些程序,手感积累了一些肯定也是因素,总之,还是惭愧了.好了,说正题,我把这两天做爬虫的过程中遇到的问题总 ...

  9. 轻量级开源内存数据库SQLite性能测试

    [IT168 专稿]SQLite是一款轻型的数据库,它占用资源非常的低,同时能够跟很多程序语言相结合,但是支持的SQL语句不会逊色于其他开源数据库.它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品 ...

随机推荐

  1. vsftpd详解(ubuntu)

    安装 apt-get instll vsftpd 配置vsftp vim vsftpd.conf listen=YES listen_port= anonymous_enable=NO local_e ...

  2. 14_Python将列表作为栈和队列_Python编程之路

    上一篇文章跟大家介绍了列表的一些方法,这一节我们还是讲列表 只是这一节我们要联系一些数据结构,来讲列表 栈 首先我们要理解一下栈是一种什么数据结构 栈(stack)又名堆栈,它是一种运算受限的线性表. ...

  3. python while条件和if判断的总练习

    输出123456 89的数字 num =1 while num < 11: if num == 7: pass else: print(num) num = num + 1 输出1-100的奇数 ...

  4. ES6(数据结构_2)

    数据结构—2 Map 与 Array 的对比 Set 与 Array的对比 Map 与 Object 的对比 Set 与 Object 的对比 (增.查.改.删) 一.Map 与 Array 的对比 ...

  5. scratch写的图灵机

    大多数人对于scratch不感冒,因为觉得这是孩子玩的.的确,积木的方式不适合专业程序员写代码,然而别小看scratch,怎么说,它也是图灵完备的.而且,过程支持递归,虽然带不了返回值. 虽然计算速度 ...

  6. CF | Alyona and Mex

    Someone gave Alyona an array containing n positive integers a1, a2, ..., an. In one operation, Alyon ...

  7. J-Link固件烧录以及使用J-Flash向arm硬件板下载固件程序

    这篇文章的最初版本是在15年写的https://blog.csdn.net/u010592722/article/details/45575663,后来又遇到了一些新问题,故更新在了这里. 一.始于安 ...

  8. 弹出层之2:JQuery.BlockUI

    JQuery.BlockUI是众多JQuery插件弹出层中的一个,它小巧(原版16k,压缩后10左右),容易使用, 功能齐全,支持Iframe,支持Modal,可定制性高也意味他默认谦虚的外表. jQ ...

  9. 安卓高级5 zXing

    ZXing作者的github地址: https://github.com/zxing/zxing 这里为大家也提供一个封装好的最新的ZXing Lib: https://github.com/xuyi ...

  10. 5秒让你的View变3D,ThreeDLayout使用和实现

    在很久很久以前,写了一篇自定义3d view的博客.但是只是讲了如何实现,实现起来还是比较耗时,所以本着平易近人的心态,把他封装成了一个ViewGroup,只需要在你的view或者布局外面包裹一层Th ...