Hi, I am trying to come up with a script that uploads a file to a given review request. This is the first script I am trying to write with the review board web apis. Kindly bear with me if it something very trivial/silly. I am sure it's something out of my ignorance but I am not able to find out the solution at the moment.
Below is the output of the script: [gyasingh@bhlbtr02 ~]$ python ~/scripts/upload_file_to_rb.py 978 #978 is the review request number [gyasingh@bhlbtr02 ~]$ python ~/scripts/upload_file_to_rb.py 978 DEBUG - Establishing connection DEBUG - path: --10.158.224.153.61349470.2151.1325586785.854.1 Content-Disposition: form-data; name="/home/gyasingh/d.txt"; filename="/home/gyasingh/d.txt" My first restfull scriupt. --10.158.224.153.61349470.2151.1325586785.854.1-- DEBUG - request body: caption=Klocwork report file&path=--10.158.224.153.61349470.2151.1325586785.854.1 Content-Disposition: form-data; name="/home/gyasingh/d.txt"; filename="/home/gyasingh/d.txt" My first restfull scriupt. --10.158.224.153.61349470.2151.1325586785.854.1-- DEBUG - resource: /review-requests/978/draft/file-attachments/ {u'body': u'{"fields": {"path": ["This field is required"], " name": ["Field is not supported"], " filename": ["Field is not supported"]}, "stat": "fail", "err": {"msg": "One or more fields had errors", "code": 105}}', u'headers': {'status': '400', 'content-length': '204', 'content-language': 'en-us', 'set-cookie': 'rbsessionid=fadc4a7dbcb80890e7df8233f7cb32f8; expires=Wed, 02- Jan-2013 10:33:05 GMT; Max-Age=31536000; Path=/;', 'expires': 'Tue, 03 Jan 2012 10:33:05 GMT', 'vary': 'Accept, Cookie, Accept-Language', 'server': 'lighttpd/1.4.28', 'last-modified': 'Tue, 03 Jan 2012 10:33:05 GMT', 'cache-control': 'max-age=0', 'date': 'Tue, 03 Jan 2012 10:33:05 GMT', 'content-type': 'application/json'}} Traceback (most recent call last): File "/home/gyasingh/scripts/upload_file_to_rb.py", line 173, in ? main() File "/home/gyasingh/scripts/upload_file_to_rb.py", line 169, in main upload_file(review_request_num) File "/home/gyasingh/scripts/upload_file_to_rb.py", line 122, in upload_file response = json.loads(response["body"]) NameError: global name 'json' is not defined [gyasingh@bhlbtr02 ~]$ ----------------------------------------------------- Source------------------------------------------------------------------------- #!/usr/bin/python -W ignore::DeprecationWarning try: from json import loads as json_loads except ImportError: from simplejson import loads as json_loads import logging import sys import os import urllib import urlparse import mimetools from restful_lib import Connection #from rest_client import Connection #from future import with_statement # Basic constants REVIEWBOARD_URL = "http://10.158.224.153:20880/"; DEFAULT_LEVEL = logging.DEBUG def setup_logger(): """Setup a logging instance to be used for error reporting.""" logger = logging.getLogger("reviewboard") handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter("%(levelname)s - %(message)s") handler.setFormatter(formatter) logger.addHandler(handler) def read_credentials(): """Read username and password from a file. The file should contain a single line in the form "username:password". Return: A (username, password) tuple. """ credential_file = os.getenv('HOME') + "/reviewboard-credentials" handle = open(credential_file, 'r') credentials = handle.readline().strip() username, password = credentials.split(":") handle.close() return username, password def encode_multipart_formdata(fields, files): """ Encodes data for use in an HTTP POST. """ BOUNDARY = mimetools.choose_boundary() content = "" fields = fields or {} files = files or {} for key in fields: content += "--" + BOUNDARY + "\r\n" content += "Content-Disposition: form-data; name=\"%s\"\r\n" % key content += "\r\n" content += str(fields[key]) + "\r\n" for key in files: filename = files[key]['filename'] value = files[key]['content'] content += "--" + BOUNDARY + "\r\n" content += "Content-Disposition: form-data; name=\"%s\"; " % key content += "filename=\"%s\"\r\n" % filename content += "\r\n" content += value + "\r\n" content += "--" + BOUNDARY + "--\r\n" content += "\r\n" content_type = "multipart/form-data; boundary=%s" % BOUNDARY return content_type, content def upload_file(review_request_num): """ Upload a new text file to a given review request """ reviewboard_url = urlparse.urljoin(REVIEWBOARD_URL, "api") username, password = read_credentials() logger = logging.getLogger("reviewboard") logger.setLevel(DEFAULT_LEVEL) logger.debug("Establishing connection") connection = Connection(reviewboard_url, username=username, password=password) fields = {} # read the klocwork report file fp = open(os.path.join("/home/gyasingh/", "d.txt"), 'r') file_content = fp.read() fp.close() file_to_be_uploaded = "/home/gyasingh/d.txt" files = {} files[file_to_be_uploaded] = { 'filename': file_to_be_uploaded, 'content': file_content } content_type, multipart_content = encode_multipart_formdata(fields, files) caption = "Klocwork report file" path = multipart_content logger.debug("path: %s" % path) request_body = "caption=%s&path=%s" % (caption, path) logger.debug("request body: %s" % request_body) resource = "/review-requests/%s/draft/file-attachments/" % review_request_num logger.debug("resource: %s" % resource) response = connection.request_post(resource, body="%s" % request_body) try: print response response = json.loads(response["body"]) except ValueError: logging.critical("Malformed response received from Reviewboard." " Contact the KDE sysadmins.") return if response["stat"] != "ok": logger.error("An error occurred while accessing Reviewboard.") logger.error(response["err"]["msg"]) return logger.debug("Sending status") response = connection.request_put(submit_resource, body="status=submitted") try: response = json.loads(response["body"]) except ValueError: logging.critical("Malformed response received from Reviewboard." " Contact the KDE sysadmins.") return if response["stat"] != "ok": logger.error("An error occurred while accessing Reviewboard.") logger.error(response["err"]["msg"]) return logger.info("Review request %s successfully closed." % review_id) def usage(): print "Usage: upload_file <name>" sys.exit(0) def main(): setup_logger() if len(sys.argv) != 2: logger = logging.getLogger("reviewboard") logger.setLevel(DEFAULT_LEVEL) # Only output information when we're using debug logger.debug(sys.argv) usage() review_request_num = sys.argv[1] upload_file(review_request_num) sys.exit(0) if __name__ == '__main__': main() -- Want to help the Review Board project? Donate today at http://www.reviewboard.org/donate/ Happy user? Let us know at http://www.reviewboard.org/users/ -~----------~----~----~----~------~----~------~--~--- To unsubscribe from this group, send email to reviewboard+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/reviewboard?hl=en