Ejemplo n.º 1
0
	def _performRequest(cls, request, xml = True, exe = None):
		connection = cls._getConnection()
		addr = '/bin/stboard.exe/pn'
		if xml:
			request = '<?xml version="1.0" encoding="utf-8"?><ReqC ver="1.1" prod="String" lang="PL">{}</ReqC>'.format(request)
			addr = '/bin/query.exe/pn'
		
		if exe is not None:
			addr = '/bin/{}/pn'.format(exe)

		try:
			connection.request("POST", addr, request.encode('utf-8'), {'Content-Type': 'text/xml; charset=utf-8'})
			response = connection.getresponse()
		except (http.client.CannotSendRequest, http.client.BadStatusLine) :
			connection = cls._getConnection(False)
			connection.request("POST", addr, request.encode('utf-8'), {'Content-Type': 'text/xml; charset=utf-8'})
			response = connection.getresponse()


		if response.status != 200:
			raise HafasError('HTML', '{} {}'.format(response.status, response.reason))
		data = response.read()

		if not xml:
			data = '<Response>{data}</Response>'.format(data=data.decode('utf-8'))

		try:
			dom = parseString(data)
		except:
			raise


		errs = dom.getElementsByTagName('Err')
		for err in errs:
			code = err.getAttribute('code')
			text = err.getAttribute('text')
			level = err.getAttribute('level')

			if level == 'E':
				raise HafasError(code, text)
			
			if level == 'W':
				if code == 'K1:890':
					continue
				raise HafasWarning(code, text)
	
			raise HafasException(code, text)

		return data
Ejemplo n.º 2
0
    def wfs_getfeature_post_compare(self, requestid, request):
        project = self.testdata_path + "test_project_wfs.qgs"
        assert os.path.exists(project), "Project file not found: " + project

        query_string = '?MAP={}'.format(urllib.parse.quote(project))
        header, body = self._execute_request(
            query_string, requestMethod=QgsServerRequest.PostMethod, data=request.encode('utf-8'))

        self.result_compare(
            'wfs_getfeature_{}.txt'.format(requestid),
            "GetFeature in POST for '{}' failed.".format(requestid),
            header, body,
        )
Ejemplo n.º 3
0
    def wfs_getfeature_post_compare(self, requestid, request):
        project = self.testdata_path + "test_project_wfs.qgs"
        assert os.path.exists(project), "Project file not found: " + project

        query_string = '?MAP={}'.format(urllib.parse.quote(project))
        header, body = self._execute_request(
            query_string,
            requestMethod=QgsServerRequest.PostMethod,
            data=request.encode('utf-8'))

        self.result_compare(
            'wfs_getfeature_{}.txt'.format(requestid),
            "GetFeature in POST for '{}' failed.".format(requestid),
            header,
            body,
        )
Ejemplo n.º 4
0
    def _postmsg(self, request):
        """
        Post a request UTF8 text listener and return the response.
        """

        data = request.encode('utf-8')
        datalen = len(data)

        url = self.ServiceURL

        logger.debug('post request to %s with DATALEN=%d, DATA=<%s>', url,
                     datalen, data)

        try:
            request = urllib.request.Request(
                url, data, {
                    'Content-Type': 'text/plain; charset=utf-8',
                    'Content-Length': datalen
                })
            opener = urllib.request.build_opener(self.ProxyHandler)
            response = opener.open(request, timeout=10)

        except urllib.error.HTTPError as err:
            logger.warn('operation failed with response: %s', err.code)
            raise MessageException(
                'operation failed with response: {0}'.format(err.code))

        except urllib.error.URLError as err:
            logger.warn('operation failed: %s', err.reason)
            raise MessageException('operation failed: {0}'.format(err.reason))

        except:
            logger.exception('no response from server')
            raise MessageException('no response from server')

        content = response.read()
        headers = response.info()
        response.close()

        encoding = headers.get('Content-Type')
        if encoding != 'text/plain; charset=utf-8':
            logger.info('server responds with message %s of type %s', content,
                        encoding)
            return None

        return content
Ejemplo n.º 5
0
def test_basic():
    request = json.dumps({
        'instances':
        ["what are the vaccine side effects?", "is the vaccine free?"]
    })
    with urllib.request.urlopen(MODEL_URL, data=request.encode('utf-8')) as fp:
        response = json.load(fp)

    assert isinstance(response['predictions'], list)
    assert len(response['predictions']) == 2
    assert response['predictions'][0]['answer'].startswith(
        'Vaccine recipients commonly experience mild to moderate side effects')
    assert isinstance(response['predictions'][0]['score'], float)
    assert response['predictions'][1]['answer'].startswith(
        'The federal government is providing the vaccine free of charge to all people'
    )
    assert isinstance(response['predictions'][1]['score'], float)
Ejemplo n.º 6
0
    def write_http_request(self, path: str, headers: Headers) -> None:
        """
        Write request line and headers to the HTTP request.

        """
        self.path = path
        self.request_headers = headers

        logger.debug("%s > GET %s HTTP/1.1", self.side, path)
        logger.debug("%s > %r", self.side, headers)

        # Since the path and headers only contain ASCII characters,
        # we can keep this simple.
        request = f"GET {path} HTTP/1.1\r\n"
        request += str(headers)

        self.transport.write(request.encode())
Ejemplo n.º 7
0
def get_response_body(sock, host: str, path: str, verbose: bool = True) -> str:
    # Make an HTTP request
    request = "GET %s HTTP/1.1\r\n" % (path)
    request += "Host: %s\r\n" % (host)
    request += "\r\n"
    if verbose:
        print("Sending request:")
        print(request)
    sock.send(request.encode("UTF-8"))

    response = b""
    while response.find(b"\r\n\r\n") == -1:  # Still receiving header
        data = sock.recv(1024)
        response += data
    content_pos = response.find(b"\r\n\r\n") + 4  # Where the content begins
    header = response[0:content_pos - 4].decode("UTF-8")
    content = response[content_pos:]
    if verbose:
        print("Got response header:")
        header = header.replace("\r\n", " ", -1)
        print(header)

    find_status = re.search('^HTTP/1.1 [0-9][0-9][0-9]', header)
    if not find_status:
        raise Exception("Invalid response")
    if find_status.group()[-3:] != "200":
        raise Exception("Incorrect status" + find_status.group()[-3:])

    find_length = re.search("Content-Length: [0-9]*", header)
    if not find_length:
        raise Exception("Unknown content length")
    content_length = int(find_length.group()[16:])
    if content_length < 128:
        raise Exception("Invalid content length")
    while content_length > len(content):
        data = sock.recv(min(1024, content_length - len(content)))
        content += data
    content = content.decode("UTF-8")
    if verbose:
        print("Got response body:")
        print(content)
    return content
Ejemplo n.º 8
0
 def _test(version, srsName, lat_lon=False):
     self.i += 1
     name = '4326-test_%s' % self.i
     request = post_data.format(
         name=name,
         version=version,
         srsName=srsName,
         coordinates='52.48,10.67' if lat_lon else '10.67,52.48')
     header, body = self._execute_request(
         query_string,
         requestMethod=QgsServerRequest.PostMethod,
         data=request.encode('utf-8'))
     feature = next(
         vl.getFeatures(
             QgsFeatureRequest(QgsExpression('"name" = \'%s\'' %
                                             name))))
     geom = feature.geometry()
     self.assertEqual(
         geom.asWkt(0), geom_4326.asWkt(0),
         "Transaction Failed: %s , %s, lat_lon=%s" %
         (version, srsName, lat_lon))
Ejemplo n.º 9
0
def mySocketProxy(
    address
):  #Creats a HTTP socket connection to Proxy Server, from there a request is sent to the specified address
    x = time.time()
    request = "GET http://" + str(address) + "/ HTTP/1.1\r\nHost:" + str(
        address
    ) + "\r\n\r\n"  #Request string and header formulated with specified endpoint address
    sock = socket.socket()
    sock.connect(
        (proxy, proxyPort)
    )  #Socket connection establised with proxy server using the proxy global variables
    sock.send(request.encode('utf-8'))
    response = sock.recv(4096)
    z = time.time()
    threadTime = z - x
    print("Thread took " + str(threadTime) + " seconds\n")
    while (len(response) > 0):
        print(response)
        response = sock.recv(4096)
    z = time.time()
    threadTime = z - x
    print("Thread took " + str(threadTime) + " seconds\n")
Ejemplo n.º 10
0
    def test_insert_srsName(self):
        """Test srsName is respected when insering"""

        post_data = """
        <Transaction xmlns="http://www.opengis.net/wfs" xsi:schemaLocation="http://www.qgis.org/gml http://localhost:8000/?SERVICE=WFS&amp;REQUEST=DescribeFeatureType&amp;VERSION=1.0.0&amp;TYPENAME=as_symbols" service="WFS" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="{version}" xmlns:gml="http://www.opengis.net/gml">
            <Insert xmlns="http://www.opengis.net/wfs">
                <as_symbols xmlns="http://www.qgis.org/gml">
                <name xmlns="http://www.qgis.org/gml">{name}</name>
                <geometry xmlns="http://www.qgis.org/gml">
                    <gml:Point srsName="{srsName}">
                    <gml:coordinates cs="," ts=" ">{coordinates}</gml:coordinates>
                    </gml:Point>
                </geometry>
                </as_symbols>
            </Insert>
        </Transaction>
        """

        project = self.testdata_path + \
            "test_project_wms_grouped_layers.qgs"
        assert os.path.exists(project), "Project file not found: " + project

        query_string = '?SERVICE=WFS&MAP={}'.format(
            urllib.parse.quote(project))
        request = post_data.format(
            name='4326-test1',
            version='1.1.0',
            srsName='EPSG:4326',
            coordinates='10.67,52.48'
        )
        header, body = self._execute_request(
            query_string, requestMethod=QgsServerRequest.PostMethod, data=request.encode('utf-8'))

        # Verify
        vl = QgsVectorLayer(self.testdata_path + 'test_project_wms_grouped_layers.gpkg|layername=as_symbols', 'as_symbols')
        self.assertTrue(vl.isValid())
        feature = next(vl.getFeatures(QgsFeatureRequest(QgsExpression('"name" = \'4326-test1\''))))
        geom = feature.geometry()

        tr = QgsCoordinateTransform(QgsCoordinateReferenceSystem.fromEpsgId(4326), vl.crs(), QgsCoordinateTransformContext())

        geom_4326 = QgsGeometry.fromWkt('point( 10.67 52.48)')
        geom_4326.transform(tr)
        self.assertEqual(geom.asWkt(0), geom_4326.asWkt(0))

        # Now: insert a feature in layer's CRS
        request = post_data.format(
            name='25832-test1',
            version='1.1.0',
            srsName='EPSG:25832',
            coordinates='613412,5815738'
        )
        header, body = self._execute_request(
            query_string, requestMethod=QgsServerRequest.PostMethod, data=request.encode('utf-8'))

        feature = next(vl.getFeatures(QgsFeatureRequest(QgsExpression('"name" = \'25832-test1\''))))
        geom = feature.geometry()
        self.assertEqual(geom.asWkt(0), geom_4326.asWkt(0))

        # Tests for inverted axis issue GH #36584
        # Cleanup
        self.assertTrue(vl.startEditing())
        vl.selectByExpression('"name" LIKE \'4326-test%\'')
        vl.deleteSelectedFeatures()
        self.assertTrue(vl.commitChanges())

        self.i = 0

        def _test(version, srsName, lat_lon=False):
            self.i += 1
            name = '4326-test_%s' % self.i
            request = post_data.format(
                name=name,
                version=version,
                srsName=srsName,
                coordinates='52.48,10.67' if lat_lon else '10.67,52.48'
            )
            header, body = self._execute_request(
                query_string, requestMethod=QgsServerRequest.PostMethod, data=request.encode('utf-8'))
            feature = next(vl.getFeatures(QgsFeatureRequest(QgsExpression('"name" = \'%s\'' % name))))
            geom = feature.geometry()
            self.assertEqual(geom.asWkt(0), geom_4326.asWkt(0), "Transaction Failed: %s , %s, lat_lon=%s" % (version, srsName, lat_lon))

        _test('1.1.0', 'urn:ogc:def:crs:EPSG::4326', lat_lon=True)
        _test('1.1.0', 'http://www.opengis.net/def/crs/EPSG/0/4326', lat_lon=True)
        _test('1.1.0', 'http://www.opengis.net/gml/srs/epsg.xml#4326', lat_lon=False)
        _test('1.1.0', 'EPSG:4326', lat_lon=False)

        _test('1.0.0', 'urn:ogc:def:crs:EPSG::4326', lat_lon=True)
        _test('1.0.0', 'http://www.opengis.net/def/crs/EPSG/0/4326', lat_lon=True)
        _test('1.0.0', 'http://www.opengis.net/gml/srs/epsg.xml#4326', lat_lon=False)
        _test('1.0.0', 'EPSG:4326', lat_lon=False)

        def _test_getFeature(version, srsName, lat_lon=False):
            # Now get the feature through WFS using BBOX filter
            bbox = QgsGeometry.fromWkt('point( 10.7006 52.4317)').boundingBox()
            bbox.grow(0.0001)
            bbox_text = "%s,%s,%s,%s" % ((bbox.yMinimum(), bbox.xMinimum(), bbox.yMaximum(), bbox.xMaximum()) if lat_lon else (bbox.xMinimum(), bbox.yMinimum(), bbox.xMaximum(), bbox.yMaximum()))
            req = query_string + '&REQUEST=GetFeature&VERSION={version}&TYPENAME=as_symbols&SRSNAME={srsName}&BBOX={bbox},{srsName}'.format(version=version, srsName=srsName, bbox=bbox_text)
            header, body = self._execute_request(req)
            self.assertTrue(b'gid>7' in body, "GetFeature Failed: %s , %s, lat_lon=%s" % (version, srsName, lat_lon))

        _test_getFeature('1.1.0', 'urn:ogc:def:crs:EPSG::4326', lat_lon=True)
        _test_getFeature('1.1.0', 'EPSG:4326', lat_lon=False)

        _test_getFeature('1.0.0', 'urn:ogc:def:crs:EPSG::4326', lat_lon=True)
        _test_getFeature('1.0.0', 'EPSG:4326', lat_lon=False)

        # Cleanup
        self.assertTrue(vl.startEditing())
        vl.selectByExpression('"name" LIKE \'4326-test%\'')
        vl.deleteSelectedFeatures()
        self.assertTrue(vl.commitChanges())
Ejemplo n.º 11
0
def weather(argument):
    """
    funcao que recebe como parametro o comando e testa se possui os parametros corretos
    caso tenha parametro certo, requisita ao servico de metereologia, via http (POST e GET) e retorna a temperatura
    atual da cidade requisitada

    :param argument: string que eh a cidade a ser pesquisada
    :return: condicao climatica atual da localizacao ou uma mensagem de erro caso a cidade nao tenha sido informada
    """
    if argument != "":
        print("[LOG] Pesquisando previsao...")

        sockOpenWeather = socket.socket(
            socket.AF_INET,
            socket.SOCK_STREAM)  # abre conexao com o servidor do Openweather
        sockOpenWeather.connect(
            ("api.openweathermap.org", 80))  # conecta com a api
        request = (
            'GET /data/2.5/weather?q=' + argument +
            '&appid=778c214add5c6263ad53043ba7bf546d HTTP/1.1\r\nHost: api.openweathermap.org\r\n\r\n'
        )
        sockOpenWeather.sendall(
            request.encode())  # envia request GET http para a api
        requisicao = sockOpenWeather.recv(1024).decode()
        sockOpenWeather.close()  # fecha conexao

        requisicao = requisicao.split('{', 1)  # divide a string em 2
        js = requisicao[1]  # pega apenas  a parte que eh o json
        js = '{' + js  # readiciona uma { no inicio da string q eh o json
        tempo = json.loads(js)

        status = tempo['weather'][0][
            'description']  # recebe descricao do tempo em ingles dentro do dict 'tempo'
        qChuva = 0
        if tempo['weather'][0][
                'main'] == "Rain" and 'rain' in tempo:  # verifica se existe palavra no dict 'tempo' e busca quantidade de chuva
            qChuva = list(
                tempo['rain'].values())[0]  #quantidade de chuva previsto

        print("[LOG] Traduzindo...")
        params = dict(
            key=API_T, text=status,
            lang='en-pt')  #parametros para requisicao com API de traducao
        res = requests.get(
            urlt, params=params
        )  #busca com uma API a traducao da previsão do tempo, retornando um json
        jsonT = res.json()  # transforma para dict o json recebido da API
        status = str(jsonT['text'][0])  #pega string traduzida da API

        #variavel com todas as informacoes atuais do tempo
        answer = "[FORECAST] Cidade " + argument + "\nStatus atual: " + status + "\nPrevisao de chuva: " + str(
            qChuva) + "mm\nTemperatura atual: " + str(
                round((float(tempo['main']['temp'])) -
                      273.15)) + "oC\nUmidade em " + str(
                          tempo['main']['humidity']
                      ) + "porcento\nVelocidade do vento em " + str(
                          round(
                              (float(tempo['wind']['speed'])) * 3.6)) + " km/h"
    else:
        answer = "[ERROR] Comando \weather necessita de uma localizacao. Digite \help para saber mais"

    return answer
Ejemplo n.º 12
0
def weatherWeek(argument):
    """
    funcao que recebe uma cidade como parametro e retorna a previsao do tempo para ela, no periodo de uma semana
    :param argument: string que representa a cidade a ser pesquisada
    :return: temperatura da semana
    """
    if argument != "":
        print("[LOG] Cidade " + argument + " recebida do cliente e ")
        city = urllib.parse.quote(
            str(argument)
        )  # transforma string da cidade para formato URL p/ API reconhecer
        print("transformada para " + str(city) + " no formato URLs!")
        print("[LOG] Pesquisando previsao...")

        sockAccuWeather = socket.socket(
            socket.AF_INET, socket.SOCK_STREAM
        )  # abre conexao TCP com o servidor do AccuWeather
        sockAccuWeather.connect(("dataservice.accuweather.com",
                                 80))  # conecta com a API AccuWeather

        # string de requisição
        request = (
            'GET /locations/v1/cities/search?apikey=' + API + '&q=' + city +
            '&details=true HTTP/1.1\r\nHost: dataservice.accuweather.com\r\n\r\n'
        )

        sockAccuWeather.sendall(
            request.encode('utf-8'))  # envia request GET http para a api
        requisicao = sockAccuWeather.recv(
            2048).decode()  # recebe string com resposta do servidor
        sockAccuWeather.close()  # fecha conexao com API AccuWeather

        requisicao = requisicao.split('[', 1)  # divide a string em 2
        requisicao = requisicao[1]  # pega segunda parte da string
        requisicao = requisicao.split(',"Country"',
                                      1)  # separa string novamente
        requisicao = requisicao[0]  # pega primeira parte da string separada
        requisicao = requisicao + '}'  # acrescenta um caracter no final da string
        tempo = json.loads(
            requisicao)  # transforma toda resposta da API para dict
        location_key = tempo['Key']

        sockAccuWeather = socket.socket(
            socket.AF_INET,
            socket.SOCK_STREAM)  # abre conexao  com o servidor do AccuWeather
        sockAccuWeather.connect(
            ("dataservice.accuweather.com", 80))  # conecta com a api

        # string de requisição
        request = (
            'GET /forecasts/v1/daily/5day/' + location_key + '?apikey=' + API +
            '&details=true HTTP/1.1\r\nHost: dataservice.accuweather.com\r\n\r\n'
        )

        sockAccuWeather.sendall(
            request.encode('utf-8'))  # envia request GET http para a api
        requisicao2 = sockAccuWeather.recv(2048).decode(
            'utf-8')  # recebe string com resposta do servidor
        requisicao2 = requisicao2 + sockAccuWeather.recv(2048).decode(
            'utf-8')  # acrescenta resposta anterior com esta nova
        requisicao2 = requisicao2 + sockAccuWeather.recv(2048).decode(
            'utf-8')  # acrescenta resposta anterior com esta nova
        requisicao2 = requisicao2 + sockAccuWeather.recv(2048).decode(
            'utf-8')  # acrescenta resposta anterior com esta nova
        requisicao2 = requisicao2 + sockAccuWeather.recv(2048).decode(
            'utf-8')  # acrescenta resposta anterior com esta nova
        requisicao2 = requisicao2 + sockAccuWeather.recv(2048).decode(
            'utf-8')  # acrescenta resposta anterior com esta nova
        requisicao2 = requisicao2 + sockAccuWeather.recv(2048).decode(
            'utf-8')  # acrescenta resposta anterior com esta nova
        requisicao2 = requisicao2 + sockAccuWeather.recv(2048).decode(
            'utf-8')  # acrescenta resposta anterior com esta nova
        requisicao2 = requisicao2 + sockAccuWeather.recv(2048).decode(
            'utf-8')  # acrescenta resposta anterior com esta nova
        requisicao2 = requisicao2 + sockAccuWeather.recv(2048).decode(
            'utf-8')  # acrescenta resposta anterior com esta nova
        requisicao2 = requisicao2 + sockAccuWeather.recv(2048).decode(
            'utf-8')  # acrescenta resposta anterior com esta nova
        requisicao2 = requisicao2 + sockAccuWeather.recv(2048).decode(
            'utf-8')  # acrescenta resposta anterior com esta nova
        sockAccuWeather.close()  # fecha conexao com API AccuWeather

        requisicao2 = requisicao2.split('{', 1)  # divide a string em 2
        requisicao2 = '{' + requisicao2[1]

        tempo = json.loads(
            requisicao2)  # transforma toda resposta da API para dict
        resp = ""
        print("[LOG] Traduzindo...")
        respStatus = []
        cont = 0

        # este for vai percorrer posições do dict dos dados de cada dia da previsão e colocar
        # todos os status em um dict para depois serem traduzidas
        # vai colocar todos os status do turno do dia e noite de cada dia em uma list
        for key1 in tempo['DailyForecasts']:
            status = key1['Day']['LongPhrase']
            respStatus.insert(cont, str(status))
            cont = cont + 1
            status = key1['Night']['LongPhrase']
            respStatus.insert(cont, str(status))
            cont = cont + 1

        params = dict(
            key=API_T, text=str(respStatus), lang='en-pt'
        )  # envia list anterior em formato string para API traduzir
        res = requests.get(
            urlt,
            params=params)  # recebe json da API com as palavras já traduzidas
        jsonT = res.json()  # transforma arquivo json recebido em dict
        status = str(jsonT['text'][0])
        string = status[1:len(status)]
        list = string.split("', '")
        list[0] = list[0][1:]
        list[9] = list[9][:-2]

        # este for vai buscar as temperaturas, chuva, vento e status de cada dia
        cont = 0
        for key1 in tempo['DailyForecasts']:
            tempMin = round(
                ((key1['Temperature']['Minimum']['Value']) - 32) / 1.8000)
            tempMax = round(
                ((key1['Temperature']['Maximum']['Value']) - 32) / 1.8000)

            # parte da temperatura durante o dia
            ventoD = round((key1['Day']['Wind']['Speed']['Value']) * 1.609)
            qChuvaD = round((key1['Day']['Rain']['Value']) * 25.4)
            statusD = list[cont]
            cont = cont + 1

            # parte da temperatura durante a noite---------------------------------------
            ventoN = round((key1['Night']['Wind']['Speed']['Value']) * 1.609)
            qChuvaN = round((key1['Night']['Rain']['Value']) * 25.4)
            statusN = list[cont]
            cont = cont + 1

            diaData = key1['Date']

            # resposta de cada dia que retorna para resposta prncipal dessa função
            resp = resp + ("\n-----------\nData: " + diaData[8:10] + "/" +
                           diaData[5:7] + "/" + diaData[0:4] +
                           "\nTemperatura minima: " + str(tempMin) +
                           "\nTemperatura maxima: " + str(tempMax) +
                           "\n--Durante o dia:" + "\nPrevisao do tempo: " +
                           statusD + "\nChuva " + str(qChuvaD) + "mm\nVento " +
                           str(ventoD) + "km/h\n--Durante a noite:" +
                           "\nPrevisao do tempo: " + statusN + "\nChuva " +
                           str(qChuvaN) + "mm\nVento " + str(ventoN) + "km/h")

        # resposta principal que retornada para cliente
        answer = "[FORECAST] Previsao do tempo para " + argument + " durante os próximos dias:\n" + resp

    else:
        # retorna resposta se cliente deixou em branco o parâmetro de cidade
        answer = "[ERROR] Comando \weatherweek necessita de uma localizacao. Digite \help para saber mais"

    return answer  # retorna resposta da função
Ejemplo n.º 13
0
    def _process_request(self, request):
        response = ""
        logger.info(request.encode('utf-8'))
        args = request.split('\n')
        for i in range(len(args)):
            args[i] = unescape(args[i])
        logger.info(args)
        cmd = args[0]

        # Lookup
        if (cmd == "L"):
            if len(args) == 2:
                result_list = self.kv_helper.lookup(args[1])
                result = ""
                for key in result_list:
                    if result == "":
                        result = key
                    else:
                        result = result + "," + key
                # Lookup result found
                if result != "":
                    response = "l\n" + escape(result)
                # No result found
                else:
                    response = "n"
            # Error
            else:
                logger.error("Invalid args for cmd Lookup")
                response = "e\nInvalid args for cmd Lookup"

        # Get
        elif (cmd == "G"):
            if len(args) == 3:
                result = self.kv_helper.get(args[1], args[2])
                # Value found
                if result is not None:
                    response = "v\n" + escape(result)
                # Value not found
                else:
                    response = "n"
            # Error
            else:
                logger.error("Invalid args for cmd Get")
                response = "e\nInvalid args for cmd Get"

        # Set
        elif (cmd == "S"):
            if len(args) == 4:
                result = self.kv_helper.set(args[1], args[2], args[3])
                # Set successful (returned True)
                if result:
                    response = "t"
                # Set unsuccessful (returned False)
                else:
                    response = "f"
            # Error
            else:
                logger.error("Invalid args for cmd Set")
                response = "e\nInvalid args for cmd Set"

        # Remove
        elif (cmd == "R"):
            if len(args) == 3 or len(args) == 4:
                if len(args) == 3:
                    result = self.kv_helper.remove(args[1], args[2])
                else:
                    result = self.kv_helper.remove(args[1],
                                                   args[2],
                                                   value=args[3])
                # Remove successful (returned True)
                if result:
                    response = "t"
                # Remove unsuccessful (returned False)
                else:
                    response = "f"
            # Error
            else:
                logger.error("Invalid args for cmd Remove")
                response = "e\nInvalid args for cmd Remove"
        # Error
        else:
            logger.error("Unknown cmd")
            response = "e\nUnknown cmd"
        return response
Ejemplo n.º 14
0
    def test_insert_srsName(self):
        """Test srsName is respected when insering"""

        post_data = """
        <Transaction xmlns="http://www.opengis.net/wfs" xsi:schemaLocation="http://www.qgis.org/gml http://localhost:8000/?SERVICE=WFS&amp;REQUEST=DescribeFeatureType&amp;VERSION=1.0.0&amp;TYPENAME=as_symbols" service="WFS" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="{version}" xmlns:gml="http://www.opengis.net/gml">
            <Insert xmlns="http://www.opengis.net/wfs">
                <as_symbols xmlns="http://www.qgis.org/gml">
                <name xmlns="http://www.qgis.org/gml">{name}</name>
                <geometry xmlns="http://www.qgis.org/gml">
                    <gml:Point srsName="{srsName}">
                    <gml:coordinates cs="," ts=" ">{coordinates}</gml:coordinates>
                    </gml:Point>
                </geometry>
                </as_symbols>
            </Insert>
        </Transaction>
        """

        project = self.testdata_path + \
            "test_project_wms_grouped_layers.qgs"
        assert os.path.exists(project), "Project file not found: " + project

        query_string = '?SERVICE=WFS&MAP={}'.format(
            urllib.parse.quote(project))
        request = post_data.format(name='4326-test1',
                                   version='1.1.0',
                                   srsName='EPSG:4326',
                                   coordinates='10.67,52.48')
        header, body = self._execute_request(
            query_string,
            requestMethod=QgsServerRequest.PostMethod,
            data=request.encode('utf-8'))

        # Verify
        vl = QgsVectorLayer(
            self.testdata_path +
            'test_project_wms_grouped_layers.gpkg|layername=as_symbols',
            'as_symbols')
        self.assertTrue(vl.isValid())
        feature = next(
            vl.getFeatures(
                QgsFeatureRequest(QgsExpression('"name" = \'4326-test1\''))))
        geom = feature.geometry()

        tr = QgsCoordinateTransform(
            QgsCoordinateReferenceSystem.fromEpsgId(4326), vl.crs(),
            QgsCoordinateTransformContext())

        geom_4326 = QgsGeometry.fromWkt('point( 10.67 52.48)')
        geom_4326.transform(tr)
        self.assertEqual(geom.asWkt(0), geom_4326.asWkt(0))

        # Now: insert a feature in layer's CRS
        request = post_data.format(name='25832-test1',
                                   version='1.1.0',
                                   srsName='EPSG:25832',
                                   coordinates='613412,5815738')
        header, body = self._execute_request(
            query_string,
            requestMethod=QgsServerRequest.PostMethod,
            data=request.encode('utf-8'))

        feature = next(
            vl.getFeatures(
                QgsFeatureRequest(QgsExpression('"name" = \'25832-test1\''))))
        geom = feature.geometry()
        self.assertEqual(geom.asWkt(0), geom_4326.asWkt(0))
Ejemplo n.º 15
0
m = hashlib.md5()
m.update(requestMD5)
hexdig = m.hexdigest()

request += '&requesttoken=%s' % hexdig

request += '&deviceids=%s' % ','.join(sensors)
#request += '&measurementfroms=%s' % ('0,' * len(sensors))
#request += '&measurementcounts=%s' % ('50,' * len(sensors))

http_header = {
                "User-Agent" : "remotemonitor/248 CFNetwork/758.2.8 Darwin/15.0.0",
                "Accept-Language" : "en-us",
                "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
                "Host" : "www.data199.com:8080",
                }

# create an urllib.request opener()
opener = urllib.request.build_opener()

# create your HTTP request
req = urllib.request.Request('https://www.data199.com/api/v1/dashboard', request.encode('utf-8'), http_header)

# submit your request
while True:
    res = opener.open(req)
    parseJSON(json.loads(res.read()))
    print('-' * 40)
    time.sleep(10*60)	# wait for 10 minutes
Ejemplo n.º 16
0
    async def proxy_connect(
        self,
        proxy_uri: ProxyURI,
        wsuri: WebSocketURI,
        ssl: Optional[Union[SSLContext, bool]] = None,
        server_hostname: Optional[str] = None,
    ) -> None:
        """
        Issue a CONNECT request, read a response and upgrade the connection
        to TLS, if necessary.

        :param proxy_uri: the URI of the HTTP proxy
        :param wsuri: the original WebSocket URI to connect to
        :param ssl: an optional :class:`~ssl.SSLContext` with
            TLS settings for the proxied HTTPS connection; ``None``
            for not allowing TLS
        :raises ValueError: if the proxy returns an error code

        """
        request_headers = Headers()

        if wsuri.port == (443 if wsuri.secure else 80):  # pragma: no cover
            request_headers["Host"] = wsuri.host
        else:
            request_headers["Host"] = f"{wsuri.host}:{wsuri.port}"

        if proxy_uri.user_info:
            request_headers["Proxy-Authorization"] = build_authorization_basic(
                *proxy_uri.user_info
            )

        logger.debug("%s > CONNECT %s HTTP/1.1", self.side, f"{wsuri.host}:{wsuri.port}")
        logger.debug("%s > %r", self.side, request_headers)

        request = f"CONNECT {wsuri.host}:{wsuri.port} HTTP/1.1\r\n"
        request += str(request_headers)

        self.transport.write(request.encode())

        try:
            status_code, reason, headers = await read_response(self.reader)
        except asyncio.CancelledError:  # pragma: no cover
            raise
        except Exception as exc:
            raise InvalidMessage("did not receive a valid HTTP response") from exc

        logger.debug("%s < HTTP/1.1 %d %s", self.side, status_code, reason)
        logger.debug("%s < %r", self.side, headers)

        if not 200 <= status_code < 300:
            # TODO improve error handling
            raise ValueError(f"proxy error: HTTP {status_code} {reason}")

        if ssl is not None:
            transport = await self.loop.start_tls(
                self.transport,
                self,
                sslcontext=create_default_context(Purpose.SERVER_AUTH) if isinstance(ssl, bool) else ssl,
                server_side=False,
                server_hostname=server_hostname
            )
            self.reader = asyncio.StreamReader(limit=self.read_limit // 2, loop=self.loop)
            self.connection_made(transport)