-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrestful_lib.py
executable file
·168 lines (139 loc) · 6.97 KB
/
restful_lib.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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
"""
Copyright (C) 2008 Benjamin O'Steen
This file is part of python-fedoracommons.
python-fedoracommons is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
python-fedoracommons is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with python-fedoracommons. If not, see <http://www.gnu.org/licenses/>.
"""
__license__ = 'GPL http://www.gnu.org/licenses/gpl.txt'
__author__ = "Benjamin O'Steen <[email protected]>"
__version__ = '0.1'
import httplib2
import urllib
import base64
from base64 import encodestring
import mimetypes
import io
class ConnectionError(Exception):
def __str__(self):
return "Connection failed"
class mimeTypes(object):
def getDictionary(self):
mimetype_to_extension = {}
extension_to_mimetype = {}
mimetype_to_extension['text/plain'] = 'txt'
mimetype_to_extension['text/xml'] = 'xml'
mimetype_to_extension['text/css'] = 'css'
mimetype_to_extension['text/javascript'] = 'js'
mimetype_to_extension['text/rtf'] = 'rtf'
mimetype_to_extension['text/calendar'] = 'ics'
mimetype_to_extension['application/msword'] = 'doc'
mimetype_to_extension['application/msexcel'] = 'xls'
mimetype_to_extension['application/x-msword'] = 'doc'
mimetype_to_extension['application/vnd.ms-excel'] = 'xls'
mimetype_to_extension['application/vnd.ms-powerpoint'] = 'ppt'
mimetype_to_extension['application/pdf'] = 'pdf'
mimetype_to_extension['text/comma-separated-values'] = 'csv'
mimetype_to_extension['image/jpeg'] = 'jpg'
mimetype_to_extension['image/gif'] = 'gif'
mimetype_to_extension['image/jpg'] = 'jpg'
mimetype_to_extension['image/tiff'] = 'tiff'
mimetype_to_extension['image/png'] = 'png'
# And hacky reverse lookups
for mimetype in mimetype_to_extension:
extension_to_mimetype[mimetype_to_extension[mimetype]] = mimetype
mimetype_extension_mapping = {}
mimetype_extension_mapping.update(mimetype_to_extension)
mimetype_extension_mapping.update(extension_to_mimetype)
return mimetype_extension_mapping
class Connection:
def __init__(self, base_url, username=None, password=None):
self.base_url = base_url
self.username = username
m = mimeTypes()
self.mimetypes = m.getDictionary()
self.url = urllib.parse.urlparse(base_url)
(scheme, netloc, path, query, fragment) = urllib.parse.urlsplit(base_url)
self.scheme = scheme
self.host = netloc
self.path = path
# Create Http class with support for Digest HTTP Authentication, if necessary
self.h = httplib2.Http(".cache")
self.h.follow_all_redirects = True
if username and password:
self.h.add_credentials(username, password)
def request_get(self, resource, args = None, headers={}):
return self.request(resource, "get", args, headers=headers)
def request_delete(self, resource, args = None, headers={}):
return self.request(resource, "delete", args, headers=headers)
def request_head(self, resource, args = None, headers={}):
return self.request(resource, "head", args, headers=headers)
def request_post(self, resource, args = None, body = None, filename=None, headers={}):
return self.request(resource, "post", args , body = body, filename=filename, headers=headers)
def request_put(self, resource, args = None, body = None, filename=None, headers={}):
return self.request(resource, "put", args , body = body, filename=filename, headers=headers)
def get_content_type(self, filename):
extension = filename.split('.')[-1]
guessed_mimetype = self.mimetypes.get(extension, mimetypes.guess_type(filename)[0])
return guessed_mimetype or 'application/octet-stream'
def request(self, resource, method = "get", args = None, body = None, filename=None, headers={}):
params = None
path = resource
headers['User-Agent'] = 'Basic Agent'
BOUNDARY = u'00hoYUXOnLD5RQ8SKGYVgLLt64jejnMwtO7q8XE1'
CRLF = u'\r\n'
if filename and body:
#fn = open(filename ,'r')
#chunks = fn.read()
#fn.close()
# Attempt to find the Mimetype
content_type = self.get_content_type(filename)
headers['Content-Type']='multipart/form-data; boundary='+BOUNDARY
encode_string = io.StringIO()
encode_string.write(CRLF)
encode_string.write(u'--' + BOUNDARY + CRLF)
encode_string.write(u'Content-Disposition: form-data; name="file"; filename="%s"' % filename)
encode_string.write(CRLF)
encode_string.write(u'Content-Type: %s' % content_type + CRLF)
encode_string.write(CRLF)
encode_string.write(body)
encode_string.write(CRLF)
encode_string.write(u'--' + BOUNDARY + u'--' + CRLF)
body = encode_string.getvalue()
headers['Content-Length'] = str(len(body))
print (type(headers['Content-Length']))
elif body:
if not headers.get('Content-Type', None):
headers['Content-Type']='text/xml'
headers['Content-Length'] = str(len(body))
else:
if ('Content-Length') in headers:
del headers['Content-Length']
headers['Content-Type']='text/plain'
if args:
if method in ("get", 'delete'):
path += u"?" + urllib.parse.urlencode(args)
elif method == "put" or method == "post":
headers['Content-Type']='application/x-www-form-urlencoded'
body = urllib.parse.urlencode(args)
request_path = []
# Normalise the / in the url path
if self.path != "/":
if self.path.endswith('/'):
request_path.append(self.path[:-1])
else:
request_path.append(self.path)
if path.startswith('/'):
request_path.append(path[1:])
else:
request_path.append(path)
resp, content = self.h.request(u"%s://%s%s" % (self.scheme, self.host, u'/'.join(request_path)), method.upper(), body=body, headers=headers )
# TODO trust the return encoding type in the decode?
return {u'headers':resp, u'body':content.decode('UTF-8')}