1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
#! /usr/bin/env python
# A server version of hammie.py
"""Usage: %(program)s [options] IP:PORT
Where:
-h
show usage and exit
-p FILE
use pickle FILE as the persistent store. loads data from this file
if it exists, and saves data to this file at the end.
-d FILE
use DBM store FILE as the persistent store.
-o section:option:value
set [section, option] in the options database to value
IP
IP address to bind (use 0.0.0.0 to listen on all IPs of this machine)
PORT
Port number to listen to.
"""
import os
import getopt
import sys
import traceback
import xmlrpclib
import SimpleXMLRPCServer
from spambayes import hammie, Options
from spambayes import storage
try:
True, False
except NameError:
# Maintain compatibility with Python 2.2
True, False = 1, 0
class ReusableSimpleXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer):
allow_reuse_address = True
program = sys.argv[0] # For usage(); referenced by docstring above
class XMLHammie(hammie.Hammie):
def score(self, msg, *extra):
try:
msg = msg.data
except AttributeError:
pass
return hammie.Hammie.score(self, msg, *extra)
def filter(self, msg, *extra):
try:
msg = msg.data
except AttributeError:
pass
return xmlrpclib.Binary(hammie.Hammie.filter(self, msg, *extra))
def usage(code, msg=''):
"""Print usage message and sys.exit(code)."""
if msg:
print >> sys.stderr, msg
print >> sys.stderr
print >> sys.stderr, __doc__
sys.exit(code)
def main():
"""Main program; parse options and go."""
try:
opts, args = getopt.getopt(sys.argv[1:], 'hd:p:o:')
except getopt.error, msg:
usage(2, msg)
options = Options.options
for opt, arg in opts:
if opt == '-h':
usage(0)
elif opt == '-o':
options.set_from_cmdline(arg, sys.stderr)
dbname, usedb = storage.database_type(opts)
if len(args) != 1:
usage(2, "IP:PORT not specified")
ip, port = args[0].split(":")
port = int(port)
bayes = storage.open_storage(dbname, usedb)
h = XMLHammie(bayes)
server = ReusableSimpleXMLRPCServer(
(ip, port),
SimpleXMLRPCServer.SimpleXMLRPCRequestHandler)
server.register_instance(h)
server.serve_forever()
if __name__ == "__main__":
main()
|