INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Internal coroutine for receiving messages | def _receive_message(self):
"""
Internal coroutine for receiving messages
"""
while True:
try:
if self._socket.getsockopt(zmq.TYPE) == zmq.ROUTER:
zmq_identity, msg_bytes = \
yield from self._socket.recv_multipart()
... |
Should be used instead of send_message, when you want to close the
connection once the message is sent.
:param msg: protobuf validator_pb2.Message | def send_last_message(self, msg, connection_id=None):
"""
Should be used instead of send_message, when you want to close the
connection once the message is sent.
:param msg: protobuf validator_pb2.Message
"""
zmq_identity = None
if connection_id is not None and s... |
Setup the asyncio event loop.
Args:
socket_type (int from zmq.*): One of zmq.DEALER or zmq.ROUTER
complete_or_error_queue (queue.Queue): A way to propagate errors
back to the calling thread. Needed since this function is
directly used in Thread.
... | def setup(self, socket_type, complete_or_error_queue):
"""Setup the asyncio event loop.
Args:
socket_type (int from zmq.*): One of zmq.DEALER or zmq.ROUTER
complete_or_error_queue (queue.Queue): A way to propagate errors
back to the calling thread. Needed since t... |
Get stored public key for a connection. | def connection_id_to_public_key(self, connection_id):
"""
Get stored public key for a connection.
"""
with self._connections_lock:
try:
connection_info = self._connections[connection_id]
return connection_info.public_key
except KeyE... |
Get stored connection id for a public key. | def public_key_to_connection_id(self, public_key):
"""
Get stored connection id for a public key.
"""
with self._connections_lock:
for connection_id, connection_info in self._connections.items():
if connection_info.public_key == public_key:
... |
Get status of the connection during Role enforcement. | def get_connection_status(self, connection_id):
"""
Get status of the connection during Role enforcement.
"""
with self._connections_lock:
try:
connection_info = self._connections[connection_id]
return connection_info.status
except ... |
Get stored public key for a connection. | def connection_id_to_endpoint(self, connection_id):
"""
Get stored public key for a connection.
"""
with self._connections_lock:
try:
connection_info = self._connections[connection_id]
return connection_info.uri
except KeyError:
... |
Determines if an additional incoming network connection
should be permitted.
Returns:
bool | def allow_inbound_connection(self):
"""Determines if an additional incoming network connection
should be permitted.
Returns:
bool
"""
LOGGER.debug("Determining whether inbound connection should "
"be allowed. num connections: %s max %s",
... |
Adds an outbound connection to the network.
Args:
uri (str): The zmq-style (e.g. tcp://hostname:port) uri
to attempt to connect to. | def add_outbound_connection(self, uri):
"""Adds an outbound connection to the network.
Args:
uri (str): The zmq-style (e.g. tcp://hostname:port) uri
to attempt to connect to.
"""
LOGGER.debug("Adding connection to %s", uri)
conn = OutboundConnection(
... |
Send ConnectionRequest to an inbound connection. This allows
the validator to be authorized by the incoming connection. | def send_connect_request(self, connection_id):
"""
Send ConnectionRequest to an inbound connection. This allows
the validator to be authorized by the incoming connection.
"""
connect_message = ConnectionRequest(endpoint=self._public_endpoint)
self._safe_send(
... |
Send a message of message_type
:param connection_id: the identity for the connection to send to
:param message_type: validator_pb2.Message.* enum value
:param data: bytes serialized protobuf
:return: future.Future | def send(self, message_type, data, connection_id, callback=None,
one_way=False):
"""
Send a message of message_type
:param connection_id: the identity for the connection to send to
:param message_type: validator_pb2.Message.* enum value
:param data: bytes serialized ... |
Returns the connection id associated with a publically
reachable endpoint or raises KeyError if the endpoint is not
found.
Args:
endpoint (str): A zmq-style uri which identifies a publically
reachable endpoint. | def get_connection_id_by_endpoint(self, endpoint):
"""Returns the connection id associated with a publically
reachable endpoint or raises KeyError if the endpoint is not
found.
Args:
endpoint (str): A zmq-style uri which identifies a publically
reachable endp... |
Adds the endpoint to the connection definition. When the
connection is created by the send/receive thread, we do not
yet have the endpoint of the remote node. That is not known
until we process the incoming ConnectRequest.
Args:
connection_id (str): The identifier for the co... | def update_connection_endpoint(self, connection_id, endpoint):
"""Adds the endpoint to the connection definition. When the
connection is created by the send/receive thread, we do not
yet have the endpoint of the remote node. That is not known
until we process the incoming ConnectRequest.... |
Adds the public_key to the connection definition.
Args:
connection_id (str): The identifier for the connection.
public_key (str): The public key used to enforce permissions on
connections. | def update_connection_public_key(self, connection_id, public_key):
"""Adds the public_key to the connection definition.
Args:
connection_id (str): The identifier for the connection.
public_key (str): The public key used to enforce permissions on
connections.
... |
Sends a message of message_type
Args:
message_type (validator_pb2.Message): enum value
data (bytes): serialized protobuf
callback (function): a callback function to call when a
response to this message is received
Returns:
future.Future | def send(self, message_type, data, callback=None, one_way=False):
"""Sends a message of message_type
Args:
message_type (validator_pb2.Message): enum value
data (bytes): serialized protobuf
callback (function): a callback function to call when a
respo... |
Returns the header of the block | def header(self):
"""
Returns the header of the block
"""
if self._block_header is None:
self._block_header = BlockHeader()
self._block_header.ParseFromString(self.block.header)
return self._block_header |
Returns the state view for an arbitrary block.
Args:
block_wrapper (BlockWrapper): The block for which a state
view is to be returned
state_view_factory (StateViewFactory): The state view factory
used to create the StateView object
Returns:
... | def state_view_for_block(block_wrapper, state_view_factory):
"""
Returns the state view for an arbitrary block.
Args:
block_wrapper (BlockWrapper): The block for which a state
view is to be returned
state_view_factory (StateViewFactory): The state view fa... |
Returns the settings view for an arbitrary block.
Args:
block_wrapper (BlockWrapper): The block for which a settings
view is to be returned
settings_view_factory (SettingsViewFactory): The settings
view factory used to create the SettingsView object
... | def settings_view_for_block(block_wrapper, settings_view_factory):
"""
Returns the settings view for an arbitrary block.
Args:
block_wrapper (BlockWrapper): The block for which a settings
view is to be returned
settings_view_factory (SettingsViewFactory):... |
Anonymize IPv4 and IPv6 :param remote_addr: to /24 (zero'd)
and /48 (zero'd). | def anonymize(remote_addr):
"""
Anonymize IPv4 and IPv6 :param remote_addr: to /24 (zero'd)
and /48 (zero'd).
"""
if not isinstance(remote_addr, text_type) and isinstance(remote_addr, str):
remote_addr = remote_addr.decode('ascii', 'ignore')
try:
ipv4 = ipaddress.IPv4Address(rem... |
Extract <h1> title from web page. The title is *probably* the text node,
which is the nearest H1 node in context to an element with the `isso-thread` id. | def thread(data, default=u"Untitled.", id=None):
"""
Extract <h1> title from web page. The title is *probably* the text node,
which is the nearest H1 node in context to an element with the `isso-thread` id.
"""
html = html5lib.parse(data, treebuilder="dom")
assert html.lastChild.nodeName == "h... |
Process a thread and insert its comments in the DB. | def insert(self, thread):
"""Process a thread and insert its comments in the DB."""
thread_id = thread['id']
title = thread['title']
self.db.threads.new(thread_id, title)
comments = list(map(self._build_comment, thread['comments']))
comments.sort(key=lambda comment: comm... |
Process the input file and fill the DB. | def migrate(self):
"""Process the input file and fill the DB."""
with io.open(self.json_file, 'rt', encoding='utf8') as fh:
threads = json.load(fh)
progress = Progress(len(threads))
for i, thread in enumerate(threads):
progress.update(i, str(i))
self.... |
Add new comment to DB and return a mapping of :attribute:`fields` and
database values. | def add(self, uri, c):
"""
Add new comment to DB and return a mapping of :attribute:`fields` and
database values.
"""
if c.get("parent") is not None:
ref = self.get(c["parent"])
if ref.get("parent") is not None:
c["parent"] = ref["parent"]... |
Turn off email notifications for replies to this comment. | def unsubscribe(self, email, id):
"""
Turn off email notifications for replies to this comment.
"""
self.db.execute([
'UPDATE comments SET',
' notification=0',
'WHERE email=? AND (id=? OR parent=?);'], (email, id, id)) |
Update comment :param:`id` with values from :param:`data` and return
updated comment. | def update(self, id, data):
"""
Update comment :param:`id` with values from :param:`data` and return
updated comment.
"""
self.db.execute([
'UPDATE comments SET',
','.join(key + '=' + '?' for key in data),
'WHERE id=?;'],
list(data.... |
Search for comment :param:`id` and return a mapping of :attr:`fields`
and values. | def get(self, id):
"""
Search for comment :param:`id` and return a mapping of :attr:`fields`
and values.
"""
rv = self.db.execute(
'SELECT * FROM comments WHERE id=?', (id, )).fetchone()
if rv:
return dict(zip(Comments.fields, rv))
return ... |
Return comments for admin with :param:`mode`. | def fetchall(self, mode=5, after=0, parent='any', order_by='id',
limit=100, page=0, asc=1):
"""
Return comments for admin with :param:`mode`.
"""
fields_comments = ['tid', 'id', 'parent', 'created', 'modified',
'mode', 'remote_addr', 'text', 'a... |
Return comments for :param:`uri` with :param:`mode`. | def fetch(self, uri, mode=5, after=0, parent='any',
order_by='id', asc=1, limit=None):
"""
Return comments for :param:`uri` with :param:`mode`.
"""
sql = ['SELECT comments.* FROM comments INNER JOIN threads ON',
' threads.uri=? AND comments.tid=threads.id ... |
Delete a comment. There are two distinctions: a comment is referenced
by another valid comment's parent attribute or stand-a-lone. In this
case the comment can't be removed without losing depending comments.
Hence, delete removes all visible data such as text, author, email,
website sets... | def delete(self, id):
"""
Delete a comment. There are two distinctions: a comment is referenced
by another valid comment's parent attribute or stand-a-lone. In this
case the comment can't be removed without losing depending comments.
Hence, delete removes all visible data such as... |
+1 a given comment. Returns the new like count (may not change because
the creater can't vote on his/her own comment and multiple votes from the
same ip address are ignored as well). | def vote(self, upvote, id, remote_addr):
"""+1 a given comment. Returns the new like count (may not change because
the creater can't vote on his/her own comment and multiple votes from the
same ip address are ignored as well)."""
rv = self.db.execute(
'SELECT likes, dislikes... |
Return comment count for main thread and all reply threads for one url. | def reply_count(self, url, mode=5, after=0):
"""
Return comment count for main thread and all reply threads for one url.
"""
sql = ['SELECT comments.parent,count(*)',
'FROM comments INNER JOIN threads ON',
' threads.uri=? AND comments.tid=threads.id AND',... |
Return comment count for one ore more urls.. | def count(self, *urls):
"""
Return comment count for one ore more urls..
"""
threads = dict(self.db.execute([
'SELECT threads.uri, COUNT(comments.id) FROM comments',
'LEFT OUTER JOIN threads ON threads.id = tid AND comments.mode = 1',
'GROUP BY thread... |
Remove comments older than :param:`delta`. | def purge(self, delta):
"""
Remove comments older than :param:`delta`.
"""
self.db.execute([
'DELETE FROM comments WHERE mode = 2 AND ? - created > ?;'
], (time.time(), delta))
self._remove_stale() |
Parse :param string: into :class:`datetime.timedelta`, you can use any
(logical) combination of Nw, Nd, Nh and Nm, e.g. `1h30m` for 1 hour, 30
minutes or `3w` for 3 weeks.
Raises a ValueError if the input is invalid/unparseable.
>>> print(timedelta("3w"))
21 days, 0:00:00
>>> print(timedelta("... | def timedelta(string):
"""
Parse :param string: into :class:`datetime.timedelta`, you can use any
(logical) combination of Nw, Nd, Nh and Nm, e.g. `1h30m` for 1 hour, 30
minutes or `3w` for 3 weeks.
Raises a ValueError if the input is invalid/unparseable.
>>> print(timedelta("3w"))
21 days... |
Factory to create hash functions from configuration section. If an
algorithm takes custom parameters, you can separate them by a colon like
this: pbkdf2:arg1:arg2:arg3. | def new(conf):
"""Factory to create hash functions from configuration section. If an
algorithm takes custom parameters, you can separate them by a colon like
this: pbkdf2:arg1:arg2:arg3."""
algorithm = conf.get("algorithm")
salt = conf.get("salt").encode("utf-8")
if algorithm == "none":
... |
Calculate hash from value (must be bytes). | def hash(self, val):
"""Calculate hash from value (must be bytes)."""
if not isinstance(val, bytes):
raise _TypeError("val", "bytes", val)
rv = self.compute(val)
if not isinstance(val, bytes):
raise _TypeError("val", "bytes", rv)
return rv |
Calculate hash from unicode value and return hex value as unicode | def uhash(self, val):
"""Calculate hash from unicode value and return hex value as unicode"""
if not isinstance(val, string_types):
raise _TypeError("val", "str", val)
return codecs.encode(self.hash(val.encode("utf-8")), "hex_codec").decode("utf-8") |
A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-url... | def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* appl... |
Decorator to execute each :param func: call in a separate thread. | def threaded(func):
"""
Decorator to execute each :param func: call in a separate thread.
"""
def dec(self, *args, **kwargs):
thread.start_new_thread(func, (self, ) + args, kwargs)
return dec |
Reconstruct host from environment. A modified version
of http://www.python.org/dev/peps/pep-0333/#url-reconstruction | def host(environ): # pragma: no cover
"""
Reconstruct host from environment. A modified version
of http://www.python.org/dev/peps/pep-0333/#url-reconstruction
"""
url = environ['wsgi.url_scheme'] + '://'
if environ.get('HTTP_HOST'):
url += environ['HTTP_HOST']
else:
url +=... |
Parse :param:`name` into (netloc, port, ssl) | def urlsplit(name):
"""
Parse :param:`name` into (netloc, port, ssl)
"""
if not (isinstance(name, string_types)):
name = str(name)
if not name.startswith(('http://', 'https://')):
name = 'http://' + name
rv = urlparse(name)
if rv.scheme == 'https' and rv.port is None:
... |
Basically the counter-part of :func:`urlsplit`. | def urljoin(netloc, port, ssl):
"""
Basically the counter-part of :func:`urlsplit`.
"""
rv = ("https" if ssl else "http") + "://" + netloc
if ssl and port != 443 or not ssl and port != 80:
rv += ":%i" % port
return rv |
Return a function that returns a valid HTTP Origin or localhost
if none found. | def origin(hosts):
"""
Return a function that returns a valid HTTP Origin or localhost
if none found.
"""
hosts = [urlsplit(h) for h in hosts]
def func(environ):
if 'ISSO_CORS_ORIGIN' in environ:
return environ['ISSO_CORS_ORIGIN']
if not hosts:
return "... |
Same as urllib2.urlopen or urllib.request.urlopen,
the only difference is that it links to the internal opener. | def urlopen(self, url, data=None, *args, **kwargs):
"""
Same as urllib2.urlopen or urllib.request.urlopen,
the only difference is that it links to the internal opener.
"""
logger.info('opening: \'%s\'', url)
if data is None:
return self.opener.open(url)
... |
Similar to urllib.urlretrieve or urllib.request.urlretrieve
only that *filname* is required.
:param url: URL to download.
:param filename: Filename to save the content to.
:param data: Valid URL-encoded data.
:return: Tuple containing path and headers. | def urlretrieve(self, url, filename, data=None):
"""
Similar to urllib.urlretrieve or urllib.request.urlretrieve
only that *filname* is required.
:param url: URL to download.
:param filename: Filename to save the content to.
:param data: Valid URL-encoded data.
:... |
parse url and the result is tuple of
(hostname, port, resource path and the flag of secure mode)
url: url string. | def parse_url(url):
"""
parse url and the result is tuple of
(hostname, port, resource path and the flag of secure mode)
url: url string.
"""
if ":" not in url:
raise ValueError("url is invalid")
scheme, url = url.split(":", 1)
parsed = urlparse(url, scheme="ws")
if parsed... |
try to retrieve proxy host and port from environment
if not provided in options.
result is (proxy_host, proxy_port, proxy_auth).
proxy_auth is tuple of username and password
of proxy authentication information.
hostname: websocket server name.
is_secure: is the connection secure? (wss)
... | def get_proxy_info(
hostname, is_secure, proxy_host=None, proxy_port=0, proxy_auth=None,
no_proxy=None, proxy_type='http'):
"""
try to retrieve proxy host and port from environment
if not provided in options.
result is (proxy_host, proxy_port, proxy_auth).
proxy_auth is tuple of user... |
connect to url and return websocket object.
Connect to url and return the WebSocket object.
Passing optional timeout parameter will set the timeout on the socket.
If no timeout is supplied,
the global default timeout setting returned by getdefauttimeout() is used.
You can customize using 'options'.... | def create_connection(url, timeout=None, class_=WebSocket, **options):
"""
connect to url and return websocket object.
Connect to url and return the WebSocket object.
Passing optional timeout parameter will set the timeout on the socket.
If no timeout is supplied,
the global default timeout set... |
Set the timeout to the websocket.
timeout: timeout time(second). | def settimeout(self, timeout):
"""
Set the timeout to the websocket.
timeout: timeout time(second).
"""
self.sock_opt.timeout = timeout
if self.sock:
self.sock.settimeout(timeout) |
Connect to url. url is websocket url scheme.
ie. ws://host:port/resource
You can customize using 'options'.
If you set "header" list object, you can set your own custom header.
>>> ws = WebSocket()
>>> ws.connect("ws://echo.websocket.org/",
... header=["User-... | def connect(self, url, **options):
"""
Connect to url. url is websocket url scheme.
ie. ws://host:port/resource
You can customize using 'options'.
If you set "header" list object, you can set your own custom header.
>>> ws = WebSocket()
>>> ws.connect("ws://echo.... |
Send the data as string.
payload: Payload must be utf-8 string or unicode,
if the opcode is OPCODE_TEXT.
Otherwise, it must be string(byte array)
opcode: operation code to send. Please see OPCODE_XXX. | def send(self, payload, opcode=ABNF.OPCODE_TEXT):
"""
Send the data as string.
payload: Payload must be utf-8 string or unicode,
if the opcode is OPCODE_TEXT.
Otherwise, it must be string(byte array)
opcode: operation code to send. Please see OPCODE_... |
Send the data frame.
frame: frame data created by ABNF.create_frame
>>> ws = create_connection("ws://echo.websocket.org/")
>>> frame = ABNF.create_frame("Hello", ABNF.OPCODE_TEXT)
>>> ws.send_frame(frame)
>>> cont_frame = ABNF.create_frame("My name is ", ABNF.OPCODE_CONT, 0)
... | def send_frame(self, frame):
"""
Send the data frame.
frame: frame data created by ABNF.create_frame
>>> ws = create_connection("ws://echo.websocket.org/")
>>> frame = ABNF.create_frame("Hello", ABNF.OPCODE_TEXT)
>>> ws.send_frame(frame)
>>> cont_frame = ABNF.c... |
send ping data.
payload: data payload to send server. | def ping(self, payload=""):
"""
send ping data.
payload: data payload to send server.
"""
if isinstance(payload, six.text_type):
payload = payload.encode("utf-8")
self.send(payload, ABNF.OPCODE_PING) |
send pong data.
payload: data payload to send server. | def pong(self, payload):
"""
send pong data.
payload: data payload to send server.
"""
if isinstance(payload, six.text_type):
payload = payload.encode("utf-8")
self.send(payload, ABNF.OPCODE_PONG) |
Receive string data(byte array) from the server.
return value: string(byte array) value. | def recv(self):
"""
Receive string data(byte array) from the server.
return value: string(byte array) value.
"""
with self.readlock:
opcode, data = self.recv_data()
if six.PY3 and opcode == ABNF.OPCODE_TEXT:
return data.decode("utf-8")
eli... |
Receive data with operation code.
control_frame: a boolean flag indicating whether to return control frame
data, defaults to False
return value: tuple of operation code and string(byte array) value. | def recv_data(self, control_frame=False):
"""
Receive data with operation code.
control_frame: a boolean flag indicating whether to return control frame
data, defaults to False
return value: tuple of operation code and string(byte array) value.
"""
opcode, fram... |
Receive data with operation code.
control_frame: a boolean flag indicating whether to return control frame
data, defaults to False
return value: tuple of operation code and string(byte array) value. | def recv_data_frame(self, control_frame=False):
"""
Receive data with operation code.
control_frame: a boolean flag indicating whether to return control frame
data, defaults to False
return value: tuple of operation code and string(byte array) value.
"""
while ... |
send close data to the server.
status: status code to send. see STATUS_XXX.
reason: the reason to close. This must be string or bytes. | def send_close(self, status=STATUS_NORMAL, reason=six.b("")):
"""
send close data to the server.
status: status code to send. see STATUS_XXX.
reason: the reason to close. This must be string or bytes.
"""
if status < 0 or status >= ABNF.LENGTH_16:
raise Valu... |
Close Websocket object
status: status code to send. see STATUS_XXX.
reason: the reason to close. This must be string.
timeout: timeout until receive a close frame.
If None, it will wait forever until receive a close frame. | def close(self, status=STATUS_NORMAL, reason=six.b(""), timeout=3):
"""
Close Websocket object
status: status code to send. see STATUS_XXX.
reason: the reason to close. This must be string.
timeout: timeout until receive a close frame.
If None, it will wait forever... |
close socket, immediately. | def shutdown(self):
"""close socket, immediately."""
if self.sock:
self.sock.close()
self.sock = None
self.connected = False |
turn on/off the traceability.
traceable: boolean value. if set True, traceability is enabled. | def enableTrace(traceable, handler = logging.StreamHandler()):
"""
turn on/off the traceability.
traceable: boolean value. if set True, traceability is enabled.
"""
global _traceEnabled
_traceEnabled = traceable
if traceable:
_logger.addHandler(handler)
_logger.setLevel(logg... |
validate the ABNF frame.
skip_utf8_validation: skip utf8 validation. | def validate(self, skip_utf8_validation=False):
"""
validate the ABNF frame.
skip_utf8_validation: skip utf8 validation.
"""
if self.rsv1 or self.rsv2 or self.rsv3:
raise WebSocketProtocolException("rsv is not implemented, yet")
if self.opcode not in ABNF.OPC... |
create frame to send text, binary and other data.
data: data to send. This is string value(byte array).
if opcode is OPCODE_TEXT and this value is unicode,
data value is converted into unicode string, automatically.
opcode: operation code. please see OPCODE_XXX.
fin: f... | def create_frame(data, opcode, fin=1):
"""
create frame to send text, binary and other data.
data: data to send. This is string value(byte array).
if opcode is OPCODE_TEXT and this value is unicode,
data value is converted into unicode string, automatically.
opc... |
format this object to string(byte array) to send data to server. | def format(self):
"""
format this object to string(byte array) to send data to server.
"""
if any(x not in (0, 1) for x in [self.fin, self.rsv1, self.rsv2, self.rsv3]):
raise ValueError("not 0 or 1")
if self.opcode not in ABNF.OPCODES:
raise ValueError("In... |
mask or unmask data. Just do xor for each byte
mask_key: 4 byte string(byte).
data: data to mask/unmask. | def mask(mask_key, data):
"""
mask or unmask data. Just do xor for each byte
mask_key: 4 byte string(byte).
data: data to mask/unmask.
"""
if data is None:
data = ""
if isinstance(mask_key, six.text_type):
mask_key = six.b(mask_key)
... |
send message.
data: message to send. If you set opcode to OPCODE_TEXT,
data must be utf-8 string or unicode.
opcode: operation code of data. default is OPCODE_TEXT. | def send(self, data, opcode=ABNF.OPCODE_TEXT):
"""
send message.
data: message to send. If you set opcode to OPCODE_TEXT,
data must be utf-8 string or unicode.
opcode: operation code of data. default is OPCODE_TEXT.
"""
if not self.sock or self.sock.send(da... |
close websocket connection. | def close(self, **kwargs):
"""
close websocket connection.
"""
self.keep_running = False
if self.sock:
self.sock.close(**kwargs)
self.sock = None |
run event loop for WebSocket framework.
This loop is infinite loop and is alive during websocket is available.
sockopt: values for socket.setsockopt.
sockopt must be tuple
and each element is argument of sock.setsockopt.
sslopt: ssl socket optional dict.
ping_inte... | def run_forever(self, sockopt=None, sslopt=None,
ping_interval=0, ping_timeout=None,
http_proxy_host=None, http_proxy_port=None,
http_no_proxy=None, http_proxy_auth=None,
skip_utf8_validation=False,
host=None, origin=Non... |
this functions extracts the code, reason from the close body
if they exists, and if the self.on_close except three arguments | def _get_close_args(self, data):
""" this functions extracts the code, reason from the close body
if they exists, and if the self.on_close except three arguments """
# if the on_close callback is "old", just return empty list
if sys.version_info < (3, 0):
if not self.on_close... |
GET request.
:param str url: Request url
:param dict headers: (optional) Request headers
:param dict params: (optional) Request query parameter
:param bool stream: (optional) get content as stream
:param timeout: (optional), How long to wait for the server
to send da... | def get(self, url, headers=None, params=None, stream=False, timeout=None):
"""GET request.
:param str url: Request url
:param dict headers: (optional) Request headers
:param dict params: (optional) Request query parameter
:param bool stream: (optional) get content as stream
... |
POST request.
:param str url: Request url
:param dict headers: (optional) Request headers
:param data: (optional) Dictionary, bytes, or file-like object to send in the body
:param timeout: (optional), How long to wait for the server
to send data before giving up, as a float,... | def post(self, url, headers=None, data=None, timeout=None):
"""POST request.
:param str url: Request url
:param dict headers: (optional) Request headers
:param data: (optional) Dictionary, bytes, or file-like object to send in the body
:param timeout: (optional), How long to wai... |
Get request body as iterator content (stream).
:param int chunk_size:
:param bool decode_unicode: | def iter_content(self, chunk_size=1024, decode_unicode=False):
"""Get request body as iterator content (stream).
:param int chunk_size:
:param bool decode_unicode:
"""
return self.response.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode) |
Convert to snake case.
:param str text:
:rtype: str
:return: | def to_snake_case(text):
"""Convert to snake case.
:param str text:
:rtype: str
:return:
"""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', text)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() |
Convert to camel case.
:param str text:
:rtype: str
:return: | def to_camel_case(text):
"""Convert to camel case.
:param str text:
:rtype: str
:return:
"""
split = text.split('_')
return split[0] + "".join(x.title() for x in split[1:]) |
safe_compare_digest method.
:param val1: string or bytes for compare
:type val1: str | bytes
:param val2: string or bytes for compare
:type val2: str | bytes | def safe_compare_digest(val1, val2):
"""safe_compare_digest method.
:param val1: string or bytes for compare
:type val1: str | bytes
:param val2: string or bytes for compare
:type val2: str | bytes
"""
if len(val1) != len(val2):
return False
result = 0
if PY3 and isinstance... |
Return dictionary from this object.
:return: dict | def as_json_dict(self):
"""Return dictionary from this object.
:return: dict
"""
data = {}
for key, value in self.__dict__.items():
camel_key = utils.to_camel_case(key)
if isinstance(value, (list, tuple, set)):
data[camel_key] = list()
... |
Create a new instance from a dict.
:param data: JSON dict
:rtype:
:return: | def new_from_json_dict(cls, data):
"""Create a new instance from a dict.
:param data: JSON dict
:rtype:
:return:
"""
new_data = {utils.to_snake_case(key): value
for key, value in data.items()}
return cls(**new_data) |
Get `cls` object w/ deserialization from json if needed.
If data is instance of cls, return data.
Else if data is instance of dict, create instance from dict.
Else, return None.
:param data:
:param cls:
:rtype: object
:return: | def get_or_new_from_json_dict(data, cls):
"""Get `cls` object w/ deserialization from json if needed.
If data is instance of cls, return data.
Else if data is instance of dict, create instance from dict.
Else, return None.
:param data:
:param cls:
:rtype: object... |
Get `cls` object w/ deserialization from json by using type key hint if needed.
If data is instance of one of cls, return data.
Else if data is instance of dict, create instance from dict.
Else, return None.
:param data:
:param cls_map:
:param type_key:
:rtype: ... | def get_or_new_from_json_dict_with_types(
data, cls_map, type_key='type'
):
"""Get `cls` object w/ deserialization from json by using type key hint if needed.
If data is instance of one of cls, return data.
Else if data is instance of dict, create instance from dict.
Els... |
Call reply message API.
https://devdocs.line.me/en/#reply-message
Respond to events from users, groups, and rooms.
Webhooks are used to notify you when an event occurs.
For events that you can respond to, a replyToken is issued for replying to messages.
Because the replyToken... | def reply_message(self, reply_token, messages, timeout=None):
"""Call reply message API.
https://devdocs.line.me/en/#reply-message
Respond to events from users, groups, and rooms.
Webhooks are used to notify you when an event occurs.
For events that you can respond to, a reply... |
Call push message API.
https://devdocs.line.me/en/#push-message
Send messages to users, groups, and rooms at any time.
:param str to: ID of the receiver
:param messages: Messages.
Max: 5
:type messages: T <= :py:class:`linebot.models.send_messages.SendMessage` |
... | def push_message(self, to, messages, timeout=None):
"""Call push message API.
https://devdocs.line.me/en/#push-message
Send messages to users, groups, and rooms at any time.
:param str to: ID of the receiver
:param messages: Messages.
Max: 5
:type messages:... |
Call get profile API.
https://devdocs.line.me/en/#bot-api-get-profile
Get user profile information.
:param str user_id: User ID
:param timeout: (optional) How long to wait for the server
to send data before giving up, as a float,
or a (connect timeout, read tim... | def get_profile(self, user_id, timeout=None):
"""Call get profile API.
https://devdocs.line.me/en/#bot-api-get-profile
Get user profile information.
:param str user_id: User ID
:param timeout: (optional) How long to wait for the server
to send data before giving up... |
Call get group member profile API.
https://devdocs.line.me/en/#get-group-room-member-profile
Gets the user profile of a member of a group that
the bot is in. This can be the user ID of a user who has
not added the bot as a friend or has blocked the bot.
:param str group_id: Gr... | def get_group_member_profile(self, group_id, user_id, timeout=None):
"""Call get group member profile API.
https://devdocs.line.me/en/#get-group-room-member-profile
Gets the user profile of a member of a group that
the bot is in. This can be the user ID of a user who has
not ad... |
Call get room member profile API.
https://devdocs.line.me/en/#get-group-room-member-profile
Gets the user profile of a member of a room that
the bot is in. This can be the user ID of a user who has
not added the bot as a friend or has blocked the bot.
:param str room_id: Room ... | def get_room_member_profile(self, room_id, user_id, timeout=None):
"""Call get room member profile API.
https://devdocs.line.me/en/#get-group-room-member-profile
Gets the user profile of a member of a room that
the bot is in. This can be the user ID of a user who has
not added ... |
Call get group member IDs API.
https://devdocs.line.me/en/#get-group-room-member-ids
Gets the user IDs of the members of a group that the bot is in.
This includes the user IDs of users who have not added the bot as a friend
or has blocked the bot.
:param str group_id: Group ID... | def get_group_member_ids(self, group_id, start=None, timeout=None):
"""Call get group member IDs API.
https://devdocs.line.me/en/#get-group-room-member-ids
Gets the user IDs of the members of a group that the bot is in.
This includes the user IDs of users who have not added the bot as ... |
Call get room member IDs API.
https://devdocs.line.me/en/#get-group-room-member-ids
Gets the user IDs of the members of a group that the bot is in.
This includes the user IDs of users who have not added the bot as a friend
or has blocked the bot.
:param str room_id: Room ID
... | def get_room_member_ids(self, room_id, start=None, timeout=None):
"""Call get room member IDs API.
https://devdocs.line.me/en/#get-group-room-member-ids
Gets the user IDs of the members of a group that the bot is in.
This includes the user IDs of users who have not added the bot as a f... |
Call get content API.
https://devdocs.line.me/en/#get-content
Retrieve image, video, and audio data sent by users.
:param str message_id: Message ID
:param timeout: (optional) How long to wait for the server
to send data before giving up, as a float,
or a (conn... | def get_message_content(self, message_id, timeout=None):
"""Call get content API.
https://devdocs.line.me/en/#get-content
Retrieve image, video, and audio data sent by users.
:param str message_id: Message ID
:param timeout: (optional) How long to wait for the server
... |
Call leave group API.
https://devdocs.line.me/en/#leave
Leave a group.
:param str group_id: Group ID
:param timeout: (optional) How long to wait for the server
to send data before giving up, as a float,
or a (connect timeout, read timeout) float tuple.
... | def leave_group(self, group_id, timeout=None):
"""Call leave group API.
https://devdocs.line.me/en/#leave
Leave a group.
:param str group_id: Group ID
:param timeout: (optional) How long to wait for the server
to send data before giving up, as a float,
... |
Call leave room API.
https://devdocs.line.me/en/#leave
Leave a room.
:param str room_id: Room ID
:param timeout: (optional) How long to wait for the server
to send data before giving up, as a float,
or a (connect timeout, read timeout) float tuple.
... | def leave_room(self, room_id, timeout=None):
"""Call leave room API.
https://devdocs.line.me/en/#leave
Leave a room.
:param str room_id: Room ID
:param timeout: (optional) How long to wait for the server
to send data before giving up, as a float,
or a (... |
Call get rich menu API.
https://developers.line.me/en/docs/messaging-api/reference/#get-rich-menu
:param str rich_menu_id: ID of the rich menu
:param timeout: (optional) How long to wait for the server
to send data before giving up, as a float,
or a (connect timeout, re... | def get_rich_menu(self, rich_menu_id, timeout=None):
"""Call get rich menu API.
https://developers.line.me/en/docs/messaging-api/reference/#get-rich-menu
:param str rich_menu_id: ID of the rich menu
:param timeout: (optional) How long to wait for the server
to send data bef... |
Call create rich menu API.
https://developers.line.me/en/docs/messaging-api/reference/#create-rich-menu
:param rich_menu: Inquired to create a rich menu object.
:type rich_menu: T <= :py:class:`linebot.models.rich_menu.RichMenu`
:param timeout: (optional) How long to wait for the serve... | def create_rich_menu(self, rich_menu, timeout=None):
"""Call create rich menu API.
https://developers.line.me/en/docs/messaging-api/reference/#create-rich-menu
:param rich_menu: Inquired to create a rich menu object.
:type rich_menu: T <= :py:class:`linebot.models.rich_menu.RichMenu`
... |
Call delete rich menu API.
https://developers.line.me/en/docs/messaging-api/reference/#delete-rich-menu
:param str rich_menu_id: ID of an uploaded rich menu
:param timeout: (optional) How long to wait for the server
to send data before giving up, as a float,
or a (conne... | def delete_rich_menu(self, rich_menu_id, timeout=None):
"""Call delete rich menu API.
https://developers.line.me/en/docs/messaging-api/reference/#delete-rich-menu
:param str rich_menu_id: ID of an uploaded rich menu
:param timeout: (optional) How long to wait for the server
... |
Call get rich menu ID of user API.
https://developers.line.me/en/docs/messaging-api/reference/#get-rich-menu-id-of-user
:param str user_id: IDs of the user
:param timeout: (optional) How long to wait for the server
to send data before giving up, as a float,
or a (connec... | def get_rich_menu_id_of_user(self, user_id, timeout=None):
"""Call get rich menu ID of user API.
https://developers.line.me/en/docs/messaging-api/reference/#get-rich-menu-id-of-user
:param str user_id: IDs of the user
:param timeout: (optional) How long to wait for the server
... |
Call link rich menu to user API.
https://developers.line.me/en/docs/messaging-api/reference/#link-rich-menu-to-user
:param str user_id: ID of an uploaded rich menu
:param str rich_menu_id: ID of the user
:type timeout: float | tuple(float, float) | def link_rich_menu_to_user(self, user_id, rich_menu_id, timeout=None):
"""Call link rich menu to user API.
https://developers.line.me/en/docs/messaging-api/reference/#link-rich-menu-to-user
:param str user_id: ID of an uploaded rich menu
:param str rich_menu_id: ID of the user
... |
Call unlink rich menu from user API.
https://developers.line.me/en/docs/messaging-api/reference/#unlink-rich-menu-from-user
:param str user_id: ID of the user
:param timeout: (optional) How long to wait for the server
to send data before giving up, as a float,
or a (con... | def unlink_rich_menu_from_user(self, user_id, timeout=None):
"""Call unlink rich menu from user API.
https://developers.line.me/en/docs/messaging-api/reference/#unlink-rich-menu-from-user
:param str user_id: ID of the user
:param timeout: (optional) How long to wait for the server
... |
Call download rich menu image API.
https://developers.line.me/en/docs/messaging-api/reference/#download-rich-menu-image
:param str rich_menu_id: ID of the rich menu with the image to be downloaded
:param timeout: (optional) How long to wait for the server
to send data before giving... | def get_rich_menu_image(self, rich_menu_id, timeout=None):
"""Call download rich menu image API.
https://developers.line.me/en/docs/messaging-api/reference/#download-rich-menu-image
:param str rich_menu_id: ID of the rich menu with the image to be downloaded
:param timeout: (optional) ... |
Call upload rich menu image API.
https://developers.line.me/en/docs/messaging-api/reference/#upload-rich-menu-image
Uploads and attaches an image to a rich menu.
:param str rich_menu_id: IDs of the richmenu
:param str content_type: image/jpeg or image/png
:param content: image... | def set_rich_menu_image(self, rich_menu_id, content_type, content, timeout=None):
"""Call upload rich menu image API.
https://developers.line.me/en/docs/messaging-api/reference/#upload-rich-menu-image
Uploads and attaches an image to a rich menu.
:param str rich_menu_id: IDs of the ri... |
Call get rich menu list API.
https://developers.line.me/en/docs/messaging-api/reference/#get-rich-menu-list
:param timeout: (optional) How long to wait for the server
to send data before giving up, as a float,
or a (connect timeout, read timeout) float tuple.
Defaul... | def get_rich_menu_list(self, timeout=None):
"""Call get rich menu list API.
https://developers.line.me/en/docs/messaging-api/reference/#get-rich-menu-list
:param timeout: (optional) How long to wait for the server
to send data before giving up, as a float,
or a (connect... |
Check signature.
https://devdocs.line.me/en/#webhook-authentication
:param str body: Request body (as text)
:param str signature: X-Line-Signature value (as text)
:rtype: bool
:return: result | def validate(self, body, signature):
"""Check signature.
https://devdocs.line.me/en/#webhook-authentication
:param str body: Request body (as text)
:param str signature: X-Line-Signature value (as text)
:rtype: bool
:return: result
"""
gen_signature = hm... |
Parse webhook request body as text.
:param str body: Webhook request body (as text)
:param str signature: X-Line-Signature value (as text)
:rtype: list[T <= :py:class:`linebot.models.events.Event`]
:return: | def parse(self, body, signature):
"""Parse webhook request body as text.
:param str body: Webhook request body (as text)
:param str signature: X-Line-Signature value (as text)
:rtype: list[T <= :py:class:`linebot.models.events.Event`]
:return:
"""
if not self.sig... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.