File: http.py

package info (click to toggle)
python-tinyrpc 0.6-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 324 kB
  • sloc: python: 1,700; makefile: 142; sh: 16
file content (66 lines) | stat: -rw-r--r-- 2,274 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import requests
import geventwebsocket as websocket

from . import ClientTransport


class HttpPostClientTransport(ClientTransport):
    """HTTP POST based client transport.

    Requires :py:mod:`requests`. Submits messages to a server using the body of
    an ``HTTP`` ``POST`` request. Replies are taken from the responses body.

    :param endpoint: The URL to send ``POST`` data to.
    :param post_method: allows to replace `requests.post` with another method,
        e.g. the post method of a `requests.Session()` instance.
    :param kwargs: Additional parameters for :py:func:`requests.post`.
    """
    def __init__(self, endpoint, post_method=None, **kwargs):
        self.endpoint = endpoint
        self.request_kwargs = kwargs
        if post_method is None:
            self.post = requests.post
        else:
            self.post = post_method

    def send_message(self, message, expect_reply=True):
        if not isinstance(message, str):
            raise TypeError('str expected')

        r = self.post(self.endpoint, data=message, **self.request_kwargs)

        if expect_reply:
            return r.content


class HttpWebSocketClientTransport(ClientTransport):
    """HTTP WebSocket based client transport.

    Requires :py:mod:`websocket-python`. Submits messages to a server using the body of
    an ``HTTP`` ``WebSocket`` message. Replies are taken from the response of the websocket.

    The connection is establish on the ``__init__`` because the protocol is connection oriented,
    you need to close the connection calling the close method.

    :param endpoint: The URL to connect the websocket.
    :param kwargs: Additional parameters for :py:func:`websocket.send`.
    """
    def __init__(self, endpoint, **kwargs):
        self.endpoint = endpoint
        self.request_kwargs = kwargs
        self.ws = websocket.create_connection(self.endpoint, **kwargs)

    def send_message(self, message, expect_reply=True):
        if not isinstance(message, str):
            raise TypeError('str expected')
        self.ws.send(message)
        r = self.ws.recv()
        if expect_reply:
            return r

    def close(self):
        if self.ws is not None:
            self.ws.close()