Best Python code snippet using fMBT_python
royal.py
Source:royal.py
1"""Extension to integrate pyramid_caching into pyramid_royal applications."""2from __future__ import absolute_import3from pyramid.view import view_config4from royal import Collection, Item, Root5from royal.views import CollectionView, delete, ItemView, not_allowed6from pyramid_caching.cache import (7 cache_factory,8 QueryStringKeyModifier,9 ResourceDependency,10 )11def includeme(config): # pragma: no cover12 """Register cached views into a Pyramid configurator."""13 config.scan(__name__)14class CachedResourceMixin(object):15 """Mixin class for Royal resources that can invalidate their cache key."""16 def invalidate(self):17 """Invalidate the cache key for this resource."""18 dep = ResourceDependency()19 key = dep(self, self.root.request)20 self.root.request.versioner.incr(key)21class CachedCollection(Collection, CachedResourceMixin):22 """A resource that supports caching and contains cached items."""23 __composite__ = True24class CachedItem(Item, CachedResourceMixin):25 """A cached resource that may belong to a cached collection."""26 pass27class CachedViewMixin(object):28 """Mixin class for Royal views that automatically invalidate the cache."""29 def __init__(self, context, request): # pragma: no cover30 self.context = context31 self.request = request32 @view_config(context=CachedCollection,33 request_method='DELETE',34 permission='delete',35 renderer='royal')36 @view_config(context=CachedItem,37 request_method='DELETE',38 permission='delete',39 renderer='royal')40 def cached_delete(self):41 """Delete the resource and invalidate the cache."""42 response = delete(self.context, self.request)43 self.context.invalidate()44 return response45 @view_config(context=CachedCollection,46 renderer='royal')47 @view_config(context=CachedItem,48 renderer='royal')49 @view_config(context=Root,50 renderer='royal')51 def cached_not_allowed(self):52 """Operation method is not valid for this resource type."""53 return not_allowed(self.context, self.request)54class CachedCollectionView(CollectionView, CachedViewMixin):55 """Collection of resources that caches the list of items it possesses."""56 @view_config(context=CachedCollection,57 request_method='GET',58 permission='index',59 decorator=cache_factory(60 depends_on=[61 ResourceDependency(),62 ],63 varies_on=[64 QueryStringKeyModifier(),65 ],66 ))67 def cached_index(self):68 """Respond with the list of items in this collection."""69 return self.index()70 @view_config(context=CachedCollection,71 request_method='POST',72 permission='create')73 def cached_create(self):74 """Add a new item to this collection and invalidate its cache."""75 response = self.create()76 self.context.invalidate()77 return response78class CachedItemView(ItemView, CachedViewMixin):79 """A resource that caches its representation."""80 @view_config(context=CachedItem,81 request_method='GET',82 permission='show',83 decorator=cache_factory(84 depends_on=[85 ResourceDependency(),86 ],87 varies_on=[88 QueryStringKeyModifier(),89 ],90 ))91 @view_config(context=Root,92 request_method='GET',93 permission='show',94 decorator=cache_factory(95 depends_on=[96 ResourceDependency(),97 ],98 varies_on=[99 QueryStringKeyModifier(),100 ],101 ))102 def cached_show(self):103 """Respond with a representation of this resource."""104 return self.show()105 @view_config(context=CachedItem,106 request_method='PUT',107 permission='replace')108 def cached_put(self):109 """Replace the current resource and invalidate its cache."""110 response = self.put()111 self.context.invalidate()112 return response113 @view_config(context=CachedItem,114 request_method='PATCH',115 permission='update')116 def cached_update(self):117 """Modify the resource and invalidate its cache."""118 response = self.patch()119 self.context.invalidate()120 return response121 @view_config(context=CachedItem,122 request_method='POST')123 def cached_post(self):124 # Raises MethodNotAllowed...
alfaviewCachedLogin.py
Source:alfaviewCachedLogin.py
1#!/usr/bin/env python32import hfuLogin3import alfaviewEngine4import json, os, time5def isCacheFile(path='./cache.json'):6 return os.path.isfile(path)7def getCacheFile(path='./cache.json'):8 if isCacheFile(path):9 cacheFile= open(path, 'r')10 cacheContent= cacheFile.read()11 cacheFile.close()12 cacheValues = json.loads(cacheContent)13 return cacheValues14 else:15 return []16def setCacheFile(cacheValues, path='./cache.json'):17 configContent = json.dumps(configValues)18 configFile= open(path, 'w')19 configFile.write(configContent)20 configFile.close()21def cleanCache(cacheValues):22 newCacheValues=[]23 cutTime= time.time()-(12*60*60)24 25 for item in cacheValues:26 if item['timestamp'] >= cutTime:27 newCacheValues.append(item)28 29 return newCacheValues30def retrieveCache(cacheValues, key):31 for item in cacheValues:32 if item['key'] == key:33 return item34def start(myRoom, myUsername, myPassword, myName, alfaviewPath='/opt/alfaview/alfaview', timeout=15, bandWidthUsage='normal', noUpdate=0, skipQuickSetup=1, configDir='./'):35 cacheValues= getCacheFile(configDir + 'cache.json')36 cacheValues= cleanCache(cacheValues)37 cachedItem= retrieveCache(cacheValues, myRoom + myUsername + myName)38 if cachedItem == None:39 url= hfuLogin.getUrl(myRoom, myUsername, myPassword, myName, geckoLogPath=configDir+'geckodriver.log', webdriverPath=configDir, timeout=timeout)40 cachedItem= {'timestamp': time.time(), 'key': myRoom + myUsername + myName, 'url': url}41 cacheValues.append(cachedItem)42 setCacheFile(cacheValues, configDir + 'cache.json')43 ...
test_cache_lib.py
Source:test_cache_lib.py
1import pytest2from cache_lib import CachedDict3import time4@pytest.fixture(scope='module')5def cd():6 cd = CachedDict()7 yield cd8def test_cacheIt(cd):9 assert cd.cacheIt('a', 10) == '<CachedItem {a:10} last updated with frequency 1>'10 assert cd.cacheIt('b', 11) == '<CachedItem {b:11} last updated with frequency 1>'11 time.sleep(2)12 assert cd.cacheIt('c', 12) == '<CachedItem {c:12} last updated with frequency 1>'13 assert cd.cacheIt('c', 13) == '<CachedItem {c:13} last updated with frequency 2>'14 time.sleep(2)15 assert cd.cacheIt('b', 13) == '<CachedItem {b:13} last updated with frequency 2>'16 time.sleep(1)17 assert cd.cacheIt('a', 13) == '<CachedItem {a:13} last updated with frequency 2>'18 time.sleep(1)19 assert cd.cacheIt('c', [1, 2, 3]) == '<CachedItem {c:[1, 2, 3]} last updated with frequency 3>'...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!