python In memory database and remote service

need import Of python Refer to the link below for in memory database code :

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

Now the question is :

Create a memory data service , It can be connected by local or remote users , Multiple users read and write simultaneously

This in memory database .

The steps are as follows 3:

(1) Create a server (memdb_server.py)

(2) Create client (memdb_client.py)

(3) Start the server , Start client

1 Server code :

#!/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 Client code :

#!/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 Open two terminals , Start the service and client respectively :

Server side :

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')

client :

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 More articles on in memory databases and remote services

  1. Python In-memory database / engine

    1 On In normal development work , We may have such a need : We want to have an in memory database or data engine , Compare with Pythonic The way of database operation ( For example, insert and query ). Take a specific example , To the database db Insert two ...

  2. python In-memory database pydblite

    Pure-Python engine Recently, due to the discovery of python informixDB The module's support for multithreading is very poor , When two threads are connected at the same time informix When it comes to databases , The database will report an error , Show SQL ...

  3. 【python】-- Redis brief introduction 、 command 、 Example

    Redis brief introduction Redis It's completely open source and free , comply with BSD agreement , Is a high-performance key-value database . Redis And others key - value Cache products have the following three characteristics : Redis Support data persistence ...

  4. python And redis and memcache operation

    Redis course Redis It's open source (BSD The license ), Memory storage data structure server , It can be used as a database , Caching and message queuing agents .Redis It's completely open source and free , comply with BSD agreement , Is a high-performance key-value data ...

  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. stay ubunut Next use pycharm and eclipse Conduct python Remote debugging

    I prefer Pycharm, Because this is JetBrains From the company python IDE Tools , The company's java IDE Tools --IDEA, Both in terms of interface and operation eclipse A few blocks , But some people on the project team use e ...

  8. Python Reptiles ( picture ) Problems encountered in the process of writing

    Recently, I'm suddenly enlightened by web crawlers , It's not too hard to do it , I used to be a little lazy , But in the last two years, some programs have been written , The hand feeling has accumulated some, which is definitely a factor , All in all , I'm still ashamed . Okay , Get to the point , I put these two days to do reptiles in the process of the problems encountered in the total ...

  9. Lightweight open source memory database SQLite Performance testing

    [IT168  Manuscript ]SQLite It's a lightweight database , It takes up very low resources , At the same time, it can be combined with many programming languages , But supported by SQL Statement will not be inferior to other open source databases . Its design goal is embedded , And it has been used in many embedded products ...

Random recommendation

  1. 20145215&20145307《 Information security system design basis 》 Experiment five Network communication

    Team members :20145215 Lu Xiaoming .20145307 Chen Junda Experiment report link : Information security system design basis -- Experiment 5 experiment report

  2. testng xml In order java class

    Like the scarlet letter , Execute the installation sequence 4 Classes <?xml version="1.0" encoding="UTF-8"?><suite name=" ...

  3. ACM: SGU 101 Domino- Euler circuit - Union checking set

    sgu 101 - Domino Time Limit:250MS     Memory Limit:4096KB     64bit IO Format:%I64d & %I64u Desc ...

  4. C# Packing and unpacking ( Conversion between value types and reference types )

    In object oriented programming , Sealing refers to putting values or data of non object type , Wrap as object type, and vice versa , Unpacking refers to splitting object types into non object values or data . Example : Define a Circle class class Circle { double radius; ...

  5. (easy)LeetCode 225.Implement Stack using Queues

    Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...

  6. highCharts introduction - Powerful chart library plug-in

    brief introduction         Highcharts It's a pure JavaScript Write a chart Library , Can be very simple and convenient in the web Website or web The application adds interactive charts , And it's free for individuals to learn . Personal websites and non-commercial ...

  7. Java [leetcode 17]Letter Combinations of a Phone Number

    Title Description : Given a digit string, return all possible letter combinations that the number could represent. ...

  8. GetActiveView return NULL by MDI Frame window

    blog stay MDI In the application ,MDI The main frame window (CMDIFrameWnd) Does not have a view associated with it . contrary , Each individual subwindow (CMDIChildWnd) Has one or more views associated with it . therefore , Yes MD ...

  9. ms-on-input

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  10. python modify txt The contents of the document

    ① With r Open the file in mode and use readlines Method to read in the list l in ② Modify related lines , Direct use l[n] The form can be ③ Close file ④ With w Way to open a file , use writelines Method write file ( Overwrite file content ) ⑤ Close file We need to pay attention to ...