Пример #1
0
    def __init__(self, tender_id, worker_defaults={}, auction_data={}):
        self.tender_id = tender_id
        self.auction_doc_id = tender_id
        self._end_auction_event = Event()
        self.tender_url = urljoin(
            worker_defaults["resource_api_server"],
            '/api/{0}/auctions/{1}'.format(
                worker_defaults["resource_api_version"], tender_id))
        if auction_data:
            self.debug = True
            LOGGER.setLevel(logging.DEBUG)
            self._auction_data = auction_data
        else:
            self.debug = False
        self.bids_actions = BoundedSemaphore()
        self.session = RequestsSession()
        self.features = {}  # bw
        self.worker_defaults = worker_defaults
        if self.worker_defaults.get('with_document_service', False):
            self.session_ds = RequestsSession()
        self._bids_data = {}
        self.db = Database(str(self.worker_defaults["COUCH_DATABASE"]),
                           session=Session(retry_delays=range(10)))
        self.audit = {}
        self.retries = 10
        self.mapping = {}
        self._bids_data = defaultdict(list)
        self.has_critical_error = False
        if REQUEST_QUEUE_SIZE == -1:
            self.bids_queue = Queue()
        else:
            self.bids_queue = Queue(REQUEST_QUEUE_SIZE)

        self.bidders_data = []
Пример #2
0
    def __init__(self, config):

        # Checking API availability
        health_url = urljoin(config['resource_api_server'],
                             "/api/{resource_api_version}/health")
        response = make_request(url=health_url.format(**config),
                                method="get",
                                retry_count=5)
        if not response:
            raise Exception("API can't be reached")

        self.api_url = urljoin(
            config['resource_api_server'],
            '/api/{0}/{1}/{2}'.format(config['resource_api_version'],
                                      config['resource_name'],
                                      config['auction_id']))
        self.api_token = config["resource_api_token"]
        self.source_id = config['auction_id']
        self.auction_url = config["AUCTIONS_URL"].format(
            auction_id=self.source_id)

        self.hash_secret = config["HASH_SECRET"]

        self.with_document_service = config.get('with_document_service', False)
        self.session = RequestsSession()
        if config.get('with_document_service', False):
            self.ds_credential['username'] = config['DOCUMENT_SERVICE'][
                'username']
            self.ds_credential['password'] = config['DOCUMENT_SERVICE'][
                'password']
            self.document_service_url = config['DOCUMENT_SERVICE']['url']

            # Checking DS availability and setting session_ds attribute
            request("GET", self.document_service_url, timeout=5)
            self.session_ds = RequestsSession()
Пример #3
0
 def session(self, base_url="http://testserver"):
     """Cached Testing HTTP client based on Requests by Kenneth Reitz."""
     if self._session is None:
         session = RequestsSession()
         session.mount(base_url, RequestsWSGIAdapter(self))
         self._session = session
     return self._session
Пример #4
0
    def __init__(self, client=None, timeout=None):
        self.timeout = timeout
        self.store = {}

        if client is None:
            self.client = RequestsSession()
        else:
            self.client = client
Пример #5
0
def send_message(chat_id: int, text: str, session: RequestsSession = RequestsSession()):
    with session.get(
        f'https://api.telegram.org/bot{settings.MEME}/sendMessage',
        params={'chat_id': chat_id, 'text': text}
    ) as response:
        if response.status_code != 429:
            return
        raise TooManyRequests(response.json()['parameters']['retry_after'])
Пример #6
0
    def __init__(self, tender_id,
                 worker_defaults,
                 auction_data={},
                 lot_id=None):
        super(Auction, self).__init__()
        self.generate_request_id()
        self.tender_id = tender_id
        self.lot_id = lot_id
        if lot_id:
            self.auction_doc_id = tender_id + "_" + lot_id
        else:
            self.auction_doc_id = tender_id
        self.tender_url = urljoin(
            worker_defaults["resource_api_server"],
            '/api/{0}/{1}/{2}'.format(
                worker_defaults["resource_api_version"],
                worker_defaults["resource_name"],
                tender_id
            )
        )
        if auction_data:
            self.debug = True
            LOGGER.setLevel(logging.DEBUG)
            self._auction_data = auction_data
        else:
            self.debug = False

        self._end_auction_event = Event()
        self.bids_actions = BoundedSemaphore()
        self.session = RequestsSession()
        self.worker_defaults = worker_defaults
        if self.worker_defaults.get('with_document_service', False):
            self.session_ds = RequestsSession()
        self._bids_data = {}
        self.db = Database(str(self.worker_defaults["COUCH_DATABASE"]),
                           session=Session(retry_delays=range(10)))
        self.audit = {}
        self.retries = 10
        self.bidders_count = 0
        self.bidders_data = []
        self.bidders_features = {}
        self.bidders_coeficient = {}
        self.features = None
        self.mapping = {}
        self.rounds_stages = []
Пример #7
0
def get_mailman_lists(
    owner: Owner, sess: RequestsSession = RequestsSession()) -> List[MailList]:
    """
    Query mailing lists owned by the given member or society.
    """
    prefix = owner_name(owner)
    resp = sess.get("https://lists.srcf.net/getlists.cgi",
                    params={"prefix": prefix})
    return [MailList(name) for name in resp.text.splitlines()]
Пример #8
0
 def test_session(self, base_url="http://testserver"):
     """
     Creates a test client associated with the given a url.
     The test session will be a requests session to be able to
     emulate a client in the browser.
     """
     session = RequestsSession()
     session.mount(prefix=base_url, adapter=RequestsWSGIAdapter(self))
     return session
Пример #9
0
    def session(self, base_url="http://baseserver"):
        """ 
        mount it to session object
        any request will start using URL given
        by prefix base_url
        """

        session = RequestsSession()
        session.mount(prefix=base_url, adapter=RequestWSGIAdapter(self))
        return session
Пример #10
0
def main():
    new_ads = []
    bot = Bot(token=settings.TELEGRAM_BOT_KEY)

    with RequestsSession() as session:
        ads = fetch_ads(session)
        if ads:
            new_ads = filter_new_ads(session, ads)
    if new_ads:
        send_message_into_telegram(bot, new_ads)
Пример #11
0
    def session(self, base_url="http://;"):
        """Testing HTTP client. Returns a Requests session object, able to send HTTP requests to the WSGI application.

        :param base_url: The URL to mount the connection adaptor to.
        """

        if self._session is None:
            session = RequestsSession()
            session.mount(base_url, RequestsWSGIAdapter(self))
            self._session = session
        return self._session
Пример #12
0
 def test_session(self, base_url="http://localserver"):
     """
     Creates a session so we can use requests whilst testing.
     Any URL that starts with base_url will be passed to the adapter
     :param base_url: url to use as a local test server
     :return: session with a mounted WSGI adapter
     :rtype: RequestsSession
     """
     session = RequestsSession()
     session.mount(prefix=base_url, adapter=RequestsWSGIAdapter(self))
     return session
Пример #13
0
    def __init__(self, config):
        self.api_url = urljoin(
            config['resource_api_server'],
            '/api/{0}/{1}/{2}'.format(config['resource_api_version'],
                                      config['resource_name'],
                                      config['auction_id']))
        self.api_token = config["resource_api_token"]
        self.source_id = config['auction_id']
        self.auction_url = config["AUCTIONS_URL"].format(
            auction_id=self.source_id)

        self.hash_secret = config["HASH_SECRET"]

        self.with_document_service = config.get('with_document_service', False)
        self.session = RequestsSession()
        if config.get('with_document_service', False):
            self.ds_credential['username'] = config['DOCUMENT_SERVICE'][
                'username']
            self.ds_credential['password'] = config['DOCUMENT_SERVICE'][
                'password']
            self.document_service_url = config['DOCUMENT_SERVICE']['url']
            self.session_ds = RequestsSession()
Пример #14
0
    def __init__(self, ansible_module):
        if not HAS_REQUESTS:
            ansible_module.fail_json(
                msg='The "requests"'
                ' python library is required to use the aoscx connection type.'
            )
        s = RequestsSession()
        connection = Connection(ansible_module._socket_path)
        session_data = connection.get_session()

        if session_data['success'] is False:
            ansible_module.fail_json(msg="Connection Failed")

        add_dict_to_cookiejar(s.cookies, session_data["cookies"])
        if session_data["use_proxy"] is False:
            s.proxies = {"http": None, "https": None}
        self._session = dict(s=s,
                             url=session_data["url"],
                             credentials=session_data["credentials"])
 def __init__(self,
              tender_id,
              worker_defaults={},
              auction_data={},
              lot_id=None,
              activate=False):
     super(Auction, self).__init__()
     self.generate_request_id()
     self.tender_id = tender_id
     self.lot_id = lot_id
     if lot_id:
         self.auction_doc_id = tender_id + "_" + lot_id
     else:
         self.auction_doc_id = tender_id
     self.tender_url = urljoin(
         worker_defaults["TENDERS_API_URL"], '/api/{0}/tenders/{1}'.format(
             worker_defaults["TENDERS_API_VERSION"], tender_id))
     self.activate = activate
     if auction_data:
         self.debug = True
         logger.setLevel(logging.DEBUG)
         self._auction_data = auction_data
     else:
         self.debug = False
     self.session = RequestsSession()
     self._end_auction_event = Event()
     self.bids_actions = BoundedSemaphore()
     self.worker_defaults = worker_defaults
     self._bids_data = {}
     self.db = Database(str(self.worker_defaults["COUCH_DATABASE"]),
                        session=Session(retry_delays=range(10)))
     self.audit = {}
     self.retries = 10
     self.bidders_count = 0
     self.bidders_data = []
     self.bidders_features = {}
     self.bidders_coeficient = {}
     self.features = None
     self.mapping = {}
     self.rounds_stages = []
def test_upload_audit_file_with_document_service(auction, db, logger, mocker):
    from requests import Session as RequestsSession
    auction.session_ds = RequestsSession()
    auction.prepare_auction_document()
    auction.get_auction_info()

    res = auction.upload_audit_file_with_document_service()
    assert res is None  # method does not return anything

    mock_session_request = mocker.patch.object(Session, 'request', autospec=True)

    mock_session_request.return_value.json.return_value = {
        'data': {
            'id': 'UA-11111'
        }
    }

    res = auction.upload_audit_file_with_document_service('UA-11111')
    assert res == 'UA-11111'

    log_strings = logger.log_capture_string.getvalue().split('\n')
    assert log_strings[3] == 'Audit log not approved.'
Пример #17
0
    def from_dict(config):
        # type: (dict) -> Client

        client = Client()
        client.username = config['username']
        client.password = config['password']
        client.cache_name = config['cache_name']

        if config['address'].startswith('http'):
            address = config['address']
        else:
            address = 'http{}://{}'.format('s' if config['is_https'] else '',
                                           config['address'])

        client.address = address

        session = RequestsSession()
        if client.password:
            session.auth = (client.username, client.password)
        client.session = session

        return client
Пример #18
0
def edit_message_reply_markup(
        chat_id: int,
        new_reply_markup: dict,
        message_id: int = None,
        inline_message_id: int = None,
        session: RequestsSession = RequestsSession()
):
    assert message_id is not None or inline_message_id is not None,\
        'You must at least provide message_id or inline_message_id !'
    params = {'chat_id': chat_id, 'reply_markup': json.dumps(new_reply_markup)}
    if message_id:
        params['message_id'] = message_id
    else:
        params['inline_message_id'] = inline_message_id
    with session.get(
        f'https://api.telegram.org/bot{settings.MEME}/editMessageReplyMarkup',
        timeout=(settings.REQUESTS_TIMEOUT * 20),
        params=params
    ) as response:
        if response.status_code != 429:
            return
        raise TooManyRequests(response.json()['parameters']['retry_after'])
Пример #19
0
 def session(self, base_url="http://app"):
     if self._session is None:
         session = RequestsSession()
         session.mount(base_url, RequestsWSGIAdapter(self))
         self._session = session
     return self._session
Пример #20
0
 def test_session(self, base_url="http://testserver") -> RequestsSession:
     """Used for Testing"""
     session = RequestsSession()
     session.mount(prefix=base_url, adapter=RequestsWSGIAdapter(self))
     return session
Пример #21
0
    def startJanus(self):
        with self._janusStartStopCondition:
            #Start janus command here
            if self._JanusProcess and self._JanusProcess.returncode is None:
                self._logger.debug('Janus was already running')
                return True  #already running

            args = ['/opt/janus/bin/janus']

            nm = networkManager()
            if not nm.isOnline():
                args.append('--config=/opt/janus/etc/janus/janus.cfg.local')

            try:
                self._JanusProcess = subprocess.Popen(args,
                                                      stdout=subprocess.PIPE)

            except Exception, error:
                self._logger.error("Error initiating janus process: %s" %
                                   str(error))
                self._JanusProcess = None
                self.sendEventToPeers('stopConnection')

            if self._JanusProcess:
                self._logger.debug('Janus Starting...')

                from requests import Session as RequestsSession

                session = RequestsSession()
                response = None

                tryingCounter = 0
                while response is None:
                    time.sleep(0.3)

                    try:
                        response = session.post(url='http://127.0.0.1:8088',
                                                data={
                                                    "message": {
                                                        "request": 'info',
                                                        "transaction": 'ready'
                                                    }
                                                })

                    except Exception, error:
                        self._logger.debug('Waiting for Janus initialization')
                        tryingCounter += 1

                        if tryingCounter >= 100:
                            self._logger.error(error)
                            return False

                self._logger.debug('Janus Started.')

                #Connect the signal for fatal errors when they happen
                ready = signal('manage_fatal_error_webrtc')
                ready.connect(self.closeAllSessions)

                #START TIMER FOR LOST PEERS
                self.peersDeadDetacher = interval(30.0, self.pingPongRounder,
                                                  None)
                self.peersDeadDetacher.start()

                return True
Пример #22
0
 def test_session(self, base_url="http://testserver"):
     session = RequestsSession()
     session.mount(prefix=base_url, adapter=RequestsWSGIAdapter(self))
     return session
Пример #23
0
 def test_session(self, base_url=BASE_URL):
     session = RequestsSession()
     session.mount(prefix=base_url, adapter=RequestsWSGIAdapter(self))
     return session
Пример #24
0
 def session(self, base_url="http://testserver"):
     if self._session is None:
         session = RequestsSession()
         session.mount(prefix=base_url, adapter=RequestsWSGIAdapter(self))
         self._session = session
     return self._session
Пример #25
0
def client(app):
    session = RequestsSession()
    session.mount(prefix=BASE_URL, adapter=RequestsWSGIAdapter(app))
    return session
Пример #26
0
def Session():
    # TODO, consider using CacheControl, or write a new
    # cache tool.
    # TODO, restore method signatures somehow?
    return RequestsSession()