SkE/Methods/example: example2.py

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