| 1 | #!/usr/bin/python |
|---|
| 2 | |
|---|
| 3 | # a test for demonstration using Sketch Engine through json interface |
|---|
| 4 | |
|---|
| 5 | import urllib, urllib2, base64 |
|---|
| 6 | import simplejson |
|---|
| 7 | |
|---|
| 8 | usr = '<username>' |
|---|
| 9 | passwd = '<password>' |
|---|
| 10 | |
|---|
| 11 | base_url = 'http://localhost/auth/run.cgi/' |
|---|
| 12 | method = 'wordlist' |
|---|
| 13 | |
|---|
| 14 | # creating query string |
|---|
| 15 | attrs = dict(corpname='bnc', wlattr='word', wlpat='test.*', |
|---|
| 16 | format='json') |
|---|
| 17 | encoded_attrs = urllib.quote(simplejson.JSONEncoder().encode(attrs)) |
|---|
| 18 | url = base_url + method + '?json=%s' % encoded_attrs |
|---|
| 19 | |
|---|
| 20 | request = urllib2.Request(url) |
|---|
| 21 | |
|---|
| 22 | # authentication |
|---|
| 23 | base64string = base64.encodestring('%s:%s' % (usr, passwd))[:-1] |
|---|
| 24 | request.add_header("Authorization", "Basic %s" % base64string) |
|---|
| 25 | |
|---|
| 26 | # json data receiving |
|---|
| 27 | file = urllib2.urlopen(request) |
|---|
| 28 | data = file.read() |
|---|
| 29 | file.close() |
|---|
| 30 | |
|---|
| 31 | # now, in the 'data' variable, there is a json string that can be parsed |
|---|
| 32 | # for json syntax (e.g. by simplejson) |
|---|
| 33 | json_obj = simplejson.loads(data) |
|---|
| 34 | print simplejson.dumps(json_obj, sort_keys=True, indent=3) |
|---|
| 35 | |
|---|