Here are the examples of the python api twisted.web.resource.Resource.__init__ taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
151 Examples
3
Example 1
def __init__(self, device, backend=None):
self.device = device
if backend == None:
backend = self.device.backend
resource.Resource.__init__(self)
service.ServiceServer.__init__(self, 'SwitchPower', self.device.version, backend)
self.control = SwitchPowerControl(self)
self.putChild(self.scpd_url, service.scpdXML(self, self.control))
self.putChild(self.control_url, self.control)
3
Example 2
def __init__(self, *args, **kwargs):
"""
Important part to note here is that self.context is the dict that
we serialize and return to the user. Add any key/values in here that
the user needs to see.
"""
Resource.__init__(self)
# This holds the user's parsed JSON input, if applicable.
self.user_input = None
# The payload we return to the user.
self.context = {
'success': True
}
3
Example 3
def __init__(self, db, retrieval_privkey):
resource.Resource.__init__(self)
self.db = db
self.retrieval_privkey = retrieval_privkey
self.old_requests = {} # maps tmppub to timestamp
self.db.subscribe("mailbox_server_messages", self.new_message)
# tid -> (EventsProtocol,symkey,tmppub) . only one per tid.
self.subscribers = {}
3
Example 4
def __init__(self, controlpoint):
resource.Resource.__init__(self)
log.Loggable.__init__(self)
self.controlpoint = controlpoint
self.controlpoint.coherence.add_web_resource('json',
self)
self.children = {}
3
Example 5
def __init__(self, access_token, db, agent):
resource.Resource.__init__(self)
self.access_token = access_token
self.db = db
self.agent = agent
self.event_dispatcher = EventChannelDispatcher(db, agent)
3
Example 6
def __init__(self, code, *lines):
resource.Resource.__init__(self)
self.code = code
self.body = ""
if lines != (None, ):
self.body = "\n".join(lines) + "\n\n"
# HACK!
if not hasattr(self, 'method'):
self.method = 'GET'
3
Example 7
Project: deluge Source File: json_api.py
def __init__(self):
resource.Resource.__init__(self)
component.Component.__init__(self, 'JSON')
self._remote_methods = []
self._local_methods = {}
if client.is_standalone():
self.get_remote_methods()
3
Example 8
Project: scrapy Source File: mockserver.py
def __init__(self):
Resource.__init__(self)
self.putChild(b"status", Status())
self.putChild(b"follow", Follow())
self.putChild(b"delay", Delay())
self.putChild(b"partial", Partial())
self.putChild(b"drop", Drop())
self.putChild(b"raw", Raw())
self.putChild(b"echo", Echo())
if twisted_version > (12, 3, 0):
from twisted.web.test.test_webclient import PayloadResource
from twisted.web.server import GzipEncoderFactory
from twisted.web.resource import EncodingResourceWrapper
self.putChild(b"payload", PayloadResource())
self.putChild(b"xpayload", EncodingResourceWrapper(PayloadResource(), [GzipEncoderFactory()]))
3
Example 9
def __init__(self, path = ""):
resource.Resource.__init__(self)
self.path = path
self.withMainTemplate = False
self.isJson = False
self.isCustom = False
self.isGZ = False
3
Example 10
def __init__(self, factory, error_code="404"):
self.factory = factory
self.skin = self.factory.skin
self.skindir = self.factory.skindir
self.error_code = error_code
if not os.path.isdir(self.skindir):
raise Exception(
"Directory %s for http skin, %s, does not exist." %
(self.skindir,self.skin))
with open(os.path.join(self.skindir, error_code+".html")) as f:
self.error_contents = f.read()
Resource.__init__(self)
3
Example 11
def __init__(self, pre, post, explode, incrementBy):
self.pre = pre
self.post = post
self.explode = explode
self.incrementBy = incrementBy
resource.Resource.__init__(self)
3
Example 12
def __init__(self, request, api_router):
request.setHeader("Content-Type", "application/json; charset=utf-8")
if hasattr(api_router, "cross_origin_domains") and \
api_router.cross_origin_domains:
request.setHeader("Access-Control-Allow-Origin", api_router.cross_origin_domains)
Resource.__init__(self)
3
Example 13
def __init__(self, entries, target_bitrate=None, min_bitrate=AUDIO_TARGET):
Resource.__init__(self)
self._entries = entries
self._target_bitrate = target_bitrate
self._min_bitrate = min_bitrate
3
Example 14
def __init__(self, uri, destination=None):
self.info('uri %s %r', uri, type(uri))
if uri[:7] not in ['file://', 'http://']:
uri = 'file://' + urllib.quote(uri) # FIXME
self.uri = uri
self.destination = destination
resource.Resource.__init__(self)
log.Loggable.__init__(self)
3
Example 15
def __init__(self, http_port):
Resource.__init__(self)
self.putChild(b"1.html", self.IframeContent1())
self.putChild(b"2.html", self.IframeContent2())
self.putChild(b"3.html", self.IframeContent3())
self.putChild(b"4.html", self.IframeContent4())
self.putChild(b"5.html", self.IframeContent5())
self.putChild(b"6.html", self.IframeContent6())
self.putChild(b"script.js", self.ScriptJs())
self.putChild(b"script2.js", self.OtherDomainScript())
self.putChild(b"nested.html", self.NestedIframeContent())
self.http_port = http_port
3
Example 16
def __init__(self, kserver):
resource.Resource.__init__(self)
self.kserver = kserver
# throttle in seconds to check app for new data
self.throttle = .25
# define a list to store client requests
self.delayed_requests = []
# define a list to store incoming keys from new POSTs
self.incoming_posts = []
# setup a loop to process delayed requests
loopingCall = task.LoopingCall(self.processDelayedRequests)
loopingCall.start(self.throttle, False)
3
Example 17
def __init__(self, get_response_for):
"""
See ``StringStubbingResource``.
"""
Resource.__init__(self)
self._get_response_for = get_response_for
3
Example 18
def __init__(self, name, *directories):
resource.Resource.__init__(self)
component.Component.__init__(self, name)
self.__paths = {}
for directory in directories:
self.add_directory(directory)
3
Example 19
def __init__(self, worker, conversation_key):
resource.Resource.__init__(self)
self.worker = worker
self.conversation_key = conversation_key
self.vumi_api = self.worker.vumi_api
self.user_apis = {}
3
Example 20
def __init__(self, session, path = ""):
resource.Resource.__init__(self)
self.session = session
try:
from Plugins.Extensions.AutoTimer.AutoTimerResource import AutoTimerDoParseResource, \
AutoTimerAddOrEditAutoTimerResource, AutoTimerChangeSettingsResource, \
AutoTimerRemoveAutoTimerResource, AutoTimerSettingsResource, \
AutoTimerSimulateResource
except ImportError:
print "AT plugin not found"
return
self.putChild('parse', AutoTimerDoParseResource())
self.putChild('remove', AutoTimerRemoveAutoTimerResource())
self.putChild('edit', AutoTimerAddOrEditAutoTimerResource())
self.putChild('get', AutoTimerSettingsResource())
self.putChild('set', AutoTimerChangeSettingsResource())
self.putChild('simulate', AutoTimerSimulateResource())
3
Example 21
def __init__(self, db, agent):
resource.Resource.__init__(self)
self.db = db
self.agent = agent
self.event_channels = {}
self.unclaimed_event_channels = set()
3
Example 22
def __init__(self, db, agent, event_dispatcher, payload):
resource.Resource.__init__(self)
self.db = db
self.agent = agent
self.event_dispatcher = event_dispatcher
self.payload = payload
3
Example 23
Project: pulp Source File: server.py
def __init__(self, config):
"""
Initialize a streamer instance.
:param config: The configuration for this streamer instance.
:type config: ConfigParser.SafeConfigParser
"""
resource.Resource.__init__(self)
self.config = config
# Used to pool TCP connections for upstream requests. Once requests #2863 is
# fixed and available, remove the PulpHTTPAdapter. This is a short-term work-around
# to avoid carrying the package.
self.session = requests.Session()
self.session.mount('https://', pulp_adapters.PulpHTTPAdapter())
3
Example 24
def __init__(self, request, url_matches, call_router=None):
request.setHeader("Content-Type", "application/json; charset=utf-8")
if call_router and \
hasattr(call_router, "version_router") and \
hasattr(call_router.version_router, "api_router"):
if hasattr(call_router.version_router.api_router, "cross_origin_domains") and \
call_router.version_router.api_router.cross_origin_domains:
request.setHeader("Access-Control-Allow-Origin",
call_router.version_router.api_router.cross_origin_domains)
request.setHeader("Access-Control-Allow-Credentials", "true")
if hasattr(call_router.version_router.api_router, "inhibit_http_caching") and \
call_router.version_router.api_router.inhibit_http_caching:
request.setHeader("Cache-Control", "no-cache")
request.setHeader("Pragma", "no-cache")
self.url_matches = url_matches
self.call_router = call_router
Resource.__init__(self)
3
Example 25
def __init__(self, factory):
self.factory = factory
self.skin = self.factory.skin
self.skindir = self.factory.skindir
if not os.path.isdir(self.skindir):
raise Exception(
"Directory %s for http skin, %s, does not exist."
% (self.skindir, self.skin))
with open(os.path.join(self.skindir, "index.html")) as f:
text = f.read()
p = re.compile(r"<!--STARTERR-->.*<!--ENDERR-->", re.DOTALL)
self.login = re.sub(p, "", text)
self.err = re.sub(r"<!--STARTERR-->|<!--ENDERR-->", "", text)
Resource.__init__(self)
3
Example 26
def __init__(self, route_map):
"""Sets up the twisted.web.Resource and loads the route map.
Arguments:
self - Reference to the object instance.
route_map (list) - List of mapping tuples containing a URL regex string to match, and
the Resource object to handle the API call. ?P<arg_name> regex
groups are converted to elements in a the argument dictionary passed
to the API call handler:
(r"^/example/auth/(?P<auth_call>.+)", AuthAPI)
"""
self.route_map = route_map
Resource.__init__(self)
3
Example 27
def __init__(self, calls_module, version_router=None, auto_list_versions=False):
"""Sets up the twisted.web.Resource and loads the route map.
Arguments:
self - Reference to the object instance.
calls_module (module) - Module containing API classes. Each URLMatchJSONResource
class will be introspected for it's route.
auto_list_versions (boolean) - If True, add an API call 'list_versions' that will
list the available versions of the current API.
"""
self.version_router=version_router
self._createRouteMap(calls_module)
if auto_list_versions:
self.route_map.append((re.compile(r"list_versions$"), ListVersionsCall))
Resource.__init__(self)
3
Example 28
def __init__(self, mount_point, properties, filename):
Resource.__init__(self)
index_name = properties.get('index', 'index.html')
root = mount_point
if not root.endswith("/"):
root += "/"
if index_name != 'index.html':
root = None
self._mount_point_root = root
self._properties = properties
self._index_content = self._get_index_content()
self._index_name = index_name
self._cortado_filename = filename
self._addChildren()
3
Example 29
def __init__(self, pre, post, explode, incrementBy):
self.pre = pre
self.post = post
self.explode = explode
self.incrementBy = incrementBy
resource.Resource.__init__(self)
self.putChild("adapter", AdderResource(self.pre, self.post, self.explode, self.incrementBy))
3
Example 30
def __init__(self, pool, max_timeout, argument_cache):
Resource.__init__(self)
self.pool = pool
self.js_profiles_path = self.pool.js_profiles_path
self.max_timeout = max_timeout
self.argument_cache = argument_cache
3
Example 31
def __init__(self, pipeline, content_type):
self.pipeline_description = pipeline
self.contentType = content_type
self.requests = []
# if stream has a streamheader (something that has to be prepended
# before any data), then it will be a tuple of GstBuffers
self.streamheader = None
self.parse_pipeline()
resource.Resource.__init__(self)
log.Loggable.__init__(self)
3
Example 32
def __init__(self, mount_point, properties):
Resource.__init__(self)
index_name = properties.get('index', 'index.html')
root = mount_point
if not root.endswith("/"):
root += "/"
if index_name != 'index.html':
root = None
self._mount_point_root = root
self._properties = properties
self._index_content = self._get_index_content()
self._index_name = index_name
self._addChildren()
3
Example 33
def __init__(self, tube_service, device, backend=None):
self.device = device
self.service = tube_service
resource.Resource.__init__(self)
id = self.service.get_id().split(':')[3]
service.ServiceServer.__init__(self, id, self.device.version, None)
self.control = TubeServiceControl(self)
self.putChild(self.scpd_url, service.scpdXML(self, self.control))
self.putChild(self.control_url, self.control)
self.device.web_resource.putChild(id, self)
3
Example 34
def __init__(self, message_store, batch_id):
resource.Resource.__init__(self)
self.message_store = message_store
self.batch_id = batch_id
inbound = resource.Resource()
inbound.putChild('match',
MatchResource('inbound', message_store, batch_id))
self.putChild('inbound', inbound)
outbound = resource.Resource()
outbound.putChild('match',
MatchResource('outbound', message_store, batch_id))
self.putChild('outbound', outbound)
3
Example 35
def __init__(self, kserver):
resource.Resource.__init__(self)
self.kserver = kserver
self.protobuf = []
self.json = []
loopingCall = task.LoopingCall(self.crawl)
loopingCall.start(60, True)
3
Example 36
def __init__(self,pypes,cluster,agents):
Resource.__init__(self)
self.pypes = pypes
self.cluster = cluster
self.agents = agents
self.cpuUsage = -1.0
self.memUsage = 0
self.lastCalcTime = time.time()
self.lastCpuVal = 0.0
self.templates = {}
for tmpl in os.listdir('templates'):
if not tmpl.endswith('.tmpl'): continue
self.templates[ tmpl[:-5] ] = open('templates/%s' % tmpl).read()
3
Example 37
def __init__(self, parent):
"""
:param parent: The Web parent resource for the WAMP session.
:type parent: Instance of :class:`autobahn.twisted.longpoll.WampLongPollResourceSession`.
"""
Resource.__init__(self)
self._parent = parent
3
Example 38
def __init__(self, original_children):
Resource.__init__(self)
try:
from twisted.web.server import GzipEncoderFactory
from twisted.web.resource import EncodingResourceWrapper
for path, child in original_children.items():
self.putChild(
path,
EncodingResourceWrapper(child, [GzipEncoderFactory()])
)
except ImportError:
pass
3
Example 39
def __init__(self):
resource.Resource.__init__(self)
try:
self.tracker_icons = component.get('TrackerIcons')
except KeyError:
self.tracker_icons = TrackerIcons()
3
Example 40
def __init__(self, service, v=0):
"""Initialize.
"""
resource.Resource.__init__(self)
self.service = service
self.hp = None
self.children = {}
self.client = 0
self.verbose = v
self.polling = self.service.polling or 15
3
Example 41
def __init__(self):
resource.Resource.__init__(self)
component.Component.__init__(self, 'Scripts')
self.__scripts = {}
for script_type in ['normal', 'debug', 'dev']:
self.__scripts[script_type] = {'scripts': {}, 'order': [], 'files_exist': True}
3
Example 42
def __init__(self, debug=False, signing_key=None, signing_id=None,
event_handler=GenericEventHandler):
Resource.__init__(self)
self.signing_key = signing_key
self.signing_id = signing_id
self.debug = debug # This class acts as a 'factory', debug is used by Protocol
self.event_handler = event_handler
3
Example 43
def __init__(self, callbacks, info):
resource.Resource.__init__(self)
self.callbacks = callbacks
self.info = info
self.aesiv = None
self.rsaaeskey = None
self.fmtp = None
self.process = None
3
Example 44
def __init__(self, db, agent, dispatcher, esid):
resource.Resource.__init__(self)
self.db = db
self.agent = agent
self.dispatcher = dispatcher
self.esid = esid
# this maps topic to set of (table,notifierfunc)
self.db_subscriptions = collections.defaultdict(set)
3
Example 45
def __init__(self, config, vhost, path, logpath, logfile, db, redirecturl="error"):
self.index = ""
self.vhost = vhost
self.path = path
self.logpath = logpath
self.logfile = logfile
self.redirecturl = redirecturl
self.config = config
self.loadIndex()
self.display = Display()
self.display.setLogPath(self.logpath)
self.db = db
Resource.__init__(self)
3
Example 46
def __init__(self, job_registry, enable_worker_id):
Resource.__init__(self)
self.job_registry = job_registry
self.isWorkerID = enable_worker_id
self.submitHashrates = {}
self.getWorkCacheTimeout = {"work":"","time":0}
3
Example 47
def __init__(self, resource, user, password, realm):
"""Constructor.
@param resource: resource to protect with authentication.
@param user: the htpasswd user
@param password: the htpasswd pass
@param realm: HTTP auth realm.
"""
Resource.__init__(self)
self.resource = resource
self.realm = realm
self.user = user
m = md5()
m.update(password)
del password
self.passwordDigest = m.digest()
3
Example 48
def __init__(self, processor, inputProtocolFactory,
outputProtocolFactory=None):
resource.Resource.__init__(self)
self.inputProtocolFactory = inputProtocolFactory
if outputProtocolFactory is None:
self.outputProtocolFactory = inputProtocolFactory
else:
self.outputProtocolFactory = outputProtocolFactory
self.processor = processor
3
Example 49
def __init__(self, path, httpauth,
mimeToResource=None,
rateController=None,
requestModifiers=None,
metadataProvider=None):
resource.Resource.__init__(self)
self._path = path
self._httpauth = httpauth
# mapping of mime type -> File subclass
self._mimeToResource = mimeToResource or {}
self._rateController = rateController
self._metadataProvider = metadataProvider
self._requestModifiers = requestModifiers or []
self._factory = MimedFileFactory(httpauth, self._mimeToResource,
rateController=rateController,
metadataProvider=metadataProvider,
requestModifiers=requestModifiers)
3
Example 50
def __init__(self, version_map, api_router=None):
"""Sets up the twisted.web.Resource and loads the version map.
Arguments:
self - Reference to the object instance
version_map (dictionary) - Dictionary of mapping tuples containing a version pattern to match, and
the module to handle that version:
{ "0.8" : (r"0.8", v0_8"),
"1.0" : (r"1.0", v1_0") }
"""
self.api_router = api_router
temp_version_map = {}
for version in version_map.keys():
temp_version_map[version]= (re.compile(version_map[version][0] + "$"), version_map[version][1])
self.version_map = temp_version_map
Resource.__init__(self)