Python file sharing with XML-RPC

Source: Internet
Author: User

1. directory structure

|__ Config. ini

|__ P2PClinet. py

|__ P2PServer. py

|__ Url.txt

2. File Content

Config. ini

1
[SERVER_INFO]
2
PORT = server PORT number
3
DIRECTORY = path to the shared folder
4
URL_FILE = url.txt
P2PClinet. py
001
'''
002
Created on 2012-7-21
003
 
004
Author: Jeff_Yu
005
'''
006
 
007
From xmlrpclib import ServerProxy, Fault
008
From cmd import Cmd, PROMPT
009
From random import choice
010
From string import lower, lowercase
011
From P2PServer import Node, UNHANDLED
012
From threading import Thread
013
From time import sleep
014
Import sys, ConfigParser, socket
015
 
016
HEAD_START = 0.1 # seconds
017
SECRET_LENGTH = 100
018
 
019
 
020
Def randomString (length ):
021
"Return the random string by given length """
022

023
Chars = []
024
Letters = lowercase [: 26]
025
While length> 0:
026
Length-= 1
027
Chars. append (choice (letters ))
028

029
Return ''. join (chars)
030
 
031
Class Client (Cmd ):
032

033
Prompt = '>'
034

035
Def _ init _ (self, url, dirname, urlfile ):
036

037
Cmd. _ init _ (self)
038
Self. secret = randomString (SECRET_LENGTH)
039
N = Node (url, dirname, self. secret)
040
T = Thread (target = n. _ start)
041
T. setDaemon (1)
042
T. start ()
043
Sleep (HEAD_START)
044
Self. server = ServerProxy (url)
045
For line in open (urlfile ):
046
Line = line. strip ()
047
Self. server. hello (line)
048

049
 
050
Def do_fetch (self, arg ):
051

052
Try:
053
Self. server. fetch (arg, self. secret)
054
Failed t Fault, f:
055
If f. faultCode! = UNHANDLED: raise
056
Print "Couldn't find the file", arg
057

058
Def do_exit (self, arg ):
059

060
Print
061
Sys. exit ()
062

063
Do_EOF = do_exit
064
 
065
Class MyConfigParser:
066

067
Def _ init _ (self, urlfile ):
068

069
Self. urlfile = urlfile
070

071
Try:
072
F = open (self. urlfile, "r ")
073
Handle t IOError:
074
Meg = "file % s is not found in the path> % s" % (self. urlfile, OS. path. abspath ('.'))
075
Return (0, meg)
076
 
077
Self. config = ConfigParser. ConfigParser ()
078
Self. config. readfp (f)
079

080
F. close ()
081
 
082
 
083
Def getValueFromcfig (self, section, filed ):
084
 
085
Try:
086
Value = self. config. get (section, filed)
087
Failed t ConfigParser. NoOptionError:
088
Meg = "% s is not found in file % s, under section %." % (filed, self. urlfile, section)
089
Return (0, meg)
090

091
Return (1, value)
092

093

094
 
095
Def main ():
096

097
Configfile = "config. ini"
098
Cfig = MyConfigParser (configfile)
099
 
100
# Get port
101
Res = cfig. getValueFromcfig ("SERVER_INFO", 'Port ')
102
If (res [0] = 0 ):
103
Print res [1]
104
Raw_input ()
105
Sys. exit ()
106
Else:
107
Port = res [1]
108

109
# Get directory
110
Res = cfig. getValueFromcfig ("SERVER_INFO", 'directory ')
111
If (res [0] = 0 ):
112
Print res [1]
113
Raw_input ()
114
Sys. exit ()
115
Else:
116
Directory = res [1]
117

118
# Get urlfile
119
Res = cfig. getValueFromcfig ("SERVER_INFO", 'url _ file ')
120
If (res [0] = 0 ):
121
Print res [1]
122
Raw_input ()
123
Sys. exit ()
124
Else:
125
Urlfile = res [1]
126

127
Url = "http: // % s: % s" % (socket. gethostname (), port)
128

129
Print "You URL is % s, you can introduce it to your friend." % url
130

131
Client = Client (url, directory, urlfile)
132
Client. nested loop ()
133

134
If _ name _ = '_ main _': main ()
P2PServer. py

001
'''
002
Created on 2012-7-21
003
 
004
Author: Jeff_Yu
005
'''
006
 
007
From xmlrpclib import ServerProxy, Fault
008
From OS. path import join, isfile, abspath
009
From SimpleXMLRPCServer import SimpleXMLRPCServer
010
From urlparse import urlparse
011
Import sys
012
 
013
 
014
SimpleXMLRPCServer. allow_reuse_address = 1
015
 
016
MAX_HISTORY_LENGTH = 6
017
 
018
UNHANDLED = 100
019
ACCESS_DENIED = 200
020
 
021
Class UnhandledQuery (Fault ):
022
"""
023
Unable to handle the query
024
"""
025

026
Def _ init _ (self, message = "Couldn't handle the query "):
027
Fault. _ init _ (self, UNHANDLED, message)
028

029
 
030
Class AccessDenied (Fault ):
031
"""
032
Access denied
033
"""
034
Def _ init _ (self, message = "Access denied "):
035
Fault. _ init _ (self, ACCESS_DENIED, message)
036
 
037
 
038
Def inside (dir, name ):
039
"""
040
Check whether can find file in the dir
041
"""
042
Dir = abspath (dir)
043
Name = abspath (name)
044
Return name. startswith (join (dir ,''))
045
 
046
 
047
Def getPort (url ):
048
"Get port from URL """
049

050
Name = urlparse (url) [1]
051
Parts = name. split (':')
052
Return int (parts [-1])
053
 
054
 
055
Class Node:
056
"P2P network node """
057

058
Def _ init _ (self, url, dirname, secret ):
059
Self. url = url
060
Self. dirname = dirname
061
Self. secret = secret
062
Self. known = set ()
063

064
Def query (self, query, history = []):
065
"Query the file """
066

067
Try:
068
Return self. _ handle (query)
069
Counter t UnhandledQuery:
070
History = history + [self. url]
071
If len (history)> = MAX_HISTORY_LENGTH: raise
072
Return self. _ broadcast (query, history)
073

074
Def hello (self, other ):
075
"Introduce self """
076

077
Self. known. add (other)
078
Return 0
079

080
Def fetch (self, query, secret ):
081
"Make the node find file and download """
082

083
If secret! = Self. secret: raise AccessDenied
084
Result = self. query (query)
085
F = open (join (self. dirname, query), 'w ')
086
F. write (result)
087
F. close ()
088
Return 0
089
 
090

091
Def _ start (self ):
092
"Start server """
093

094
S = SimpleXMLRPCServer ("", getPort (self. url), logRequests = True, allow_none = True)
095
S. register_instance (self)
096
S. serve_forever ()
097

098
Def _ handle (self, query ):
099

100
Dir = self. dirname
101
Name = join (dir, query)
102
If not isfile (name): raise UnhandledQuery
103
If not inside (dir, name): raise AccessDenied
104
Return open (name). read ()
105

106
Def _ broadcast (self, query, history ):
107
"Used to query other known Node """
108

109
For other in self. known. copy ():
110
If other in history: continue
111

112
Try:
113
S = ServerProxy (other)
114
Return s. query (query, history)
115

116
Failed t Fault, f:
117
If f. faultCode = UNHANDLED: pass
118
Else: self. known. remove (other)
119
Except t:
120
Self. known. remove (other)
121

122
Raise UnhandledQuery
123

124
Def main ():
125
Url, directory, secret = sys. argv [1:]
126
N = Node (url, directory, secret)
127
N. _ start ()
128
Www.2cto.com
129
If _ name _ = '_ main _': main ()
Url.txt

1
Http: // machine name 1: Port 1
2
Http: // machine name 2: Port 2
3
Http: // machine name 3: Port 3
Author: JeffYu

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.