Python 分布式计算(作品)

发布于 2024-11-11 04:57:35 字数 2977 浏览 4 评论 0原文

我正在使用旧线程发布试图解决相同问题的新代码。 什么构成了安全的泡菜? 这个?

sock.py

from socket import socket
from socket import AF_INET
from socket import SOCK_STREAM
from socket import gethostbyname
from socket import gethostname

class SocketServer:
  def __init__(self, port):
    self.sock = socket(AF_INET, SOCK_STREAM)
    self.port = port
  def listen(self, data):
    self.sock.bind(("127.0.0.1", self.port))
    self.sock.listen(len(data))
    while data:
      s = self.sock.accept()[0]
      siz, dat = data.pop()
      s.send(siz)
      s.send(dat)
      s.close()

class Socket:
  def __init__(self, host, port):
    self.sock = socket(AF_INET, SOCK_STREAM)
    self.sock.connect((host, port))
  def recv(self, size):
    return self.sock.recv(size)

pack.py

#http://stackoverflow.com/questions/6234586/we-need-to-pickle-any-sort-of-callable
from marshal import dumps as marshal_dumps
from pickle import dumps as pickle_dumps
from struct import pack as struct_pack

class packer:
  def __init__(self):
    self.f = []
  def pack(self, what):
    if type(what) is type(lambda:None):
      self.f = []
      self.f.append(marshal_dumps(what.func_code))
      self.f.append(pickle_dumps(what.func_name))
      self.f.append(pickle_dumps(what.func_defaults))
      self.f.append(pickle_dumps(what.func_closure))
      self.f = pickle_dumps(self.f)
      return (struct_pack('Q', len(self.f)), self.f)

unpack.py

from types import FunctionType
from pickle import loads as pickle_loads
from marshal import loads as marshal_loads
from struct import unpack as struct_unpack
from struct import calcsize

#http://stackoverflow.com/questions/6234586/we-need-to-pickle-any-sort-of-callable

class unpacker:
  def __init__(self):
    self.f = []
    self.fcompiled = lambda:None
    self.sizeofsize = calcsize('Q')
  def unpack(self, sock):
    size = struct_unpack('Q', sock.recv(self.sizeofsize))[0]
    self.f = pickle_loads(sock.recv(size))
    a = marshal_loads(self.f[0])
    b = globals() ##
    c = pickle_loads(self.f[1])
    d = pickle_loads(self.f[2])
    e = pickle_loads(self.f[3])
    self.fcompiled = FunctionType(a, b, c, d, e)
    return self.fcompiled

test.py

from unpack import unpacker
from pack import packer
from sock import SocketServer
from sock import Socket
from threading import Thread
from time import sleep

count = 2
port = 4446

def f():
  print 42

def server():
  ss = SocketServer(port)
  pack = packer()
  functions = [pack.pack(f) for nothing in range(count)]
  ss.listen(functions)

if __name__ == "__main__":
  Thread(target=server).start()
  sleep(1)
  unpack = unpacker()
  for nothing in range(count):
    print unpack.unpack(Socket("127.0.0.1", port))

输出:

<function f at 0x12917d0>
<function f at 0x12915f0>

I'm using an old thread to post new code which attempts to solve the same problem.
What constitutes a secure pickle? this?

sock.py

from socket import socket
from socket import AF_INET
from socket import SOCK_STREAM
from socket import gethostbyname
from socket import gethostname

class SocketServer:
  def __init__(self, port):
    self.sock = socket(AF_INET, SOCK_STREAM)
    self.port = port
  def listen(self, data):
    self.sock.bind(("127.0.0.1", self.port))
    self.sock.listen(len(data))
    while data:
      s = self.sock.accept()[0]
      siz, dat = data.pop()
      s.send(siz)
      s.send(dat)
      s.close()

class Socket:
  def __init__(self, host, port):
    self.sock = socket(AF_INET, SOCK_STREAM)
    self.sock.connect((host, port))
  def recv(self, size):
    return self.sock.recv(size)

pack.py

#http://stackoverflow.com/questions/6234586/we-need-to-pickle-any-sort-of-callable
from marshal import dumps as marshal_dumps
from pickle import dumps as pickle_dumps
from struct import pack as struct_pack

class packer:
  def __init__(self):
    self.f = []
  def pack(self, what):
    if type(what) is type(lambda:None):
      self.f = []
      self.f.append(marshal_dumps(what.func_code))
      self.f.append(pickle_dumps(what.func_name))
      self.f.append(pickle_dumps(what.func_defaults))
      self.f.append(pickle_dumps(what.func_closure))
      self.f = pickle_dumps(self.f)
      return (struct_pack('Q', len(self.f)), self.f)

unpack.py

from types import FunctionType
from pickle import loads as pickle_loads
from marshal import loads as marshal_loads
from struct import unpack as struct_unpack
from struct import calcsize

#http://stackoverflow.com/questions/6234586/we-need-to-pickle-any-sort-of-callable

class unpacker:
  def __init__(self):
    self.f = []
    self.fcompiled = lambda:None
    self.sizeofsize = calcsize('Q')
  def unpack(self, sock):
    size = struct_unpack('Q', sock.recv(self.sizeofsize))[0]
    self.f = pickle_loads(sock.recv(size))
    a = marshal_loads(self.f[0])
    b = globals() ##
    c = pickle_loads(self.f[1])
    d = pickle_loads(self.f[2])
    e = pickle_loads(self.f[3])
    self.fcompiled = FunctionType(a, b, c, d, e)
    return self.fcompiled

test.py

from unpack import unpacker
from pack import packer
from sock import SocketServer
from sock import Socket
from threading import Thread
from time import sleep

count = 2
port = 4446

def f():
  print 42

def server():
  ss = SocketServer(port)
  pack = packer()
  functions = [pack.pack(f) for nothing in range(count)]
  ss.listen(functions)

if __name__ == "__main__":
  Thread(target=server).start()
  sleep(1)
  unpack = unpacker()
  for nothing in range(count):
    print unpack.unpack(Socket("127.0.0.1", port))

output:

<function f at 0x12917d0>
<function f at 0x12915f0>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

玩心态 2024-11-18 04:57:35

我不认为 Process 对象被设计为通过网络发送。查看 multiprocessing/process.py 中的第 256 行。

# We subclass bytes to avoid accidental transmission of auth keys over network.

听起来我有一个很好的理由。如果您想做分布式计算,也许您应该查看为此设计的库

I don't think Process objects are designed to be sent over the network. Look at line 256 in multiprocessing/process.py.

# We subclass bytes to avoid accidental transmission of auth keys over network.

Sounds like there's a good reason to me. If you want to do distributed computing, maybe you should look into a library designed for that.

烦人精 2024-11-18 04:57:35

当 pickle 损坏时,会引发 ValueError: insecure string pickle 。您确定您正在一个 sock.recv() (unpack.py) 中接收整个 pickle 对象吗?

编辑:为了避免这种情况发生在您可以做的任何大小(您的 Socket 类必须支持使用缓冲区大小参数(即

 class Socket:
    def recv(self, bufsize):
        return self.sock.recv(bufsize)

)调用recv):

import struct

struct.pack('Q', len(pickled_list))
# Send it, and then send the pickled list.

在接收器程序中:

import struct

length = struct.unpack('Q', sock.recv(struct.calcsize('Q')))[0]
pickled_list = sock.recv(length)

“Q”是一个无符号长长。对于其他结构体,请参阅 结构模块文档

ValueError: insecure string pickle is raised when your pickle is corrupted. Are you sure you are receiving the entire pickled object in one sock.recv() (unpack.py)?

Edit: to avoid this for any size you could do (your Socket class would have to support recv to be called with an buffer size argument (i.e

 class Socket:
    def recv(self, bufsize):
        return self.sock.recv(bufsize)

)):

import struct

struct.pack('Q', len(pickled_list))
# Send it, and then send the pickled list.

In the receiver program:

import struct

length = struct.unpack('Q', sock.recv(struct.calcsize('Q')))[0]
pickled_list = sock.recv(length)

'Q' is an unsigned long long. For other struct things see the struct module documentation

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文