本文整理汇总了Python中Formatter类的典型用法代码示例。如果您正苦于以下问题:Python Formatter类的具体用法?Python Formatter怎么用?Python Formatter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Formatter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get
def get(self,format,id):
#set content-type
self.response.headers['Content-Type'] = Formatter.contentType(format)
#get consumer/client app id
appid = 'Unknown'
if (self.request.GET):
if ('appid' in self.request.GET):
appid = self.request.GET['appid']
if ('app' in self.request.GET):
appid = self.request.GET['app']
referer = ''
if ('HTTP_REFERER' in os.environ):
referer = os.environ['HTTP_REFERER']
returnData = APIContent.getHackerNewsPost(id,format,self.request.url, referer, self.request.remote_addr)
#track this request
GAHelper.trackGARequests('/post/%s' % (id), appid, referer)
if (not returnData):
returnData = ''
#output to the browser
self.response.out.write(Formatter.dataWrapper(format, returnData, self.request.get('callback')))
示例2: main
def main():
f = open('data/person_foaf.n3')
fresnel_data = f.read()
fresnel = Fresnel( fresnel_data )
print "Created Fresnel Graph.."
rdf_graph = Graph()
print "Downloading resource.."
#f = open('data/Tim_Berners-Lee.rdf')
#rdf_graph.parse( file=f, format="xml")
#rdf_graph.parse(source="http://dbpedia.org/page/A._P._J._Abdul_Kalam")
#print "more..."
f = open('data/A._P._J._Abdul_Kalam.rdf')
rdf_graph.parse( file=f, format="xml")
#rdf_graph.parse(source="http://dbpedia.org/page/Tim_Berners-Lee")
for term in rdf_graph:
print term
print "Making selection.."
selector = Selector( fresnel , rdf_graph)
selector.select()
formatter = Formatter( selector )
formatter.format()
data = "<html>\n<head><link rel='stylesheet' type='text/css' href='style.css'></head>\n<body>\n"
for resource in formatter.result:
print resource.render()
data += resource.render()
data += "</body>\n</html>"
f = open('output/test.html', 'w')
f.write(data.encode('utf-8'))
示例3: getDiagnosisICD9Data
def getDiagnosisICD9Data(self,xml,format):
if (xml):
documentElms = xml.getElementsByTagName('entry')
if (documentElms):
#grab two highest ranked content
content1 = ''
content2 = ''
contentNode1 = documentElms[0]
content1 = APIUtils.parseHealthDiagnosisICD9Content(format,contentNode1)
if (len(documentElms) > 0):
contentNode2 = documentElms[1]
content2 = APIUtils.parseHealthDiagnosisICD9Content(format,contentNode2)
returnData = "%s%s" % (content1, content2)
if (format == 'json'):
return returnData[:-1]
else:
return returnData
else:
logging.error('unable to retrieve diagnosis content')
return Formatter.data(format, 'error', 'No results')
else:
logging.error('unable to retrieve diagnosis content')
return Formatter.data(format, 'error', 'Unable to retrieve content from provider')
示例4: getHealthNews
def getHealthNews(lan='en',format='json'):
returnData = MutableString()
returnData = ''
if (lan == 'es'):
dom = minidom.parse(urllib.urlopen(AppConfig.medlinePlusHealthNewsSpanishURL))
else:
dom = minidom.parse(urllib.urlopen(AppConfig.medlinePlusHealthNewsEnglishURL))
rssTitle = MutableString()
rssDescription = MutableString()
rssURL = MutableString()
for node in dom.getElementsByTagName('item'):
for item_node in node.childNodes:
rssTitle = ''
rssDescription = ''
rssURL = ''
#item title
if (item_node.nodeName == "title"):
for text_node in item_node.childNodes:
if (text_node.nodeType == node.TEXT_NODE):
rssTitle += text_node.nodeValue
#description
if (item_node.nodeName == "description"):
for text_node in item_node.childNodes:
rssDescription += text_node.nodeValue
#link to URL
if (item_node.nodeName == "link"):
for text_node in item_node.childNodes:
rssURL += text_node.nodeValue
if (format == 'json'):
startTag = '{'
endTag = '},'
#cleanup
#rssTitle = re.sub("\"", "'", rssTitle)
rssTitle = re.sub("\n", "", rssTitle)
rssTitle = re.sub("\"", "\\\"", rssTitle)
rssDescription = re.sub("\"", "\\\"", rssDescription)
rssDescription = re.sub("\n", "", rssDescription)
rssDescription = re.sub("\t", " ", rssDescription)
rssDescription = re.sub("\r", "", rssDescription)
if (len(rssDescription) > 0):
rssDescription = Formatter.data(format, 'description', escape(rssDescription))[:-1]
else:
startTag = '<record>'
endTag = '</record>'
if (len(rssDescription) > 0):
rssDescription = Formatter.data(format, 'description', escape(rssDescription))
if (len(rssTitle) > 0):
returnData += startTag + Formatter.data(format, 'title', rssTitle)
if (len(rssURL) > 0):
returnData += Formatter.data(format, 'url', rssURL)
if (len(rssDescription) > 0 ):
returnData += rssDescription + endTag
return returnData
示例5: get
def get(self,keyword, state, format='json'):
#set content-type
self.response.headers['Content-Type'] = Formatter.contentType(format)
returnData = MutableString()
returnData = ''
try:
#get XML from the service
state = "%s%s" % ("NA%3AUS%3A", state)
xml = minidom.parse(urllib.urlopen('%s&term=%s&state1=%s' % (AppConfig.clinicalTrialsAPIURL, keyword, state.upper())))
if (xml):
documentElms = xml.getElementsByTagName('clinical_study')
if (documentElms):
for docNode in documentElms:
content = APIUtils.parseClinicalTrialsContent(format,docNode)
returnData += content
else:
logging.error('unable to retrieve content')
self.response.out.write(Formatter.error(format, 'No results'))
return
else:
logging.error('unable to retrieve content')
self.response.out.write(Formatter.error(format, 'Unable to retrieve content from provider'))
return
except Exception, e:
logging.error('GetClinicalTrialsHandler: unable to get health topics or parse XML: %s' % e)
self.response.out.write(Formatter.error(format, 'Exception: %s' % (e)))
return
示例6: constructFromFile
def constructFromFile(self):
self.constructNewBoard()
try:
self.file = FileUtil.openForRead(os.path.join(FileUtil.getProgramDirectory(), "maps", self.mapName + ".battlefield"))
except IOError:
print "Error loading map"
ships = Formatter.stripShips(Formatter.convertMatrix(self.file))
self.board.addShips(ships)
示例7: get
def get(self, format='json'):
#set content-type
self.response.headers['Content-Type'] = Formatter.contentType(format)
returnData = MutableString()
returnData = APIContent.getHackerNewsRSS(format)
referer = ''
if ('HTTP_REFERER' in os.environ):
referer = os.environ['HTTP_REFERER']
#track this request
GAHelper.trackGARequests('/rss', self.request.remote_addr, referer)
#output to the browser
self.response.out.write(Formatter.dataWrapper(format, returnData, self.request.get('callback')))
示例8: post
def post(self):
#set content-type
format = "json"
formatParamName = "format"
if (formatParamName in self.request.params):
format = self.request.params[formatParamName]
self.response.headers['Content-Type'] = Formatter.contentType(format)
#get content
textToTranslate = ""
textParamName = "data"
if (textParamName in self.request.params):
textToTranslate = self.request.params[textParamName]
if (textToTranslate == None or textToTranslate == ''):
logging.error('GetTranslateHandler: invalid parameters')
self.response.out.write(Formatter.error(format, 'Invalid parameters'))
return
#strip tags?
stripTagsParam = "striphtml"
if (stripTagsParam in self.request.params):
if (self.request.params[stripTagsParam] == 'true'):
textToTranslate = CharReplacementMap.remove_html_tags(textToTranslate)
#language
toLanguage = "es"
lanParam = "language"
if (textParamName in self.request.params):
toLanguage = self.request.params[lanParam]
#auto-detect language (blank)
sourceLanguage = ''
params = ({'langpair': '%s|%s' % (sourceLanguage, toLanguage), 'v': '1.0' })
returnData = MutableString()
translatedText = ''
for textToTranslate in self.getSplits(textToTranslate):
params['q'] = textToTranslate
resp = simplejson.load(urllib.urlopen('%s' % (AppConfig.googleTranslateAPIURL), data = urllib.urlencode(params)))
try:
translatedText += resp['responseData']['translatedText']
except Exception, e:
logging.error('GetTranslateHandler: error(s) translating data: %s' % e)
self.response.out.write(Formatter.error(format, 'Exception: %s' % (e)))
return
示例9: get
def get(self, format='json', limit=1):
#set content-type
self.response.headers['Content-Type'] = Formatter.contentType(format)
referer = ''
if ('HTTP_REFERER' in os.environ):
referer = os.environ['HTTP_REFERER']
returnData = APIContent.getHackerNewsLatestContent('', format, self.request.url, referer, self.request.remote_addr, limit)
#track this request
GAHelper.trackGARequests('/latest', self.request.remote_addr, referer)
if (not returnData):
returnData = ''
#output to the browser
self.response.out.write(Formatter.dataWrapper(format, returnData, self.request.get('callback')))
示例10: get
def get(self,format,user):
#set content-type
self.response.headers['Content-Type'] = Formatter.contentType(format)
referer = ''
if ('HTTP_REFERER' in os.environ):
referer = os.environ['HTTP_REFERER']
returnData = APIContent.getHackerNewsSubmittedContent(user,format,self.request.url, referer, self.request.remote_addr)
#track this request
GAHelper.trackGARequests('/submitted/%s' % (user), self.request.remote_addr, referer)
if (not returnData):
returnData = ''
#output to the browser
self.response.out.write(Formatter.dataWrapper(format, returnData))
示例11: get
def get(self, format='json', page=''):
#set content-type
self.response.headers['Content-Type'] = Formatter.contentType(format)
referer = ''
if ('HTTP_REFERER' in os.environ):
referer = os.environ['HTTP_REFERER']
returnData = APIContent.getHackerNewsNewestContent(page, format, self.request.url, referer, self.request.remote_addr)
if (not returnData or returnData == None or returnData == '' or returnData == 'None'):
#call the service again this time without the pageID
returnData = APIContent.getHackerNewsNewestContent('', format, self.request.url, referer, self.request.remote_addr)
#track this request
GAHelper.trackGARequests('/newest', self.request.remote_addr, referer)
#output to the browser
self.response.out.write(Formatter.dataWrapper(format, returnData, self.request.get('callback')))
示例12: man
def man(self, pattern):
"""Call viewer.sh to view man page"""
try:
os.makedirs(Environ.man_dir)
except:
pass
avail = os.listdir(Environ.man_dir)
if not os.path.exists(Environ.index_db):
raise RuntimeError("can't find index.db")
conn = sqlite3.connect(Environ.index_db)
cursor = conn.cursor()
# Try direct match
try:
page_name, url = cursor.execute(
"SELECT name,url FROM CPPMAN WHERE" ' name="%s" ORDER BY LENGTH(name)' % pattern
).fetchone()
except TypeError:
# Try standard library
try:
page_name, url = cursor.execute(
"SELECT name,url FROM CPPMAN" ' WHERE name="std::%s" ORDER BY LENGTH(name)' % pattern
).fetchone()
except TypeError:
try:
page_name, url = cursor.execute(
"SELECT name,url FROM " 'CPPMAN WHERE name LIKE "%%%s%%" ORDER BY LENGTH(name)' % pattern
).fetchone()
except TypeError:
raise RuntimeError("No manual entry for " + pattern)
finally:
conn.close()
page_name = page_name.replace("/", "_")
if page_name + ".3.gz" not in avail or self.forced:
self.cache_man_page(url, page_name)
self.update_mandb()
pager = Environ.pager if sys.stdout.isatty() else Environ.renderer
# Call viewer
pid = os.fork()
if pid == 0:
os.execl(
"/bin/sh",
"/bin/sh",
pager,
Environ.man_dir + page_name + ".3.gz",
str(Formatter.get_width()),
Environ.pager_config,
page_name,
)
return pid
示例13: get
def get(self, format, user):
# set content-type
self.response.headers["Content-Type"] = Formatter.contentType(format)
referer = ""
if "HTTP_REFERER" in os.environ:
referer = os.environ["HTTP_REFERER"]
returnData = APIContent.getHackerNewsSubmittedContent(
user, format, self.request.url, referer, self.request.remote_addr
)
# track this request
GAHelper.trackGARequests("/submitted/%s" % (user), self.request.remote_addr, referer)
if not returnData:
returnData = ""
# output to the browser
self.response.out.write(Formatter.dataWrapper(format, returnData, self.request.get("callback")))
示例14: get
def get(self, format="json", page=""):
# set content-type
self.response.headers["Content-Type"] = Formatter.contentType(format)
referer = ""
if "HTTP_REFERER" in os.environ:
referer = os.environ["HTTP_REFERER"]
returnData = APIContent.getHackerNewsBestContent(
page, format, self.request.url, referer, self.request.remote_addr
)
if not returnData or returnData == None or returnData == "" or returnData == "None":
# call the service again this time without the pageID
returnData = APIContent.getHackerNewsBestContent(
"", format, self.request.url, referer, self.request.remote_addr
)
# track this request
GAHelper.trackGARequests("/best", self.request.remote_addr, referer)
# output to the browser
self.response.out.write(Formatter.dataWrapper(format, returnData))
示例15: man
def man(self, pattern):
"""Call viewer.sh to view man page"""
try:
os.makedirs(Environ.man_dir)
except: pass
avail = os.listdir(Environ.man_dir)
if not os.path.exists(Environ.index_db):
raise RuntimeError("can't find index.db")
conn = sqlite3.connect(Environ.index_db)
cursor = conn.cursor()
# Try direct match
try:
page_name, url = cursor.execute('SELECT name,url FROM CPPMAN WHERE'
' name="%s" ORDER BY LENGTH(name)' % pattern).fetchone()
except TypeError:
# Try standard library
try:
page_name, url = cursor.execute('SELECT name,url FROM CPPMAN'
' WHERE name="std::%s" ORDER BY LENGTH(name)'
% pattern).fetchone()
except TypeError:
try:
page_name, url = cursor.execute('SELECT name,url FROM '
'CPPMAN WHERE name LIKE "%%%s%%" ORDER BY LENGTH(name)'
% pattern).fetchone()
except TypeError:
raise RuntimeError('No manual entry for ' + pattern)
finally:
conn.close()
page_name = page_name.replace('/', '_')
#if page_name + '.3.gz' not in avail or self.forced:
#self.cache_man_page(url, page_name)
#self.update_mandb()
pager = Environ.pager if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() else Environ.renderer
# Call viewer
#pid = os.fork()
#if pid == 0:
#out = os.execl('/bin/sh', '/bin/sh', pager,
#page_name + '.3.gz',
#str(Formatter.get_width()), Environ.pager_config,
#page_name)
p = subprocess.Popen([pager, page_name + '.3.gz', str(Formatter.get_width()), Environ.pager_config, page_name], stdout=subprocess.PIPE)
return {'page':page_name, 'out':p.stdout.read()}