code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
current_mid = self._current_mid
self._current_mid += 1
self._current_mid %= 65535
return current_mid | def fetch_mid(self) | Gets the next valid MID.
:return: the mid to use | 3.878583 | 3.718991 | 1.042913 |
logger.debug("receive_request - " + str(request))
try:
host, port = request.source
except AttributeError:
return
key_mid = str_append_hash(host, port, request.mid)
key_token = str_append_hash(host, port, request.token)
if key_mid in list(self._transactions.keys()):
# Duplicated
self._transactions[key_mid].request.duplicated = True
transaction = self._transactions[key_mid]
else:
request.timestamp = time.time()
transaction = Transaction(request=request, timestamp=request.timestamp)
with transaction:
self._transactions[key_mid] = transaction
self._transactions_token[key_token] = transaction
return transaction | def receive_request(self, request) | Handle duplicates and store received messages.
:type request: Request
:param request: the incoming request
:rtype : Transaction
:return: the edited transaction | 3.943686 | 3.915129 | 1.007294 |
logger.debug("receive_response - " + str(response))
try:
host, port = response.source
except AttributeError:
return
key_mid = str_append_hash(host, port, response.mid)
key_mid_multicast = str_append_hash(defines.ALL_COAP_NODES, port, response.mid)
key_token = str_append_hash(host, port, response.token)
key_token_multicast = str_append_hash(defines.ALL_COAP_NODES, port, response.token)
if key_mid in list(self._transactions.keys()):
transaction = self._transactions[key_mid]
if response.token != transaction.request.token:
logger.warning("Tokens does not match - response message " + str(host) + ":" + str(port))
return None, False
elif key_token in self._transactions_token:
transaction = self._transactions_token[key_token]
elif key_mid_multicast in list(self._transactions.keys()):
transaction = self._transactions[key_mid_multicast]
elif key_token_multicast in self._transactions_token:
transaction = self._transactions_token[key_token_multicast]
if response.token != transaction.request.token:
logger.warning("Tokens does not match - response message " + str(host) + ":" + str(port))
return None, False
else:
logger.warning("Un-Matched incoming response message " + str(host) + ":" + str(port))
return None, False
send_ack = False
if response.type == defines.Types["CON"]:
send_ack = True
transaction.request.acknowledged = True
transaction.completed = True
transaction.response = response
if transaction.retransmit_stop is not None:
transaction.retransmit_stop.set()
return transaction, send_ack | def receive_response(self, response) | Pair responses with requests.
:type response: Response
:param response: the received response
:rtype : Transaction
:return: the transaction to which the response belongs to | 2.667487 | 2.650788 | 1.0063 |
logger.debug("receive_empty - " + str(message))
try:
host, port = message.source
except AttributeError:
return
key_mid = str_append_hash(host, port, message.mid)
key_mid_multicast = str_append_hash(defines.ALL_COAP_NODES, port, message.mid)
key_token = str_append_hash(host, port, message.token)
key_token_multicast = str_append_hash(defines.ALL_COAP_NODES, port, message.token)
if key_mid in list(self._transactions.keys()):
transaction = self._transactions[key_mid]
elif key_token in self._transactions_token:
transaction = self._transactions_token[key_token]
elif key_mid_multicast in list(self._transactions.keys()):
transaction = self._transactions[key_mid_multicast]
elif key_token_multicast in self._transactions_token:
transaction = self._transactions_token[key_token_multicast]
else:
logger.warning("Un-Matched incoming empty message " + str(host) + ":" + str(port))
return None
if message.type == defines.Types["ACK"]:
if not transaction.request.acknowledged:
transaction.request.acknowledged = True
elif (transaction.response is not None) and (not transaction.response.acknowledged):
transaction.response.acknowledged = True
elif message.type == defines.Types["RST"]:
if not transaction.request.acknowledged:
transaction.request.rejected = True
elif not transaction.response.acknowledged:
transaction.response.rejected = True
elif message.type == defines.Types["CON"]:
#implicit ACK (might have been lost)
logger.debug("Implicit ACK on received CON for waiting transaction")
transaction.request.acknowledged = True
else:
logger.warning("Unhandled message type...")
if transaction.retransmit_stop is not None:
transaction.retransmit_stop.set()
return transaction | def receive_empty(self, message) | Pair ACKs with requests.
:type message: Message
:param message: the received message
:rtype : Transaction
:return: the transaction to which the message belongs to | 2.661511 | 2.634248 | 1.010349 |
logger.debug("send_request - " + str(request))
assert isinstance(request, Request)
try:
host, port = request.destination
except AttributeError:
return
request.timestamp = time.time()
transaction = Transaction(request=request, timestamp=request.timestamp)
if transaction.request.type is None:
transaction.request.type = defines.Types["CON"]
if transaction.request.mid is None:
transaction.request.mid = self.fetch_mid()
key_mid = str_append_hash(host, port, request.mid)
self._transactions[key_mid] = transaction
key_token = str_append_hash(host, port, request.token)
self._transactions_token[key_token] = transaction
return self._transactions[key_mid] | def send_request(self, request) | Create the transaction and fill it with the outgoing request.
:type request: Request
:param request: the request to send
:rtype : Transaction
:return: the created transaction | 4.054718 | 4.004712 | 1.012487 |
logger.debug("send_response - " + str(transaction.response))
if transaction.response.type is None:
if transaction.request.type == defines.Types["CON"] and not transaction.request.acknowledged:
transaction.response.type = defines.Types["ACK"]
transaction.response.mid = transaction.request.mid
transaction.response.acknowledged = True
transaction.completed = True
elif transaction.request.type == defines.Types["NON"]:
transaction.response.type = defines.Types["NON"]
else:
transaction.response.type = defines.Types["CON"]
transaction.response.token = transaction.request.token
if transaction.response.mid is None:
transaction.response.mid = self.fetch_mid()
try:
host, port = transaction.response.destination
except AttributeError:
return
key_mid = str_append_hash(host, port, transaction.response.mid)
self._transactions[key_mid] = transaction
transaction.request.acknowledged = True
return transaction | def send_response(self, transaction) | Set the type, the token and eventually the MID for the outgoing response
:type transaction: Transaction
:param transaction: the transaction that owns the response
:rtype : Transaction
:return: the edited transaction | 3.225605 | 3.159031 | 1.021074 |
logger.debug("send_empty - " + str(message))
if transaction is None:
try:
host, port = message.destination
except AttributeError:
return
key_mid = str_append_hash(host, port, message.mid)
key_token = str_append_hash(host, port, message.token)
if key_mid in self._transactions:
transaction = self._transactions[key_mid]
related = transaction.response
elif key_token in self._transactions_token:
transaction = self._transactions_token[key_token]
related = transaction.response
else:
return message
if message.type == defines.Types["ACK"]:
if transaction.request == related:
transaction.request.acknowledged = True
transaction.completed = True
message.mid = transaction.request.mid
message.code = 0
message.destination = transaction.request.source
elif transaction.response == related:
transaction.response.acknowledged = True
transaction.completed = True
message.mid = transaction.response.mid
message.code = 0
message.token = transaction.response.token
message.destination = transaction.response.source
elif message.type == defines.Types["RST"]:
if transaction.request == related:
transaction.request.rejected = True
message._mid = transaction.request.mid
if message.mid is None:
message.mid = self.fetch_mid()
message.code = 0
message.token = transaction.request.token
message.destination = transaction.request.source
elif transaction.response == related:
transaction.response.rejected = True
transaction.completed = True
message._mid = transaction.response.mid
if message.mid is None:
message.mid = self.fetch_mid()
message.code = 0
message.token = transaction.response.token
message.destination = transaction.response.source
return message | def send_empty(self, transaction, related, message) | Manage ACK or RST related to a transaction. Sets if the transaction has been acknowledged or rejected.
:param transaction: the transaction
:param related: if the ACK/RST message is related to the request or the response. Must be equal to
transaction.request or to transaction.response or None
:type message: Message
:param message: the ACK or RST message to send | 2.30086 | 2.192849 | 1.049256 |
value = []
for option in self.options:
if option.number == defines.OptionRegistry.LOCATION_PATH.number:
value.append(str(option.value))
return "/".join(value) | def location_path(self) | Return the Location-Path of the response.
:rtype : String
:return: the Location-Path option | 7.152177 | 5.804626 | 1.232151 |
path = path.strip("/")
tmp = path.split("?")
path = tmp[0]
paths = path.split("/")
for p in paths:
option = Option()
option.number = defines.OptionRegistry.LOCATION_PATH.number
option.value = p
self.add_option(option) | def location_path(self, path) | Set the Location-Path of the response.
:type path: String
:param path: the Location-Path as a string | 5.220633 | 5.482232 | 0.952282 |
value = []
for option in self.options:
if option.number == defines.OptionRegistry.LOCATION_QUERY.number:
value.append(option.value)
return value | def location_query(self) | Return the Location-Query of the response.
:rtype : String
:return: the Location-Query option | 9.126348 | 6.931889 | 1.316575 |
del self.location_query
queries = value.split("&")
for q in queries:
option = Option()
option.number = defines.OptionRegistry.LOCATION_QUERY.number
option.value = str(q)
self.add_option(option) | def location_query(self, value) | Set the Location-Query of the response.
:type path: String
:param path: the Location-Query as a string | 6.8791 | 7.047185 | 0.976149 |
value = defines.OptionRegistry.MAX_AGE.default
for option in self.options:
if option.number == defines.OptionRegistry.MAX_AGE.number:
value = int(option.value)
return value | def max_age(self) | Return the MaxAge of the response.
:rtype : int
:return: the MaxAge option | 5.518918 | 5.327404 | 1.035949 |
option = Option()
option.number = defines.OptionRegistry.MAX_AGE.number
option.value = int(value)
self.del_option_by_number(defines.OptionRegistry.MAX_AGE.number)
self.add_option(option) | def max_age(self, value) | Set the MaxAge of the response.
:type value: int
:param value: the MaxAge option | 4.843599 | 5.250958 | 0.922422 |
self._socket.settimeout(float(timeout))
while not self.stopped.isSet():
try:
data, client_address = self._socket.recvfrom(4096)
if len(client_address) > 2:
client_address = (client_address[0], client_address[1])
except socket.timeout:
continue
except Exception as e:
if self._cb_ignore_listen_exception is not None and isinstance(self._cb_ignore_listen_exception, collections.Callable):
if self._cb_ignore_listen_exception(e, self):
continue
raise
try:
serializer = Serializer()
message = serializer.deserialize(data, client_address)
if isinstance(message, int):
logger.error("receive_datagram - BAD REQUEST")
rst = Message()
rst.destination = client_address
rst.type = defines.Types["RST"]
rst.code = message
rst.mid = self._messageLayer.fetch_mid()
self.send_datagram(rst)
continue
logger.debug("receive_datagram - " + str(message))
if isinstance(message, Request):
transaction = self._messageLayer.receive_request(message)
if transaction.request.duplicated and transaction.completed:
logger.debug("message duplicated, transaction completed")
if transaction.response is not None:
self.send_datagram(transaction.response)
continue
elif transaction.request.duplicated and not transaction.completed:
logger.debug("message duplicated, transaction NOT completed")
self._send_ack(transaction)
continue
args = (transaction, )
t = threading.Thread(target=self.receive_request, args=args)
t.start()
# self.receive_datagram(data, client_address)
elif isinstance(message, Response):
logger.error("Received response from %s", message.source)
else: # is Message
transaction = self._messageLayer.receive_empty(message)
if transaction is not None:
with transaction:
self._blockLayer.receive_empty(message, transaction)
self._observeLayer.receive_empty(message, transaction)
except RuntimeError:
logger.exception("Exception with Executor")
self._socket.close() | def listen(self, timeout=10) | Listen for incoming messages. Timeout is used to check if the server must be switched off.
:param timeout: Socket Timeout in seconds | 3.543843 | 3.549566 | 0.998388 |
with transaction:
transaction.separate_timer = self._start_separate_timer(transaction)
self._blockLayer.receive_request(transaction)
if transaction.block_transfer:
self._stop_separate_timer(transaction.separate_timer)
self._messageLayer.send_response(transaction)
self.send_datagram(transaction.response)
return
self._observeLayer.receive_request(transaction)
self._requestLayer.receive_request(transaction)
if transaction.resource is not None and transaction.resource.changed:
self.notify(transaction.resource)
transaction.resource.changed = False
elif transaction.resource is not None and transaction.resource.deleted:
self.notify(transaction.resource)
transaction.resource.deleted = False
self._observeLayer.send_response(transaction)
self._blockLayer.send_response(transaction)
self._stop_separate_timer(transaction.separate_timer)
self._messageLayer.send_response(transaction)
if transaction.response is not None:
if transaction.response.type == defines.Types["CON"]:
self._start_retransmission(transaction, transaction.response)
self.send_datagram(transaction.response) | def receive_request(self, transaction) | Handle requests coming from the udp socket.
:param transaction: the transaction created to manage the request | 3.106403 | 3.06209 | 1.014471 |
assert isinstance(resource, Resource)
path = path.strip("/")
paths = path.split("/")
actual_path = ""
i = 0
for p in paths:
i += 1
actual_path += "/" + p
try:
res = self.root[actual_path]
except KeyError:
res = None
if res is None:
resource.path = actual_path
self.root[actual_path] = resource
return True | def add_resource(self, path, resource) | Helper function to add resources to the resource directory during server initialization.
:param path: the path for the new created resource
:type resource: Resource
:param resource: the resource to be added | 2.730827 | 2.802532 | 0.974414 |
path = path.strip("/")
paths = path.split("/")
actual_path = ""
i = 0
for p in paths:
i += 1
actual_path += "/" + p
try:
res = self.root[actual_path]
except KeyError:
res = None
if res is not None:
del(self.root[actual_path])
return res | def remove_resource(self, path) | Helper function to remove resources.
:param path: the path for the unwanted resource
:rtype : the removed object | 2.959722 | 3.03697 | 0.974564 |
ack = Message()
ack.type = defines.Types['ACK']
# TODO handle mutex on transaction
if not transaction.request.acknowledged and transaction.request.type == defines.Types["CON"]:
ack = self._messageLayer.send_empty(transaction, transaction.request, ack)
self.send_datagram(ack) | def _send_ack(self, transaction) | Sends an ACK message for the request.
:param transaction: the transaction that owns the request | 10.363016 | 11.04873 | 0.937937 |
observers = self._observeLayer.notify(resource)
logger.debug("Notify")
for transaction in observers:
with transaction:
transaction.response = None
transaction = self._requestLayer.receive_request(transaction)
transaction = self._observeLayer.send_response(transaction)
transaction = self._blockLayer.send_response(transaction)
transaction = self._messageLayer.send_response(transaction)
if transaction.response is not None:
if transaction.response.type == defines.Types["CON"]:
self._start_retransmission(transaction, transaction.response)
self.send_datagram(transaction.response) | def notify(self, resource) | Notifies the observers of a certain resource.
:param resource: the resource | 5.280005 | 5.617746 | 0.93988 |
resource_node = self._parent.root[path]
transaction.resource = resource_node
# If-Match
if transaction.request.if_match:
if None not in transaction.request.if_match and str(transaction.resource.etag) \
not in transaction.request.if_match:
transaction.response.code = defines.Codes.PRECONDITION_FAILED.number
return transaction
method = getattr(resource_node, "render_POST", None)
try:
resource = method(request=transaction.request)
except NotImplementedError:
try:
method = getattr(resource_node, "render_POST_advanced", None)
ret = method(request=transaction.request, response=transaction.response)
if isinstance(ret, tuple) and len(ret) == 2 and isinstance(ret[1], Response) \
and isinstance(ret[0], Resource):
# Advanced handler
resource, response = ret
resource.changed = True
resource.observe_count += 1
transaction.resource = resource
transaction.response = response
if transaction.response.code is None:
transaction.response.code = defines.Codes.CREATED.number
return transaction
elif isinstance(ret, tuple) and len(ret) == 3 and isinstance(ret[1], Response) \
and isinstance(ret[0], Resource):
# Advanced handler separate
resource, response, callback = ret
ret = self._handle_separate_advanced(transaction, callback)
if not isinstance(ret, tuple) or \
not (isinstance(ret[0], Resource) and isinstance(ret[1], Response)): # pragma: no cover
transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number
return transaction
resource, response = ret
resource.changed = True
resource.observe_count += 1
transaction.resource = resource
transaction.response = response
if transaction.response.code is None:
transaction.response.code = defines.Codes.CREATED.number
return transaction
else:
raise NotImplementedError
except NotImplementedError:
transaction.response.code = defines.Codes.METHOD_NOT_ALLOWED.number
return transaction
if isinstance(resource, Resource):
pass
elif isinstance(resource, tuple) and len(resource) == 2:
resource, callback = resource
resource = self._handle_separate(transaction, callback)
if not isinstance(resource, Resource): # pragma: no cover
transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number
return transaction
else: # pragma: no cover
# Handle error
transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number
return transaction
if resource.path is None:
resource.path = path
resource.observe_count = resource_node.observe_count
if resource is resource_node:
transaction.response.code = defines.Codes.CHANGED.number
else:
transaction.response.code = defines.Codes.CREATED.number
resource.changed = True
resource.observe_count += 1
transaction.resource = resource
assert(isinstance(resource, Resource))
if resource.etag is not None:
transaction.response.etag = resource.etag
transaction.response.location_path = resource.path
if resource.location_query is not None and len(resource.location_query) > 0:
transaction.response.location_query = resource.location_query
transaction.response.payload = None
self._parent.root[resource.path] = resource
return transaction | def edit_resource(self, transaction, path) | Render a POST on an already created resource.
:param path: the path of the resource
:param transaction: the transaction
:return: the transaction | 2.22144 | 2.222194 | 0.999661 |
method = getattr(parent_resource, "render_POST", None)
try:
resource = method(request=transaction.request)
except NotImplementedError:
try:
method = getattr(parent_resource, "render_POST_advanced", None)
ret = method(request=transaction.request, response=transaction.response)
if isinstance(ret, tuple) and len(ret) == 2 and isinstance(ret[1], Response) \
and isinstance(ret[0], Resource):
# Advanced handler
resource, response = ret
resource.path = lp
resource.changed = True
self._parent.root[resource.path] = resource
transaction.resource = resource
transaction.response = response
if transaction.response.code is None:
transaction.response.code = defines.Codes.CREATED.number
return transaction
elif isinstance(ret, tuple) and len(ret) == 3 and isinstance(ret[1], Response) \
and isinstance(ret[0], Resource):
# Advanced handler separate
resource, response, callback = ret
ret = self._handle_separate_advanced(transaction, callback)
if not isinstance(ret, tuple) or \
not (isinstance(ret[0], Resource) and isinstance(ret[1], Response)): # pragma: no cover
transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number
return transaction
resource, response = ret
resource.path = lp
resource.changed = True
self._parent.root[resource.path] = resource
transaction.resource = resource
transaction.response = response
if transaction.response.code is None:
transaction.response.code = defines.Codes.CREATED.number
return transaction
else:
raise NotImplementedError
except NotImplementedError:
transaction.response.code = defines.Codes.METHOD_NOT_ALLOWED.number
return transaction
if isinstance(resource, Resource):
pass
elif isinstance(resource, tuple) and len(resource) == 2:
resource, callback = resource
resource = self._handle_separate(transaction, callback)
if not isinstance(resource, Resource): # pragma: no cover
transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number
return transaction
else: # pragma: no cover
# Handle error
transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number
return transaction
resource.path = lp
if resource.etag is not None:
transaction.response.etag = resource.etag
transaction.response.location_path = resource.path
if resource.location_query is not None and len(resource.location_query) > 0:
transaction.response.location_query = resource.location_query
transaction.response.code = defines.Codes.CREATED.number
transaction.response.payload = None
assert (isinstance(resource, Resource))
if resource.etag is not None:
transaction.response.etag = resource.etag
if resource.max_age is not None:
transaction.response.max_age = resource.max_age
resource.changed = True
transaction.resource = resource
self._parent.root[resource.path] = resource
return transaction | def add_resource(self, transaction, parent_resource, lp) | Render a POST on a new resource.
:param transaction: the transaction
:param parent_resource: the parent of the resource
:param lp: the location_path attribute of the resource
:return: the response | 2.142633 | 2.102326 | 1.019172 |
t = self._parent.root.with_prefix(path)
max_len = 0
imax = None
for i in t:
if i == path:
# Resource already present
return self.edit_resource(transaction, path)
elif len(i) > max_len:
imax = i
max_len = len(i)
lp = path
parent_resource = self._parent.root[imax]
if parent_resource.allow_children:
return self.add_resource(transaction, parent_resource, lp)
else:
transaction.response.code = defines.Codes.METHOD_NOT_ALLOWED.number
return transaction | def create_resource(self, path, transaction) | Render a POST request.
:param path: the path of the request
:param transaction: the transaction
:return: the response | 5.262882 | 5.416542 | 0.971631 |
# If-Match
if transaction.request.if_match:
if None not in transaction.request.if_match and str(transaction.resource.etag) \
not in transaction.request.if_match:
transaction.response.code = defines.Codes.PRECONDITION_FAILED.number
return transaction
# If-None-Match
if transaction.request.if_none_match:
transaction.response.code = defines.Codes.PRECONDITION_FAILED.number
return transaction
method = getattr(transaction.resource, "render_PUT", None)
try:
resource = method(request=transaction.request)
except NotImplementedError:
try:
method = getattr(transaction.resource, "render_PUT_advanced", None)
ret = method(request=transaction.request, response=transaction.response)
if isinstance(ret, tuple) and len(ret) == 2 and isinstance(ret[1], Response) \
and isinstance(ret[0], Resource):
# Advanced handler
resource, response = ret
resource.changed = True
resource.observe_count += 1
transaction.resource = resource
transaction.response = response
if transaction.response.code is None:
transaction.response.code = defines.Codes.CHANGED.number
return transaction
elif isinstance(ret, tuple) and len(ret) == 3 and isinstance(ret[1], Response) \
and isinstance(ret[0], Resource):
# Advanced handler separate
resource, response, callback = ret
ret = self._handle_separate_advanced(transaction, callback)
if not isinstance(ret, tuple) or \
not (isinstance(ret[0], Resource) and isinstance(ret[1], Response)): # pragma: no cover
transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number
return transaction
resource, response = ret
resource.changed = True
resource.observe_count += 1
transaction.resource = resource
transaction.response = response
if transaction.response.code is None:
transaction.response.code = defines.Codes.CHANGED.number
return transaction
else:
raise NotImplementedError
except NotImplementedError:
transaction.response.code = defines.Codes.METHOD_NOT_ALLOWED.number
return transaction
if isinstance(resource, Resource):
pass
elif isinstance(resource, tuple) and len(resource) == 2:
resource, callback = resource
resource = self._handle_separate(transaction, callback)
if not isinstance(resource, Resource): # pragma: no cover
transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number
return transaction
else: # pragma: no cover
# Handle error
transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number
return transaction
if resource.etag is not None:
transaction.response.etag = resource.etag
transaction.response.code = defines.Codes.CHANGED.number
transaction.response.payload = None
assert (isinstance(resource, Resource))
if resource.etag is not None:
transaction.response.etag = resource.etag
if resource.max_age is not None:
transaction.response.max_age = resource.max_age
resource.changed = True
resource.observe_count += 1
transaction.resource = resource
return transaction | def update_resource(self, transaction) | Render a PUT request.
:param transaction: the transaction
:return: the response | 2.131644 | 2.09962 | 1.015252 |
resource = transaction.resource
method = getattr(resource, 'render_DELETE', None)
try:
ret = method(request=transaction.request)
except NotImplementedError:
try:
method = getattr(transaction.resource, "render_DELETE_advanced", None)
ret = method(request=transaction.request, response=transaction.response)
if isinstance(ret, tuple) and len(ret) == 2 and isinstance(ret[1], Response) \
and isinstance(ret[0], bool):
# Advanced handler
delete, response = ret
if delete:
del self._parent.root[path]
transaction.response = response
if transaction.response.code is None:
transaction.response.code = defines.Codes.DELETED.number
return transaction
elif isinstance(ret, tuple) and len(ret) == 3 and isinstance(ret[1], Response) \
and isinstance(ret[0], Resource):
# Advanced handler separate
resource, response, callback = ret
ret = self._handle_separate_advanced(transaction, callback)
if not isinstance(ret, tuple) or \
not (isinstance(ret[0], bool) and isinstance(ret[1], Response)): # pragma: no cover
transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number
return transaction
delete, response = ret
if delete:
del self._parent.root[path]
transaction.response = response
if transaction.response.code is None:
transaction.response.code = defines.Codes.DELETED.number
return transaction
else:
raise NotImplementedError
except NotImplementedError:
transaction.response.code = defines.Codes.METHOD_NOT_ALLOWED.number
return transaction
if isinstance(ret, bool):
pass
elif isinstance(ret, tuple) and len(ret) == 2:
resource, callback = ret
ret = self._handle_separate(transaction, callback)
if not isinstance(ret, bool): # pragma: no cover
transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number
return transaction
else: # pragma: no cover
# Handle error
transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number
return transaction
if ret:
del self._parent.root[path]
transaction.response.code = defines.Codes.DELETED.number
transaction.response.payload = None
transaction.resource.deleted = True
else: # pragma: no cover
transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number
return transaction | def delete_resource(self, transaction, path) | Render a DELETE request.
:param transaction: the transaction
:param path: the path
:return: the response | 2.301254 | 2.254502 | 1.020737 |
method = getattr(transaction.resource, 'render_GET', None)
transaction.resource.actual_content_type = None
# Accept
if transaction.request.accept is not None:
transaction.resource.actual_content_type = transaction.request.accept
# Render_GET
try:
resource = method(request=transaction.request)
except NotImplementedError:
try:
method = getattr(transaction.resource, "render_GET_advanced", None)
ret = method(request=transaction.request, response=transaction.response)
if isinstance(ret, tuple) and len(ret) == 2 and isinstance(ret[1], Response) \
and isinstance(ret[0], Resource):
# Advanced handler
resource, response = ret
transaction.resource = resource
transaction.response = response
if transaction.response.code is None:
transaction.response.code = defines.Codes.CONTENT.number
return transaction
elif isinstance(ret, tuple) and len(ret) == 3 and isinstance(ret[1], Response) \
and isinstance(ret[0], Resource):
# Advanced handler separate
resource, response, callback = ret
ret = self._handle_separate_advanced(transaction, callback)
if not isinstance(ret, tuple) or \
not (isinstance(ret[0], Resource) and isinstance(ret[1], Response)): # pragma: no cover
transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number
return transaction
resource, response = ret
transaction.resource = resource
transaction.response = response
if transaction.response.code is None:
transaction.response.code = defines.Codes.CONTENT.number
return transaction
else:
raise NotImplementedError
except NotImplementedError:
transaction.response.code = defines.Codes.METHOD_NOT_ALLOWED.number
return transaction
if isinstance(resource, Resource):
pass
elif isinstance(resource, tuple) and len(resource) == 2:
resource, callback = resource
resource = self._handle_separate(transaction, callback)
if not isinstance(resource, Resource): # pragma: no cover
transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number
return transaction
else: # pragma: no cover
# Handle error
transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number
return transaction.response
if resource.etag in transaction.request.etag:
transaction.response.code = defines.Codes.VALID.number
else:
transaction.response.code = defines.Codes.CONTENT.number
try:
transaction.response.payload = resource.payload
if resource.actual_content_type is not None \
and resource.actual_content_type != defines.Content_types["text/plain"]:
transaction.response.content_type = resource.actual_content_type
except KeyError:
transaction.response.code = defines.Codes.NOT_ACCEPTABLE.number
return transaction.response
assert(isinstance(resource, Resource))
if resource.etag is not None:
transaction.response.etag = resource.etag
if resource.max_age is not None:
transaction.response.max_age = resource.max_age
transaction.resource = resource
return transaction | def get_resource(self, transaction) | Render a GET request.
:param transaction: the transaction
:return: the transaction | 2.304199 | 2.29152 | 1.005533 |
transaction.response.code = defines.Codes.CONTENT.number
payload = ""
for i in self._parent.root.dump():
if i == "/":
continue
resource = self._parent.root[i]
if resource.visible:
ret = self.valid(transaction.request.uri_query, resource.attributes)
if ret:
payload += self.corelinkformat(resource)
transaction.response.payload = payload
transaction.response.content_type = defines.Content_types["application/link-format"]
return transaction | def discover(self, transaction) | Render a GET request to the .well-know/core link.
:param transaction: the transaction
:return: the transaction | 6.277687 | 6.452613 | 0.972891 |
msg = "<" + resource.path + ">;"
assert(isinstance(resource, Resource))
keys = sorted(list(resource.attributes.keys()))
for k in keys:
method = getattr(resource, defines.corelinkformat[k], None)
if method is not None and method != "":
v = method
msg = msg[:-1] + ";" + str(v) + ","
else:
v = resource.attributes[k]
if v is not None:
msg = msg[:-1] + ";" + k + "=" + v + ","
return msg | def corelinkformat(resource) | Return a formatted string representation of the corelinkformat in the tree.
:return: the string | 4.171021 | 4.058115 | 1.027822 |
method = transaction.request.code
if method == defines.Codes.GET.number:
transaction = self._handle_get(transaction)
elif method == defines.Codes.POST.number:
transaction = self._handle_post(transaction)
elif method == defines.Codes.PUT.number:
transaction = self._handle_put(transaction)
elif method == defines.Codes.DELETE.number:
transaction = self._handle_delete(transaction)
else:
transaction.response = None
return transaction | def receive_request(self, transaction) | Handle request and execute the requested method
:type transaction: Transaction
:param transaction: the transaction that owns the request
:rtype : Transaction
:return: the edited transaction with the response to the request | 2.090988 | 2.272116 | 0.920282 |
path = str("/" + transaction.request.uri_path)
transaction.response = Response()
transaction.response.destination = transaction.request.source
transaction.response.token = transaction.request.token
if path == defines.DISCOVERY_URL:
transaction = self._server.resourceLayer.discover(transaction)
else:
try:
resource = self._server.root[path]
except KeyError:
resource = None
if resource is None or path == '/':
# Not Found
transaction.response.code = defines.Codes.NOT_FOUND.number
else:
transaction.resource = resource
transaction = self._server.resourceLayer.get_resource(transaction)
return transaction | def _handle_get(self, transaction) | Handle GET requests
:type transaction: Transaction
:param transaction: the transaction that owns the request
:rtype : Transaction
:return: the edited transaction with the response to the request | 4.604246 | 4.664963 | 0.986984 |
path = str("/" + transaction.request.uri_path)
transaction.response = Response()
transaction.response.destination = transaction.request.source
transaction.response.token = transaction.request.token
# Create request
transaction = self._server.resourceLayer.create_resource(path, transaction)
return transaction | def _handle_post(self, transaction) | Handle POST requests
:type transaction: Transaction
:param transaction: the transaction that owns the request
:rtype : Transaction
:return: the edited transaction with the response to the request | 8.528443 | 8.377947 | 1.017963 |
path = str("/" + transaction.request.uri_path)
transaction.response = Response()
transaction.response.destination = transaction.request.source
transaction.response.token = transaction.request.token
try:
resource = self._server.root[path]
except KeyError:
resource = None
if resource is None:
transaction.response.code = defines.Codes.NOT_FOUND.number
else:
# Delete
transaction.resource = resource
transaction = self._server.resourceLayer.delete_resource(transaction, path)
return transaction | def _handle_delete(self, transaction) | Handle DELETE requests
:type transaction: Transaction
:param transaction: the transaction that owns the request
:rtype : Transaction
:return: the edited transaction with the response to the request | 5.119782 | 5.085519 | 1.006737 |
value = []
for option in self.options:
if option.number == defines.OptionRegistry.URI_PATH.number:
value.append(str(option.value) + '/')
value = "".join(value)
value = value[:-1]
return value | def uri_path(self) | Return the Uri-Path of a request
:rtype : String
:return: the Uri-Path | 5.943067 | 6.117465 | 0.971492 |
path = path.strip("/")
tmp = path.split("?")
path = tmp[0]
paths = path.split("/")
for p in paths:
option = Option()
option.number = defines.OptionRegistry.URI_PATH.number
option.value = p
self.add_option(option)
if len(tmp) > 1:
query = tmp[1]
self.uri_query = query | def uri_path(self, path) | Set the Uri-Path of a request.
:param path: the Uri-Path | 3.793401 | 4.481987 | 0.846366 |
value = []
for option in self.options:
if option.number == defines.OptionRegistry.URI_QUERY.number:
value.append(str(option.value))
return "&".join(value) | def uri_query(self) | Get the Uri-Query of a request.
:return: the Uri-Query
:rtype : String
:return: the Uri-Query string | 6.16389 | 6.85461 | 0.899233 |
del self.uri_query
queries = value.split("&")
for q in queries:
option = Option()
option.number = defines.OptionRegistry.URI_QUERY.number
option.value = str(q)
self.add_option(option) | def uri_query(self, value) | Adds a query.
:param value: the query | 6.452616 | 7.790238 | 0.828295 |
for option in self.options:
if option.number == defines.OptionRegistry.ACCEPT.number:
return option.value
return None | def accept(self) | Get the Accept option of a request.
:return: the Accept value or None if not specified by the request
:rtype : String | 11.88008 | 8.090392 | 1.468418 |
if value in list(defines.Content_types.values()):
option = Option()
option.number = defines.OptionRegistry.ACCEPT.number
option.value = value
self.add_option(option) | def accept(self, value) | Add an Accept option to a request.
:param value: the Accept value | 10.618603 | 8.740322 | 1.214898 |
value = []
for option in self.options:
if option.number == defines.OptionRegistry.IF_MATCH.number:
value.append(option.value)
return value | def if_match(self) | Get the If-Match option of a request.
:return: the If-Match values or [] if not specified by the request
:rtype : list | 7.013741 | 6.26692 | 1.119169 |
assert isinstance(values, list)
for v in values:
option = Option()
option.number = defines.OptionRegistry.IF_MATCH.number
option.value = v
self.add_option(option) | def if_match(self, values) | Set the If-Match option of a request.
:param values: the If-Match values
:type values : list | 5.836087 | 5.617573 | 1.038898 |
for option in self.options:
if option.number == defines.OptionRegistry.IF_NONE_MATCH.number:
return True
return False | def if_none_match(self) | Get the if-none-match option of a request.
:return: True, if if-none-match is present
:rtype : bool | 7.691664 | 6.390321 | 1.203643 |
option = Option()
option.number = defines.OptionRegistry.IF_NONE_MATCH.number
option.value = None
self.add_option(option) | def add_if_none_match(self) | Add the if-none-match option to the request. | 8.598584 | 5.627993 | 1.527824 |
option = Option()
option.number = defines.OptionRegistry.NO_RESPONSE.number
option.value = 26
self.add_option(option) | def add_no_response(self) | Add the no-response option to the request
# https://tools.ietf.org/html/rfc7967#section-2.1 | 10.356344 | 4.881662 | 2.121479 |
for option in self.options:
if option.number == defines.OptionRegistry.PROXY_URI.number:
return option.value
return None | def proxy_uri(self) | Get the Proxy-Uri option of a request.
:return: the Proxy-Uri values or None if not specified by the request
:rtype : String | 8.796805 | 6.518116 | 1.349593 |
option = Option()
option.number = defines.OptionRegistry.PROXY_URI.number
option.value = str(value)
self.add_option(option) | def proxy_uri(self, value) | Set the Proxy-Uri option of a request.
:param value: the Proxy-Uri value | 7.402298 | 8.75017 | 0.845961 |
for option in self.options:
if option.number == defines.OptionRegistry.PROXY_SCHEME.number:
return option.value
return None | def proxy_schema(self) | Get the Proxy-Schema option of a request.
:return: the Proxy-Schema values or None if not specified by the request
:rtype : String | 9.957039 | 7.023567 | 1.417661 |
option = Option()
option.number = defines.OptionRegistry.PROXY_SCHEME.number
option.value = str(value)
self.add_option(option) | def proxy_schema(self, value) | Set the Proxy-Schema option of a request.
:param value: the Proxy-Schema value | 8.370135 | 8.825597 | 0.948393 |
logger.debug("adding response to the cache")
code = response.code
try:
utils.check_code(code)
except utils.InvalidResponseCode: # pragma no cover
logger.error("Invalid response code")
return
if response.max_age == 0:
return
if self.mode == defines.FORWARD_PROXY:
new_key = CacheKey(request)
else:
new_key = ReverseCacheKey(request)
logger.debug("MaxAge = {maxage}".format(maxage=response.max_age))
new_element = CacheElement(new_key, response, request, response.max_age)
self.cache.update(new_key, new_element)
logger.debug("Cache Size = {size}".format(size=self.cache.debug_print())) | def cache_add(self, request, response) | checks for full cache and valid code before updating the cache
:param request:
:param response:
:return: | 4.887553 | 4.82794 | 1.012347 |
logger.debug("Cache Search Request")
if self.cache.is_empty() is True:
logger.debug("Empty Cache")
return None
result = []
items = list(self.cache.cache.items())
for key, item in items:
element = self.cache.get(item.key)
logger.debug("Element : {elm}".format(elm=str(element)))
if request.proxy_uri == element.uri:
result.append(item)
return result | def search_related(self, request) | extracting everything from the cache | 5.546809 | 5.090212 | 1.089701 |
logger.debug("Cache Search Response")
if self.cache.is_empty() is True:
logger.debug("Empty Cache")
return None
if self.mode == defines.FORWARD_PROXY:
search_key = CacheKey(request)
else:
search_key = ReverseCacheKey(request)
response = self.cache.get(search_key)
return response | def search_response(self, request) | creates a key from the request and searches the cache with it
:param request:
:return CacheElement: returns None if there's a cache miss | 5.640578 | 5.277971 | 1.068702 |
element = self.search_response(request)
if element is not None:
element.cached_response.options = response.options
element.freshness = True
element.max_age = response.max_age
element.creation_time = time.time()
element.uri = request.proxy_uri | def validate(self, request, response) | refreshes a resource when a validation response is received
:param request:
:param response:
:return: | 6.868405 | 6.578605 | 1.044052 |
logger.debug("Element : {elm}".format(elm=str(element)))
if element is not None:
logger.debug("Mark as not fresh")
element.freshness = False
logger.debug(str(self.cache)) | def mark(self, element) | marks the requested resource in the cache as not fresh
:param element:
:return: | 6.679906 | 5.450316 | 1.2256 |
uri = transaction.request.proxy_uri
if uri is None:
transaction.response = Response()
transaction.response.destination = transaction.request.source
transaction.response.token = transaction.request.token
transaction.response.type = defines.Types["RST"]
transaction.response.code = defines.Codes.BAD_REQUEST.number
return transaction
host, port, path = parse_uri(uri)
path = str("/" + path)
transaction.response = Response()
transaction.response.destination = transaction.request.source
transaction.response.token = transaction.request.token
return self._forward_request(transaction, (host, port), path) | def receive_request(self, transaction) | Setup the transaction for forwarding purposes on Forward Proxies.
:type transaction: Transaction
:param transaction: the transaction that owns the request
:rtype : Transaction
:return: the edited transaction | 3.495136 | 3.44561 | 1.014374 |
path = str("/" + transaction.request.uri_path)
transaction.response = Response()
transaction.response.destination = transaction.request.source
transaction.response.token = transaction.request.token
if path == defines.DISCOVERY_URL:
transaction = self._server.resourceLayer.discover(transaction)
else:
new = False
if transaction.request.code == defines.Codes.POST.number:
new_paths = self._server.root.with_prefix(path)
new_path = "/"
for tmp in new_paths:
if len(tmp) > len(new_path):
new_path = tmp
if path != new_path:
new = True
path = new_path
try:
resource = self._server.root[path]
except KeyError:
resource = None
if resource is None or path == '/':
# Not Found
transaction.response.code = defines.Codes.NOT_FOUND.number
else:
transaction.resource = resource
transaction = self._handle_request(transaction, new)
return transaction | def receive_request_reverse(self, transaction) | Setup the transaction for forwarding purposes on Reverse Proxies.
:type transaction: Transaction
:param transaction: the transaction that owns the request
:rtype : Transaction
:return: the edited transaction | 4.047606 | 4.189165 | 0.966208 |
client = HelperClient(destination)
request = Request()
request.options = copy.deepcopy(transaction.request.options)
del request.block2
del request.block1
del request.uri_path
del request.proxy_uri
del request.proxy_schema
# TODO handle observing
del request.observe
# request.observe = transaction.request.observe
request.uri_path = path
request.destination = destination
request.payload = transaction.request.payload
request.code = transaction.request.code
response = client.send_request(request)
client.stop()
if response is not None:
transaction.response.payload = response.payload
transaction.response.code = response.code
transaction.response.options = response.options
else:
transaction.response.code = defines.Codes.SERVICE_UNAVAILABLE.number
return transaction | def _forward_request(transaction, destination, path) | Forward requests.
:type transaction: Transaction
:param transaction: the transaction that owns the request
:param destination: the destination of the request (IP, port)
:param path: the path of the request.
:rtype : Transaction
:return: the edited transaction | 3.857952 | 4.046311 | 0.953449 |
client = HelperClient(transaction.resource.remote_server)
request = Request()
request.options = copy.deepcopy(transaction.request.options)
del request.block2
del request.block1
del request.uri_path
del request.proxy_uri
del request.proxy_schema
# TODO handle observing
del request.observe
# request.observe = transaction.request.observe
request.uri_path = "/".join(transaction.request.uri_path.split("/")[1:])
request.destination = transaction.resource.remote_server
request.payload = transaction.request.payload
request.code = transaction.request.code
response = client.send_request(request)
client.stop()
transaction.response.payload = response.payload
transaction.response.code = response.code
transaction.response.options = response.options
if response.code == defines.Codes.CREATED.number:
lp = transaction.response.location_path
del transaction.response.location_path
transaction.response.location_path = transaction.request.uri_path.split("/")[0] + "/" + lp
# TODO handle observing
if new_resource:
resource = RemoteResource('server', transaction.resource.remote_server, lp, coap_server=self,
visible=True,
observable=False,
allow_children=True)
self._server.add_resource(transaction.response.location_path, resource)
if response.code == defines.Codes.DELETED.number:
del self._server.root["/" + transaction.request.uri_path]
return transaction | def _handle_request(self, transaction, new_resource) | Forward requests. Used by reverse proxies to also create new virtual resources on the proxy
in case of created resources
:type new_resource: bool
:type transaction: Transaction
:param transaction: the transaction that owns the request
:rtype : Transaction
:param new_resource: if the request will generate a new resource
:return: the edited transaction | 3.836679 | 3.796573 | 1.010564 |
self.stopped.set()
for event in self.to_be_stopped:
event.set()
if self._receiver_thread is not None:
self._receiver_thread.join()
self._socket.close() | def close(self) | Stop the client. | 4.240519 | 3.607328 | 1.175529 |
if isinstance(message, Request):
request = self._requestLayer.send_request(message)
request = self._observeLayer.send_request(request)
request = self._blockLayer.send_request(request)
transaction = self._messageLayer.send_request(request)
self.send_datagram(transaction.request)
if transaction.request.type == defines.Types["CON"]:
self._start_retransmission(transaction, transaction.request)
elif isinstance(message, Message):
message = self._observeLayer.send_empty(message)
message = self._messageLayer.send_empty(None, None, message)
self.send_datagram(message) | def send_message(self, message) | Prepare a message to send on the UDP socket. Eventually set retransmissions.
:param message: the message to send | 4.307199 | 4.280469 | 1.006245 |
if hasattr(transaction, 'retransmit_thread'):
while transaction.retransmit_thread is not None:
logger.debug("Waiting for retransmit thread to finish ...")
time.sleep(0.01)
continue | def _wait_for_retransmit_thread(transaction) | Only one retransmit thread at a time, wait for other to finish | 3.180493 | 2.800999 | 1.135485 |
transaction = self._messageLayer.send_request(transaction.request)
# ... but don't forget to reset the acknowledge flag
transaction.request.acknowledged = False
self.send_datagram(transaction.request)
if transaction.request.type == defines.Types["CON"]:
self._start_retransmission(transaction, transaction.request) | def _send_block_request(self, transaction) | A former request resulted in a block wise transfer. With this method, the block wise transfer
will be continued, including triggering of the retry mechanism.
:param transaction: The former transaction including the request which should be continued. | 8.711932 | 8.652674 | 1.006849 |
host, port = message.destination
logger.debug("send_datagram - " + str(message))
serializer = Serializer()
raw_message = serializer.serialize(message)
try:
self._socket.sendto(raw_message, (host, port))
except Exception as e:
if self._cb_ignore_write_exception is not None and isinstance(self._cb_ignore_write_exception, collections.Callable):
if not self._cb_ignore_write_exception(e, self):
raise
# if you're explicitly setting that you don't want a response, don't wait for it
# https://tools.ietf.org/html/rfc7967#section-2.1
for opt in message.options:
if opt.number == defines.OptionRegistry.NO_RESPONSE.number:
if opt.value == 26:
return
if self._receiver_thread is None or not self._receiver_thread.isAlive():
self._receiver_thread = threading.Thread(target=self.receive_datagram)
self._receiver_thread.daemon = True
self._receiver_thread.start() | def send_datagram(self, message) | Send a message over the UDP socket.
:param message: the message to send | 3.640024 | 3.803626 | 0.956988 |
with transaction:
if message.type == defines.Types['CON']:
future_time = random.uniform(defines.ACK_TIMEOUT, (defines.ACK_TIMEOUT * defines.ACK_RANDOM_FACTOR))
transaction.retransmit_stop = threading.Event()
self.to_be_stopped.append(transaction.retransmit_stop)
transaction.retransmit_thread = threading.Thread(target=self._retransmit,
name=str('%s-Retry-%d' % (threading.current_thread().name, message.mid)),
args=(transaction, message, future_time, 0))
transaction.retransmit_thread.start() | def _start_retransmission(self, transaction, message) | Start the retransmission task.
:type transaction: Transaction
:param transaction: the transaction that owns the message that needs retransmission
:type message: Message
:param message: the message that needs the retransmission task | 4.223655 | 4.743881 | 0.890337 |
logger.debug("Start receiver Thread")
while not self.stopped.isSet():
self._socket.settimeout(0.1)
try:
datagram, addr = self._socket.recvfrom(1152)
except socket.timeout: # pragma: no cover
continue
except Exception as e: # pragma: no cover
if self._cb_ignore_read_exception is not None and isinstance(self._cb_ignore_read_exception, collections.Callable):
if self._cb_ignore_read_exception(e, self):
continue
return
else: # pragma: no cover
if len(datagram) == 0:
logger.debug("Exiting receiver Thread due to orderly shutdown on server end")
return
serializer = Serializer()
try:
host, port = addr
except ValueError:
host, port, tmp1, tmp2 = addr
source = (host, port)
message = serializer.deserialize(datagram, source)
if isinstance(message, Response):
logger.debug("receive_datagram - " + str(message))
transaction, send_ack = self._messageLayer.receive_response(message)
if transaction is None: # pragma: no cover
continue
self._wait_for_retransmit_thread(transaction)
if send_ack:
self._send_ack(transaction)
self._blockLayer.receive_response(transaction)
if transaction.block_transfer:
self._send_block_request(transaction)
continue
elif transaction is None: # pragma: no cover
self._send_rst(transaction)
return
self._observeLayer.receive_response(transaction)
if transaction.notification: # pragma: no cover
ack = Message()
ack.type = defines.Types['ACK']
ack = self._messageLayer.send_empty(transaction, transaction.response, ack)
self.send_datagram(ack)
self._callback(transaction.response)
else:
self._callback(transaction.response)
elif isinstance(message, Message):
self._messageLayer.receive_empty(message)
logger.debug("Exiting receiver Thread due to request") | def receive_datagram(self) | Receive datagram from the UDP socket and invoke the callback function. | 3.802494 | 3.813769 | 0.997044 |
rst = self._messageLayer.send_empty(transaction, transaction.response, rst)
self.send_datagram(rst) | def _send_rst(self, transaction): # pragma: no cover
rst = Message()
rst.type = defines.Types['RST']
if not transaction.response.acknowledged | Sends an RST message for the response.
:param transaction: transaction that holds the response | 27.267845 | 24.018335 | 1.135293 |
transaction.cached_element = self.cache.search_response(transaction.request)
if transaction.cached_element is None:
transaction.cacheHit = False
else:
transaction.response = transaction.cached_element.cached_response
transaction.response.mid = transaction.request.mid
transaction.cacheHit = True
age = transaction.cached_element.creation_time + transaction.cached_element.max_age - time.time()
if transaction.cached_element.freshness is True:
if age <= 0:
logger.debug("resource not fresh")
transaction.cached_element.freshness = False
transaction.cacheHit = False
logger.debug("requesting etag %s", transaction.response.etag)
transaction.request.etag = transaction.response.etag
else:
transaction.response.max_age = age
else:
transaction.cacheHit = False
return transaction | def receive_request(self, transaction) | checks the cache for a response to the request
:param transaction:
:return: | 3.758017 | 3.697201 | 1.016449 |
if transaction.cacheHit is False:
logger.debug("handling response")
self._handle_response(transaction)
return transaction | def send_response(self, transaction) | updates the cache with the response if there was a cache miss
:param transaction:
:return: | 13.908948 | 14.343939 | 0.969674 |
code = transaction.response.code
utils.check_code(code)
if code == Codes.VALID.number:
logger.debug("received VALID")
self.cache.validate(transaction.request, transaction.response)
if transaction.request.etag != transaction.response.etag:
element = self.cache.search_response(transaction.request)
transaction.response = element.cached_response
return transaction
if code == Codes.CHANGED.number or code == Codes.CREATED.number or code == Codes.DELETED.number:
target = self.cache.search_related(transaction.request)
if target is not None:
for element in target:
self.cache.mark(element)
return transaction
self.cache.cache_add(transaction.request, transaction.response)
return transaction | def _handle_response(self, transaction) | handles responses based on their type
:param transaction:
:return: | 4.487976 | 4.533123 | 0.99004 |
if not isinstance(v, int) or v != 1:
raise AttributeError
self._version = v | def version(self, v) | Sets the CoAP version
:param v: the version
:raise AttributeError: if value is not 1 | 6.167691 | 5.23898 | 1.17727 |
if value not in list(defines.Types.values()):
raise AttributeError
self._type = value | def type(self, value) | Sets the type of the message.
:type value: Types
:param value: the type
:raise AttributeError: if value is not a valid type | 10.457231 | 11.560189 | 0.90459 |
if not isinstance(value, int) or value > 65536:
raise AttributeError
self._mid = value | def mid(self, value) | Sets the MID of the message.
:type value: Integer
:param value: the MID
:raise AttributeError: if value is not int or cannot be represented on 16 bits. | 4.960511 | 4.133266 | 1.200143 |
if value is None:
self._token = value
return
if not isinstance(value, str):
value = str(value)
if len(value) > 256:
raise AttributeError
self._token = value | def token(self, value) | Set the Token of the message.
:type value: String
:param value: the Token
:raise AttributeError: if value is longer than 256 | 2.883461 | 2.504121 | 1.151487 |
if value is None:
value = []
assert isinstance(value, list)
self._options = value | def options(self, value) | Set the options of the CoAP message.
:type value: list
:param value: list of options | 3.580727 | 5.696258 | 0.62861 |
if isinstance(value, tuple):
content_type, payload = value
self.content_type = content_type
self._payload = payload
else:
self._payload = value | def payload(self, value) | Sets the payload of the message and eventually the Content-Type
:param value: the payload | 3.002303 | 3.23989 | 0.926668 |
if value is not None and (not isinstance(value, tuple) or len(value)) != 2:
raise AttributeError
self._destination = value | def destination(self, value) | Set the destination of the message.
:type value: tuple
:param value: (ip, port)
:raise AttributeError: if value is not a ip and a port. | 4.261695 | 3.975344 | 1.072032 |
if not isinstance(value, tuple) or len(value) != 2:
raise AttributeError
self._source = value | def source(self, value) | Set the source of the message.
:type value: tuple
:param value: (ip, port)
:raise AttributeError: if value is not a ip and a port. | 3.741504 | 3.575059 | 1.046557 |
if value not in list(defines.Codes.LIST.keys()) and value is not None:
raise AttributeError
self._code = value | def code(self, value) | Set the code of the message.
:type value: Codes
:param value: the code
:raise AttributeError: if value is not a valid code | 10.504844 | 10.309908 | 1.018908 |
assert (isinstance(value, bool))
self._acknowledged = value
if value:
self._timeouted = False
self._rejected = False
self._cancelled = False | def acknowledged(self, value) | Marks this message as acknowledged.
:type value: Boolean
:param value: if acknowledged | 4.42725 | 6.132471 | 0.721936 |
assert (isinstance(value, bool))
self._rejected = value
if value:
self._timeouted = False
self._acknowledged = False
self._cancelled = True | def rejected(self, value) | Marks this message as rejected.
:type value: Boolean
:param value: if rejected | 5.283177 | 6.647687 | 0.794739 |
for opt in self._options:
if option.number == opt.number:
return True
return False | def _already_in(self, option) | Check if an option is already in the message.
:type option: Option
:param option: the option to be checked
:return: True if already present, False otherwise | 4.744485 | 5.580566 | 0.85018 |
assert isinstance(option, Option)
repeatable = defines.OptionRegistry.LIST[option.number].repeatable
if not repeatable:
ret = self._already_in(option)
if ret:
raise TypeError("Option : %s is not repeatable", option.name)
else:
self._options.append(option)
else:
self._options.append(option) | def add_option(self, option) | Add an option to the message.
:type option: Option
:param option: the option
:raise TypeError: if the option is not repeatable and such option is already present in the message | 6.135251 | 5.494078 | 1.116703 |
assert isinstance(option, Option)
while option in list(self._options):
self._options.remove(option) | def del_option(self, option) | Delete an option from the message
:type option: Option
:param option: the option | 4.749214 | 6.50011 | 0.730636 |
for o in list(self._options):
assert isinstance(o, Option)
if o.name == name:
self._options.remove(o) | def del_option_by_name(self, name) | Delete an option from the message by name
:type name: String
:param name: option name | 3.223292 | 4.671237 | 0.69003 |
for o in list(self._options):
assert isinstance(o, Option)
if o.number == number:
self._options.remove(o) | def del_option_by_number(self, number) | Delete an option from the message by number
:type number: Integer
:param number: option naumber | 3.233671 | 4.51053 | 0.716916 |
value = []
for option in self.options:
if option.number == defines.OptionRegistry.ETAG.number:
value.append(option.value)
return value | def etag(self) | Get the ETag option of the message.
:rtype: list
:return: the ETag values or [] if not specified by the request | 7.684258 | 6.37216 | 1.205911 |
if not isinstance(etag, list):
etag = [etag]
for e in etag:
option = Option()
option.number = defines.OptionRegistry.ETAG.number
if not isinstance(e, bytes):
e = bytes(e, "utf-8")
option.value = e
self.add_option(option) | def etag(self, etag) | Add an ETag option to the message.
:param etag: the etag | 4.197782 | 4.116906 | 1.019645 |
value = 0
for option in self.options:
if option.number == defines.OptionRegistry.CONTENT_TYPE.number:
value = int(option.value)
return value | def content_type(self) | Get the Content-Type option of a response.
:return: the Content-Type value or 0 if not specified by the response | 7.23156 | 6.796185 | 1.064062 |
option = Option()
option.number = defines.OptionRegistry.CONTENT_TYPE.number
option.value = int(content_type)
self.add_option(option) | def content_type(self, content_type) | Set the Content-Type option of a response.
:type content_type: int
:param content_type: the Content-Type | 6.939639 | 10.430249 | 0.665338 |
for option in self.options:
if option.number == defines.OptionRegistry.OBSERVE.number:
# if option.value is None:
# return 0
if option.value is None:
return 0
return option.value
return None | def observe(self) | Check if the request is an observing request.
:return: 0, if the request is an observing request | 6.647455 | 6.573755 | 1.011211 |
option = Option()
option.number = defines.OptionRegistry.OBSERVE.number
option.value = ob
self.del_option_by_number(defines.OptionRegistry.OBSERVE.number)
self.add_option(option) | def observe(self, ob) | Add the Observe option.
:param ob: observe count | 5.431729 | 5.379235 | 1.009759 |
value = None
for option in self.options:
if option.number == defines.OptionRegistry.BLOCK1.number:
value = parse_blockwise(option.value)
return value | def block1(self) | Get the Block1 option.
:return: the Block1 value | 11.152809 | 9.172132 | 1.215945 |
option = Option()
option.number = defines.OptionRegistry.BLOCK1.number
num, m, size = value
if size > 512:
szx = 6
elif 256 < size <= 512:
szx = 5
elif 128 < size <= 256:
szx = 4
elif 64 < size <= 128:
szx = 3
elif 32 < size <= 64:
szx = 2
elif 16 < size <= 32:
szx = 1
else:
szx = 0
value = (num << 4)
value |= (m << 3)
value |= szx
option.value = value
self.add_option(option) | def block1(self, value) | Set the Block1 option.
:param value: the Block1 value | 2.73615 | 2.835527 | 0.964953 |
value = None
for option in self.options:
if option.number == defines.OptionRegistry.BLOCK2.number:
value = parse_blockwise(option.value)
return value | def block2(self) | Get the Block2 option.
:return: the Block2 value | 11.047651 | 9.157412 | 1.206416 |
option = Option()
option.number = defines.OptionRegistry.BLOCK2.number
num, m, size = value
if size > 512:
szx = 6
elif 256 < size <= 512:
szx = 5
elif 128 < size <= 256:
szx = 4
elif 64 < size <= 128:
szx = 3
elif 32 < size <= 64:
szx = 2
elif 16 < size <= 32:
szx = 1
else:
szx = 0
value = (num << 4)
value |= (m << 3)
value |= szx
option.value = value
self.add_option(option) | def block2(self, value) | Set the Block2 option.
:param value: the Block2 value | 2.741411 | 2.819425 | 0.97233 |
inv_types = {v: k for k, v in defines.Types.items()}
if self._code is None:
self._code = defines.Codes.EMPTY.number
msg = "From {source}, To {destination}, {type}-{mid}, {code}-{token}, ["\
.format(source=self._source, destination=self._destination, type=inv_types[self._type], mid=self._mid,
code=defines.Codes.LIST[self._code].name, token=self._token)
for opt in self._options:
msg += "{name}: {value}, ".format(name=opt.name, value=opt.value)
msg += "]"
if self.payload is not None:
if isinstance(self.payload, dict):
tmp = list(self.payload.values())[0][0:20]
else:
tmp = self.payload[0:20]
msg += " {payload}...{length} bytes".format(payload=tmp, length=len(self.payload))
else:
msg += " No payload"
return msg | def line_print(self) | Return the message as a one-line string.
:return: the string representing the message | 3.618402 | 3.513862 | 1.029751 |
msg = "Source: " + str(self._source) + "\n"
msg += "Destination: " + str(self._destination) + "\n"
inv_types = {v: k for k, v in defines.Types.items()}
msg += "Type: " + str(inv_types[self._type]) + "\n"
msg += "MID: " + str(self._mid) + "\n"
if self._code is None:
self._code = 0
msg += "Code: " + str(defines.Codes.LIST[self._code].name) + "\n"
msg += "Token: " + str(self._token) + "\n"
for opt in self._options:
msg += str(opt)
msg += "Payload: " + "\n"
msg += str(self._payload) + "\n"
return msg | def pretty_print(self) | Return the message as a formatted string.
:return: the string representing the message | 2.67163 | 2.701841 | 0.988818 |
# Calculate the distance to each vertex
val = 0
norm = 0
for i in range(8):
# Inv distance, or Inv-dsq weighting
distance = sqrt((x-box[i,0])**2 + (y-box[i,1])**2 + (z-box[i, 2])**2)
# If you happen to land on exactly a corner, you're done.
if distance == 0:
val = values[i]
norm = 1.
break
w = 1./distance
# w = 1./((x-box[i,0])*(x-box[i,0]) +
# (y-box[i,1])*(y-box[i,1]) +
# (z-box[i, 2])*(z-box[i, 2]))
val += w * values[i]
norm += w
return val/norm | def interp_box(x, y, z, box, values) | box is 8x3 array, though not really a box
values is length-8 array, corresponding to values at the "box" coords
TODO: should make power `p` an argument | 3.280008 | 3.216794 | 1.019651 |
X,Y,Z = cls._get_XYZ(filename)
Xsun = 0.703812
Zsun = 0.016188
return np.log10((Z/X) / (Zsun/Xsun)) | def get_feh(cls, filename) | example filename: yapsi_w_X0p602357_Z0p027643.dat | 6.425564 | 5.564081 | 1.154829 |
if brightest:
row = self.brightest
else:
row = self.closest
if not hasattr(self, 'conversions'):
convert = False
if convert:
bands = self.conversions
else:
bands = self.bands.keys()
d = {}
for b in bands:
if convert:
key = b
mag, dmag = getattr(self, b)(brightest=brightest)
else:
key = self.bands[b]
mag, dmag = row[b], row['e_{}'.format(b)]
d[key] = mag, max(dmag, min_unc)
return d | def get_photometry(self, brightest=False,
min_unc=0.02, convert=True) | Returns dictionary of photometry of closest match
unless brightest is True, in which case the brightest match. | 3.304675 | 3.338601 | 0.989838 |
if isinstance(models, Isochrone):
return models
def actual(bands, ictype):
if bands is None:
return list(ictype.default_bands)
elif default:
return list(set(bands).union(set(ictype.default_bands)))
else:
return bands
if type(models) is type(type):
ichrone = models(actual(bands, models))
elif models=='dartmouth':
from isochrones.dartmouth import Dartmouth_Isochrone
ichrone = Dartmouth_Isochrone(bands=actual(bands, Dartmouth_Isochrone), **kwargs)
elif models=='dartmouthfast':
from isochrones.dartmouth import Dartmouth_FastIsochrone
ichrone = Dartmouth_FastIsochrone(bands=actual(bands, Dartmouth_FastIsochrone), **kwargs)
elif models=='mist':
from isochrones.mist import MIST_Isochrone
ichrone = MIST_Isochrone(bands=actual(bands, MIST_Isochrone), **kwargs)
elif models=='padova':
from isochrones.padova import Padova_Isochrone
ichrone = Padova_Isochrone(bands=actual(bands, Padova_Isochrone), **kwargs)
elif models=='basti':
from isochrones.basti import Basti_Isochrone
ichrone = Basti_Isochrone(bands=actual(bands, Basti_Isochrone), **kwargs)
else:
raise ValueError('Unknown stellar models: {}'.format(models))
return ichrone | def get_ichrone(models, bands=None, default=False, **kwargs) | Gets Isochrone Object by name, or type, with the right bands
If `default` is `True`, then will set bands
to be the union of bands and default_bands | 2.005683 | 1.950597 | 1.02824 |
M = self.mass(*args) * MSUN
V = 4./3 * np.pi * (self.radius(*args) * RSUN)**3
return M/V | def density(self, *args) | Mean density in g/cc | 6.933044 | 5.975614 | 1.160223 |
return 134.88 * np.sqrt(self.mass(*args) / self.radius(*args)**3) | def delta_nu(self, *args) | Returns asteroseismic delta_nu in uHz
reference: https://arxiv.org/pdf/1312.3853v1.pdf, Eq (2) | 9.934236 | 8.553513 | 1.161422 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.