Skip to content

Instantly share code, notes, and snippets.

@3kwa
Created September 1, 2011 08:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 3kwa/1185683 to your computer and use it in GitHub Desktop.
Save 3kwa/1185683 to your computer and use it in GitHub Desktop.
Various ways to use template with CherryPy
"""
experimenting with templates (pystache but could be any other) and cherrypy
reading http://streamhacker.com/2011/08/27/python-3-web-development-review/
annoyed the crap out of me!
hence let's illustrate some of the many ways to graft templates on the cherry
tree ... pistachio:
+ string interpolation PHP-esque?
+ serve_template helper called when returning from controller
+ render_decorator cause view and controller should be orthognal
+ cherry_tool cause it is cherrypy but ...
every exposed method of the App class builds a 'context' dictionary
{'body' : 'OK'}
the mustache templates are saved in a view folder (in a more serious context
I would probably use cherrypy.request.script_name as subfolders)
using requests http://pypi.python.org/pypi/requests to (doc)test
>>> import requests
mounting the application and starting the engine (setup)
>>> cherrypy.log.screen = False
>>> application = cherrypy.tree.mount(App())
>>> cherrypy.engine.start()
>>> get = lambda handler: requests.get("http://localhost:8080/%s" % handler).content
>>> get('')
'index: OK'
>>> get('render_template')
'render_template: OK\\n'
pystache is adding a EOL ... prints pretty :P
>>> get('decorator')
'decorator: OK\\n'
>>> get('tool')
'tool: OK\\n'
teardown
>>> cherrypy.engine.exit()
"""
import os
import cherrypy
import pystache
def load_template(template_name):
"""
load template_name.mustache from view
"""
mustache = os.path.join('view', "%s.mustache" % template_name)
with open(mustache) as f:
template = f.read()
return template
def render_template(template_name, context):
"""
open template_name and render using context
"""
template = load_template(template_name)
return pystache.render(template, context)
def render_decorator(handler):
"""
wrap the handler in a call to render the relevant template following the
railesque convention template_name = handlet.__name__
"""
def wrap(*args, **kvargs):
return render_template(handler.__name__, handler(*args, **kvargs))
return wrap
def my_tool():
"""
a custom tool designed to be used once a response is available
"""
template_name = cherrypy.request.path_info[1:]
data = cherrypy.response.body
cherrypy.response.body = render_template(template_name, dict(data))
cherrypy.tools.pystache = cherrypy.Tool('before_finalize', my_tool)
class App(object):
@cherrypy.expose
def index(self):
"""
old school string interpolation
"""
return "index: %(body)s" % {'body' : 'OK'}
@cherrypy.expose
def render_template(self):
"""
a classic return serve_template
"""
return render_template('render_template', {'body' : 'OK'})
@cherrypy.expose
@render_decorator
def decorator(self):
"""
a new school render_decorator (my favorite)
"""
return {'body' : 'OK'}
@cherrypy.expose
@cherrypy.tools.pystache()
def tool(self):
"""
A CP tool, a thing of beauty (if a tad complex)
Returning a dict without calling the pystache tool would respond 'body'
because of the way encode_string in encoding.py works ('OK' is lost)
Trying to render 'body' using the tool would fail, it expects a dict.
Returning an itemize dict fails without the tool (a tuple is not a string)
but succeed with the tool when calling dict before rendering.
I am in pdb bliss :P
"""
return {'body' : 'OK'}.items()
application = cherrypy.tree.mount(App(), '')
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=False)
@mayurpatil1211
Copy link

hi, Can you solve my problem?
I want to render json to a template, i am not getting. If its flask then i can.

import requests
import redis
import json
import cherrypy
import jinja2

import threading

def background():
	import time
 
# Wait for 5 seconds

	while  True:

		time.sleep(300)
		print ("Getting Data")
		
		requests.get("http://127.0.0.1:8080")
		
threading.Thread(target=background).start()


class HelloWorld(object):
		@cherrypy.expose	
		def index(self):
				
				status = self.getData()
				return status


		def getData(self):
				conn = redis.Redis('localhost')
				self.conn = conn
				topGainers = requests.get("https://www.nseindia.com/live_market/dynaContent/live_analysis/gainers/niftyGainers1.json")

				topLosers = requests.get("https://www.nseindia.com/live_market/dynaContent/live_analysis/losers/niftyLosers1.json")

				

				print(json.loads(topLosers.text))
				topLosers = json.loads(topLosers.text)
				topGainers = json.loads(topGainers.text)

				conn.hmset("topGainers", topGainers)

				conn.hmset("topLosers", topLosers)

				return topLosers
		@cherrypy.expose
		def displayData(self):
				conn = redis.Redis('localhost')
				topLosers = conn.hgetall("topLosers")
				topGainers = conn.hgetall("topGainers")



				print (topGainers)
				
				return "topGainers %r, topLosers %r." % (topGainers, topLosers)
		index.exposed = True




_cp_config={
    'global':{
        'server.socket_host'  : '0.0.0.0',
        'server.socket_port'  : 1919,
    },
}

if __name__ == '__main__':
	cherrypy.quickstart(HelloWorld())


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment