-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPyWolf.py
More file actions
68 lines (59 loc) · 2.62 KB
/
PyWolf.py
File metadata and controls
68 lines (59 loc) · 2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import cherrypy
import os
import sys
import urllib
import urllib2
import xml.etree.ElementTree as eT
from xml.sax.saxutils import unescape
reload(sys)
sys.setdefaultencoding('UTF8')
class PyWolf(object):
def __init__(self):
self.AppId = '' # Please define your own API Id. You can get one for free at Wolfram|Alpha.
self.PodState = '*Step-by-step solution'
self.Start = self.hunescape('<!DOCTYPE html><html lang="en"><head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>PyWolf - A Python Wolfram|Alpha Query Service</title> <link href="/static/img/favicon.ico" rel="shortcut icon" type="image/x-icon" /></head><body style="text-align: center;">')
self.End = self.hunescape('</body></html>')
@cherrypy.expose
def index(self):
return open('public_html/index.html', 'rb')
@cherrypy.expose
def query(self, input=None):
xml = self.getXML(input)
return self.Start + self.writeHTML(xml)
def getXML(self, input):
BaseURL = 'http://api.wolframalpha.com/v2/query?'
URLParams = {'input': input, 'appid': self.AppId, 'podstate': self.PodState}
Params = urllib.urlencode(URLParams)
Headers = {'User-Agent': None}
req = urllib2.Request(BaseURL, Params, Headers)
return urllib2.urlopen(req).read()
def writeHTML(self, xml):
html = ''
tree = eT.fromstring(xml)
for pod in tree.iter('pod'):
html += '<h2>' + pod.get('title') + '</h2>\n'
for img in pod.iter('img'):
html += '<img src=\"' + img.get('src') + '\" ' + 'alt=\"' + img.get('alt') + '\" />' + '\n'
return html
def hunescape(self, text):
table = {
""": '"',
"'": "'"
}
return unescape(text, table)
if __name__ == '__main__':
conf = {
'global': {
'server.socket_host': '0.0.0.0',
'server.socket_port': 8080
},
'/': {
'tools.sessions.on': True,
'tools.staticdir.root': os.path.abspath(os.getcwd())
},
'/static': {
'tools.staticdir.on': True,
'tools.staticdir.dir': './public_html'
}
}
cherrypy.quickstart(PyWolf(), "/", conf)