Package restkit :: Module console
[hide private]
[frames] | no frames]

Source Code for Module restkit.console

 1  # -*- coding: utf-8 - 
 2  # 
 3  # This file is part of restkit released under the MIT license.  
 4  # See the NOTICE for more information. 
 5   
 6  import os 
 7  import optparse as op 
 8  import sys 
 9   
10  from restkit import __version__, request 
11   
12  __usage__ = "'%prog [options] url [METHOD] [filename]'" 
13   
14 -def options():
15 """ build command lines options """ 16 return [ 17 op.make_option('-H', '--header', action='append', dest='headers', 18 help='http string header in the form of Key:Value. '+ 19 'For example: "Accept: application/json" '), 20 op.make_option('-i', '--input', action='store', dest='input', 21 metavar='FILE', help='the name of the file to read from'), 22 op.make_option('-o', '--output', action='store', dest='output', 23 help='the name of the file to write to'), 24 op.make_option('--follow-redirect', action='store_false', 25 dest='follow_redirect', default=True) 26 ]
27
28 -def main():
29 """ function to manage restkit command line """ 30 parser = op.OptionParser(usage=__usage__, option_list=options(), 31 version="%prog " + __version__) 32 33 opts, args = parser.parse_args() 34 args_len = len(args) 35 36 if args_len < 1: 37 return parser.error('incorrect number of arguments') 38 39 body = None 40 headers = [] 41 if opts.input: 42 if opts.input == '-': 43 body = sys.stdin.read() 44 headers.append(("Content-Length", str(len(body)))) 45 else: 46 fname = os.path.normpath(os.path.join(os.getcwd(),opts.input)) 47 body = open(fname, 'r') 48 49 if opts.headers: 50 for header in opts.headers: 51 try: 52 k, v = header.split(':') 53 headers.append((k, v)) 54 except ValueError: 55 pass 56 57 try: 58 if args_len == 3: 59 resp = request(args[0], method=args[1], body=body, 60 headers=headers, follow_redirect=opts.follow_redirect) 61 elif len(args) == 2: 62 if args[1] == "-": 63 body = sys.stdin.read() 64 headers.append(("Content-Length", str(len(body)))) 65 66 resp = request(args[0], method=args[1], body=body, 67 headers=headers, follow_redirect=opts.follow_redirect) 68 else: 69 if opts.input: 70 method = 'POST' 71 else: 72 method='GET' 73 resp = request(args[0], method=method, body=body, 74 headers=headers, follow_redirect=opts.follow_redirect) 75 76 if opts.output: 77 f = open(opts.output, 'wb') 78 for block in resp.body_file: 79 f.write(block) 80 f.close() 81 else: 82 print resp.body 83 84 except Exception, e: 85 sys.stderr.write("An error happened: %s" % str(e)) 86 sys.stderr.flush() 87 sys.exit(1) 88 89 sys.exit(0)
90