forked from Kitware/VTK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
upload.py
78 lines (61 loc) · 2.41 KB
/
upload.py
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
r"""
This module provides a server side mechanism to support uploading files
to the server.
$ python file_upload_handler.py --upload-directory .../path-to-upload-directory --upload-port port
--upload-directory
Path to directory where uploaded files should go. If this argument is not
specified, then uploaded files will end up in the directory from which python
is run.
--port
Port on which upload server should listen.
"""
# import os to concatenate paths in a system independent way
import os
# import twisted as the webserver
from twisted.web.server import Site
from twisted.web.resource import Resource
from twisted.internet import reactor
# import to process command line arguments
try:
import argparse
except ImportError:
# since Python 2.6 and earlier don't have argparse, we simply provide
# the source for the same as _argparse and we use it instead.
import _argparse as argparse
def add_arguments(parser) :
"""
Extract arguments needed by the upload server.
--upload-directory => Full path to location where files should be uploaded
"""
parser.add_argument("--upload-directory",
default=os.getcwd(),
help="path to root upload directory",
dest="uploadPath")
class UploadPage(Resource) :
isLeaf = True
uploadDirectory = os.getcwd()
def __init__(self, uploadDir) :
self.uploadDirectory = uploadDir
Resource.__init__(self)
def render_POST(self, request):
for key in request.args :
filename = os.path.join(self.uploadDirectory, key)
with open(filename, 'w') as nfd:
for lineText in request.args[key] :
nfd.write(lineText)
request.setHeader('Access-Control-Allow-Origin', '*')
return '<html><body>Your post was received</body></html>'
if __name__ == "__main__":
# Create argument parser
parser = argparse.ArgumentParser(description="File Upload Server")
add_arguments(parser)
parser.add_argument("--port",
default=8081,
help="port for upload server to listen on",
dest="port")
args = parser.parse_args()
# Now start the twisted server
resource = UploadPage(args.uploadPath)
factory = Site(resource)
reactor.listenTCP(args.port, factory)
reactor.run()