Difference between revisions of "Python Interactive Client"

From Textserver wiki
Jump to: navigation, search
(Created page with "<syntaxhighlight lang="python" line="1" > #! /usr/bin/python ######################################################################## # # Example client to submit an interac...")
 
 
Line 10: Line 10:
 
#
 
#
 
########################################################################
 
########################################################################
 
  
 
# import required libraries
 
# import required libraries

Latest revision as of 13:01, 20 January 2016

 1 #! /usr/bin/python
 2 
 3 ########################################################################
 4 #
 5 #  Example client to submit an interactive request to TextServer 
 6 # SERVICENAME service. 
 7 #  Input may be a plain text or a text file.  No ZIP files.
 8 #  Output will be in the requested format (XML, json, conll)
 9 #
10 ########################################################################
11 
12 # import required libraries
13 import urllib2
14 # You may need to install "poster" python module for these two:
15 from poster.encode import multipart_encode
16 from poster.streaminghttp import register_openers
17 
18 # Register the streaming http handlers with urllib2
19 register_openers()
20 
21 # set query elements
22 text = raw_input('Text to analyze: ')
23 lang = raw_input('Language: ')
24 out = raw_input('Output format (xml,json,conll,naf): ')
25 user = raw_input('TextServer Username: ')
26 pwd = raw_input('TextServer Password: ')
27 
28 # Encode query in a form-data.
29 # 'headers' contains the necessary Content-Type and Content-Length.
30 # 'datagen' is a generator object that yields the encoded parameters.
31 datagen, headers = multipart_encode({'username':user,
32                                      'password':pwd,
33                                      'text_input':text,
34                                      'language':lang,
35                                      'output':out,
36                                      'interactive':'1'
37                                      } )
38 # service URL
39 service = "SERVICENAME"
40 url = "http://frodo.lsi.upc.edu:8080/TextWS/textservlet/ws/processQuery/"+service
41 
42 # Create the Request object
43 request = urllib2.Request(url, datagen, headers)
44 try:
45   # Actually do the request, and get the response
46   resp =  urllib2.urlopen(request).read()
47 
48 except urllib2.HTTPError, e:
49   # handle connection errors
50   print e, "-", e.read()
51   exit()
52 
53 # No error, appropriately process response
54 # (e.g. parsing XML or JSON, and doing clever stuff with the content)
55 print resp