why decorate Jinja2 instances with #webapp2.cached_property - caching

The webapp2 site (http://webapp-improved.appspot.com/api/webapp2_extras/jinja2.html) has a tutorial on how to use webapp2_extras.jinja2, and the code is below.
My question is: why cache the webapp2_extras.jinja2.Jinja2 instance return by return jinja2.get_jinja2(app=self.app)? I checked the code of #webapp2.cached_property and found that it caches the Jinja2 instance in a instance of BaseHandler, which will be destroyed after the request, so why bother to cache it? Did I miss something here?
import webapp2
from webapp2_extras import jinja2
class BaseHandler(webapp2.RequestHandler):
#webapp2.cached_property
def jinja2(self):
# Returns a Jinja2 renderer cached in the app registry.
return jinja2.get_jinja2(app=self.app)
def render_response(self, _template, **context):
# Renders a template and writes the result to the response.
rv = self.jinja2.render_template(_template, **context)
self.response.write(rv)

Here you can find the documentation about cached_property.
The BaseHandler class will be later on called often. My understanding is that to avoid the overhead of calling jinja2.get_jinja2(app=self.app) each time, such reference is evaluated the first time only, and then returned many times later on, i.e. every time a view is called.
To see this happen in code, see this example, where each view is derived from the same BaseHandler class.

Related

Django rest framework question: Using TestCase I'm not understanding using fixtures

I'm confused about factories.
#pytest.fixture
def a_api_request_factory():
return APIRequestFactory()
class TestUserProfileDetailView(TestCase):
def test_create_userprofile(self, up=a_user_profile, rf=a_api_request_factory):
"""creates an APIRequest and uses an instance of UserProfile from a_user_profile to test a view user_detail_view"""
request = rf().get('/api/userprofile/') # the problem line
request.user = up.user
response = userprofile_detail_view(request)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data['user'], up.user.username)
if I take out the parens from rf().get.... then I get
"function doesn't have a get attribute".
If I call it directly then it gives me:
"Fixture "a_api_request_factory" called directly. Fixtures are not
meant to be called directly, but are created automatically when test
functions request them as parameters. See
https://docs.pytest.org/en/stable/fixture.html for more information
about fixtures, and
https://docs.pytest.org/en/stable/deprecations.html#calling-fixtures-directly
about how to update your code."
I do believe I've hit every combination of with or without parens in all relevant locations. Where do the parens go for fixtures?
Or better yet is there a pattern to avoid this type of confusion completely?

Nesting custom resources in chef

I am trying to build a custom resource which would in turn use another of my custom resource as part of its action. The pseudo-code would look something like this
customResource A
property component_id String
action: doSomething do
component_id = 1 if component_id.nil?
node.default[component_details][component_id] = ''
customResource_b "Get me component details" do
comp_id component_id
action :get_component_details
end
Chef::log.info("See the output computed by my customResourceB")
Chef::log.info(node[component_details][component_id])
end
Thing to note:
1. The role of customResource_b is to make a PS call to a REST web service and store the JSON result in node[component_details][component_id] overriding its value. I am creating this attribute node on this resource since I know it will be used later one, hence avoiding compile time issues.
Issues I am facing:
1. When testing a simple recipe that calls this resource in chef-client, the code in the resource gets executed to the last log line and after that the call to customResource_b is made. Which is something I am not expecting to happen.
Any advice would be appreciated. I am also quite new to Chef so any design improvements are also welcome
there is no need to nest chef resources, rather use chef idompotance, guards and notification.
and as usualy, you can always use a condition to decide which cookbook\recipe to run.

Cannot call .Count() IEnumerable extensions from lua script using nula

So I have a little lua script where I want to call an extension method on IEnumerable collection.
require ''CLRPackage''
import ''System.Collections.Generic''
import ''System.Linq''
import ''My.Namespace.Containing.AudioMarker''
local audioMarkersWithOffset = GetAudioMarkers();
local numberOfMarkers = audioMarkersWithOffset.Count();
So GetAudioMarkers() is a C# method returning an IEnumerable of AudioMarker objects. Doing a luanet.each will work fine and I will be able to iterate to every element of the collection. But I need the count of that collection and calling .Count() does the following error:
NLua.Exceptions.LuaScriptException: [string "chunk"]:54: attempt to call field 'Count' (a string value).
By the way, I know that with nlua you don't need to pre-register your types to used them so I try with and without the last import about AudioMarker, but got the same result.
I'm probably doing something wrong but I cannot seem to find any documentation on the web that could help regarding this issue.
I have been trying to use the IEnumerable<T>.ToList() extension method myself, but testing reveals that NLua has some problems with generic methods.. Calling a method of the form void func<T>(<T> arg) is possible if you register it as a lua function (Lua.RegisterFunction), but if you try to call the same method on an object present in lua state, you get the "attempt to call method..." error. Also, a method of the form void func<T>(IEnumerable<T> arg) will fail in both cases with a NullReferenceException and the "attempt to call method..." error, respectively.
Another point is, if you want to call C# extension methods from Lua, you need the ":" syntax, not "." (see the NLua "TestExtensionMethods" unit test).

How do I load and cache data into a bottle.py app that's accessible in multiple functions without using global variables?

I have a bottle.py app that should load some data, parts of which get served depending on specific routes. (This is similar to memcached in principle, except the data isn't that big and I don't want the extra complexity.) I can load the data into global variables which are accessible from each function I write, but this seems less clean. Is there any way to load some data into a Bottle() instance during initialization?
You can do it by using bottle.default_app
Here's simple example.
main.py (used sample code from http://bottlepy.org/docs/dev/)
import bottle
from bottle import route, run, template
app = bottle.default_app()
app.myvar = "Hello there!" # add new variable to app
#app.route('/hello/<name>')
def index(name='World'):
return template('<b>Hello {{name}}</b>!', name=name)
run(app, host='localhost', port=8080)
some_handler.py
import bottle
def show_var_from_app():
var_from_app = bottle.default_app().myvar
return var_from_app

Accessing Ruby Threads

Probably not even a valid question but how can I see what this block contains:
spec = Thread.current[:spec]
print spec # gives => #<RSpec::Core::ExampleGroup::Nested_1:0x7f61991d90c8>
Can I see any of the methods assigned to this or whatever is in it?
If more context is needed, I'm trying to understand what spec is doing here in function here but not being used anywhere (at least directly)
https://github.com/amfranz/rspec-hiera-puppet/blob/master/lib/rspec-hiera-puppet/puppet.rb#L7
To view properties do:
spec.inspect
If you want to access those properties:
spec.propertyyouwant

Resources