I am running a simple python server application with grpc. This is the server code:
class Classifier(grpc_cl.BetaClassifierServicer):
def __init__(self):
default_config = self.getDefaultConfig()
self.engine_config = default_config["engine"]
self.port = default_config["daemon"]["port"]
# self.engine = loadLSTM3Model(self.engine_config)
def getDefaultConfig(self):
with open("service.properties.yaml", "r") as stream:
default_config = yaml.load(stream)
return default_config
def Analyze(self, request, context):
file_name = request.sentences_file
print "This is the file to analyze ", file_name
error = grpc_cl.Error(error_code = 0, error_message = "OK")
return grpc_cl.CategoryReply(error)
The client:
channel = implementations.insecure_channel('localhost', 50051)
stub = classifier_grpc.beta_create_Classifier_stub(channel)
reply = stub.Analyze(classifier_grpc.CategoryRequest(user_context=1, sentences_file="file"), 10000)
print 'Answer', reply.error.error_message
And the .proto file with the messages:
syntax = "proto3";
service Classifier{
rpc Analyze(CategoryRequest) returns (CategoryReply){}
rpc Train(TrainRequest) returns (CategoryReply){}
}
message CategoryRequest{
int32 user_context = 1;
string sentences_file = 2;
}
message CategoryReply{
Error error = 1;
string categories_file = 2;
}
message Error{
int32 error_code = 1;
string error_message = 2;
}
Launching the server and the client, and connecting both of them to the respective port, gives me this error:
Traceback (most recent call last):
File "/home/~/service/client.py", line 19, in <module>
reply = stub.Analyze(classifier_grpc.CategoryRequest(user_context=1, sentences_file="file"), 10000)
File "/usr/local/lib/python2.7/dist-packages/grpc/framework/crust/implementations.py", line 73, in __call__
protocol_options, metadata, request)
File "/usr/local/lib/python2.7/dist-packages/grpc/framework/crust/_calls.py", line 109, in blocking_unary_unary
return next(rendezvous)
File "/usr/local/lib/python2.7/dist-packages/grpc/framework/crust/_control.py", line 412, in next
raise self._termination.abortion_error
grpc.framework.interfaces.face.face.RemoteError
Does somebody now why this happens? Also, I could extract the user_context from the CategoryRequest, but not the sentences_file string, that one is blank.
grpc.framework.interfaces.face.face.RemoteError indicates that an exception occurred on the server while processing the request.
In your case, protobuf parameters need to be specified by keyword, ie
return grpc_cl.CategoryReply(error)
should be
return grpc_cl.CategoryReply(error=error)
Related
Traceback (most recent call last):
File "/usr/lib/python3.9/threading.py", line 973, in _bootstrap_inner
self.run()
File "/usr/lib/python3.9/threading.py", line 910, in run
self._target(*self._args, **self._kwargs)
File "/home/jeevan/.venv/lib/python3.9/site-packages/paho/mqtt/client.py", line 3591, in _thread_main
self.loop_forever(retry_first_connection=True)
File "/home/jeevan/.venv/lib/python3.9/site-packages/paho/mqtt/client.py", line 1756, in loop_forever
rc = self._loop(timeout)
File "/home/jeevan/.venv/lib/python3.9/site-packages/paho/mqtt/client.py", line 1164, in _loop
rc = self.loop_read()
File "/home/jeevan/.venv/lib/python3.9/site-packages/paho/mqtt/client.py", line 1556, in loop_read
rc = self._packet_read()
File "/home/jeevan/.venv/lib/python3.9/site-packages/paho/mqtt/client.py", line 2439, in _packet_read
rc = self._packet_handle()
File "/home/jeevan/.venv/lib/python3.9/site-packages/paho/mqtt/client.py", line 3039, in _packet_handle
return self._handle_connack()
File "/home/jeevan/.venv/lib/python3.9/site-packages/paho/mqtt/client.py", line 3138, in _handle_connack
on_connect(
File "/home/jeevan/.venv/lib/python3.9/site-packages/flask_mqtt/init.py", line 238, in _handle_connect
self._connect_handler(client, userdata, flags, rc)
File "/home/jeevan/nightlight-server/test_server.py", line 34, in handle_telemetry
payload = json.loads(message.payload.decode())
AttributeError: 'dict' object has no attribute 'payload'
^Z
[1]+ Stopped python3 test_server.py
```python
from web3 import Web3, HTTPProvider, IPCProvider, WebsocketProvider
from flask import Flask
from flask_mqtt import Mqtt
import time
import json as json
import json
import time
import paho.mqtt.client as mqtt
id = '20'
client_telemetry_topic = id + '/telemetry'
server_command_topic = id + '/commands'
client_name = id + '_nightlight_server'
mqtt_client = mqtt.Client(client_name)
mqtt_client.connect('test.mosquitto.org')
app = Flask(__name__)
app.config['test.mosquitto.org'] = 'yourbroker.com' # your broker address goes here
app.config['MQTT_BROKER_PORT'] = 1883 # default port for non-tls connection
app.config['MQTT_USERNAME'] = '' # No username set for now
app.config['MQTT_PASSWORD'] = '' # no password set for now
app.config['MQTT_KEEPALIVE'] = 5 # keepalive every 5 seconds
app.config['MQTT_TLS_ENABLED'] = False # set TLS to disabled for testing purposes
mqtt_client.loop_start()
mqtt = Mqtt()
mqtt.init_app(app)
running = True
#mqtt.on_connect()
def handle_telemetry(client, userdata, message, rc):
payload = json.loads(message.payload.decode())
print("Message received:", payload)
command ={'led_on' : payload['light'] < 300 }
print("Sending messages:", command)
print('connectedquot');
mqtt.subscribe('client_telemetry_topic') #your MQTT topic here
while running == True:
#mqtt.on_message()
def handle_mqtt_message(client, userdata, message):
data = dict(
topic=message.topic,
payload=message.payload.decode()
)
light = (data[quotpayloadquot])
light = int(light)
print (light)
#our function to store the MQTT payload on Ethereum goes here as store_results(barcode)
print (quotOKquot)
mqtt_client.subscribe(client_telemetry_topic)
mqtt_client.on_message = handle_telemetry
while True:
time.sleep(2)
w3 = Web3(HTTPProvider('https://ropsten.infura.io/inufrra api goes here'))
contract_address ='0x5a3AaF5274888e309f6dE86412389aaEaC01DE8B'
wallet_private_key = 'wallet private key goes here'
wallet_address = 'wallet address goes here'
contract = w3.eth.contract(address = contract_address, abi = abi)
def store_results(x):
nonce = w3.eth.getTransactionCount(wallet_address)
#if something is failing, try print (nonce) to test connectivity to Infura here. Chain ID = 3 is Ropst>
#Below, we craft a transaction to set variable x in the smart contract to the value provided to this f>
txn_dict = contract.functions.set(x).buildTransaction({
'chainId': 3,
'gas': 140000,
'gasPrice': w3.toWei('40', 'gwei'),
'nonce': nonce,
})
#Then we sign the transaction with our private key
signed_txn = w3.eth.account.signTransaction(txn_dict, private_key=wallet_private_key)
#The signed transaction is sent to the blockchain using Infura as an endpoint
result = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
# Then we wait for a receipt. It can take a short while.
tx_receipt = w3.eth.getTransactionReceipt(result)
count = 0
while tx_receipt is None and (count <, 30):
time.sleep(10)
tx_receipt = w3.eth.getTransactionReceipt(result)
return(tx_receipt)
if tx_receipt is None:
tx_receipt = quot;Failed"
return(tx_receipt)
```
I wrote a code of a Server that uses HTTP protocol to communicate with chrome browser, and for some reason I am getting an Exception.
the exception is an index out of bound exception but the server still gives a response to chrome and I can see the answer on the html file displayed on the screen. (the exception is in recv in the function get_clients_req()).
I would be happy if someone could explain me why.
import socket
IP = '127.0.0.1'
PORT = 80
def get_clients_req(client):
recv = client.recv(2 ** 16).decode()
recv = recv.split('\n')[0].split('/')
recv = recv[1].split(' ')[0].split('?')
return recv[0], recv[1].split('&')
def clean_data(request, params):
valid = False
clean_params = []
error_msg = 'Not Valid Request'
if request == 'calculate-area' and len(params) == 2:
if 'height' in params[0] and 'width' in params[1]:
print(params[0], params[1])
valid = True
error_msg = 'Everything is just Fine <3<3'
clean_params.append(params[0].replace('height=', ''))
clean_params.append(params[1].replace('width=', ''))
print(clean_params[0], clean_params[1])
else:
valid = False
error_msg = 'Parameters are not valid'
clean_params = []
else:
valid = False
error_msg = 'Request is not valid'
clean_params = []
return (valid, error_msg, clean_params)
def handle_request(client, clean_params):
area = int(clean_params[0]) * int(clean_params[1]) / 2
data = 'HTTP/1.1 200 OK \r\n'
data = 'HTTP/1.1 200 OK \r\n'
data += 'Connect-Type: text/html; charset=utf-8\r\n'
data += '\r\n'
data += f'<html><body>{area}</body></html>\r\n\r\n'
client.sendall(data.encode())
client.shutdown(socket.SHUT_WR)
server = socket.socket()
server.bind((IP, PORT))
server.listen()
print(f'URL: {IP}:{PORT}')
while 1:
client, client_add = server.accept()
request, params = get_clients_req(client)
(valid, error_msg, clean_params) = clean_data(request, params)
handle_request(client, clean_params)
the exception:
Traceback (most recent call last):
File "C:/Users/orlav/PycharmProjects/networks_book/chapter_4/e4.8.py", line 56, in <module>
request, params = get_clients_req(client)
File "C:/Users/orlav/PycharmProjects/networks_book/chapter_4/e4.8.py", line 11, in get_clients_req
return recv[0], recv[1].split('&')
IndexError: list index out of range
recv = recv[1].split(' ')[0].split('?')
return recv[0], recv[1].split('&')
There is no recv[1] in the last line if there is no ? in the original request, which causes the stack trace you see. While you don't show the original request you intended to send, the browser will often try to access some /facicon.ico by itself and this request has no ?.
Here is the error:
No handlers could be found for logger "suds.client"
Traceback (most recent call last):
File "bling.py", line 134, in <module>
get_data("146.215.236.10", list)
File "bling.py", line 48, in get_data
retval = client.service.SelectCmDevice("", stuff)
File "/usr/lib/python2.6/site-packages/suds/client.py", line 542, in __call__
return client.invoke(args, kwargs)
File "/usr/lib/python2.6/site-packages/suds/client.py", line 602, in invoke
result = self.send(soapenv)
File "/usr/lib/python2.6/site-packages/suds/client.py", line 649, in send
result = self.failed(binding, e)
File "/usr/lib/python2.6/site-packages/suds/client.py", line 702, in failed
r, p = binding.get_fault(reply)
File "/usr/lib/python2.6/site-packages/suds/bindings/binding.py", line 265, in get_fault
raise WebFault(p, faultroot)
suds.WebFault: Server raised fault: 'org.xml.sax.SAXParseException: Element type "SelectItem" must be followed by either attribute specifications, ">" or "/>".'
Here is the code:
def get_data(ip, list):
"""
Connect to soap webservice
Append device name and status
To data list
"""
stuff = {}
stuff['SelectBy'] = 'Name'
count = 0
for i in list:
if "SelectItems" not in stuff:
stuff['SelectItems'] = {}
if 'SelectItem[' + str(count) + ']' not in stuff['SelectItems']:
stuff['SelectItems']['SelectItem[' + str(count) + ']'] = {}
stuff['SelectItems']['SelectItem[' + str(count) + ']']['Item'] = i
count = count + 1
t = HttpAuthenticated(**credentials)
uri = 'https://' + ip + ':8443/realtimeservice/services/RisPort?wsdl'
imp = Import('http://schemas.xmlsoap.org/soap/encoding/')
doctor = ImportDoctor(imp)
client = Client(url=uri, transport=t, doctor=doctor)
retval = client.service.SelectCmDevice("", stuff)
pprint(retval)
sys.exit(0)
for node in retval['SelectCmDeviceResult'].CmNodes:
for dev in node.CmDevices:
name = dev.Name
status = dev.Status
data.append([name,status])
I am trying to call the Cisco Risport API with Python however even when emulating how it is done in PHP I get an error and I am really trying not to port over to PHP at this point in the project.
Here is how PHP passes the data:
foreach ($devices_chunks as $chunk){
echo '.';
//Prepare RisPort request
$array["SelectBy"] = "Name";
$array["Status"] = "Registered";
//$array["Class"] = "Phone";
//$array["MaxReturnedDevices"] = "1000";
$i = 1;
foreach($chunk as $device){
$array["SelectItems"]["SelectItem[$i]"]["Item"] = $device->name;
$i++;
}
// Run RisPost Query + wait a bit as max requests is 15 per min.
$response = $soap_ris->SelectCmDevice("",$array);
I think the problem is with how suds is transposing the dict of dict to XML, any thoughts on how to fix this outside of manually building SOAP XML request?
thanks!
I have my rpi connected up to a digital scales via RS232, a MAX3232 serial port / ttl module connected into the GPIO. Successfully collected the weight data streaming from the scales using this code (data is in blocks of 20 and the weight is at 11 - 14). This prints it out locally in terminal:
import serial
import time
ser = serial.Serial("/dev/ttyAMA0")
read = ser.read(20)
def get_num(read):
return float(''.join(ele for ele in read if ele.isdigit() or ele == '.'))
while True:
print(get_num(read))
time.sleep(2)
This works great but my python code to send datastream to xively isn't so good.
def get_num(read):
return float(''.join(ele for ele in read if ele.isdigit() or ele == '.'))
# function to return a datastream object. This either creates a new datastream,
# or returns an existing one
def get_datastream(feed):
try:
datastream = feed.datastreams.get("(get_num(read))")
return datastream
except:
datastream = feed.datastreams.create("(get_num(read))", tags = "weight")
return datastream
def run():
feed = api.feeds.get(FEED_ID)
datastream = get_datastream(feed)
datastream.max_value = None
datastream.min_value = None
while True:
weight = get_num(read)
datastream.current_value = weight
datastream.at = datetime.datetime.utcnow()
try:
datastream.update()
except requests.HTTPError as e:
print "HTTPError({0}): {1}".format(e.errno, e.strerror)
time.sleep(5)
run()
It checks out OK in IDLE - but when run it generates an error as follows:
Traceback (most recent call last):
File "xivelycodescales.py", line 51, in <module>
run()
File "xivelycodescales.py", line 36, in run
datastream = get_datastream(feed)
File "xivelycodescales.py", line 32, in get_datastream
datastream = feed.datastreams.create("(get_num(read))")
File "/usr/local/lib/python2.7/dist-packages/xively/managers.py", line 416, in create
response.raise_for_status()
File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 773, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 422 Client Error:
I can see what the error type is - and had good help at the RPI forums. But can't figure out where I've gone wrong
Many thanks
When trying to send and decode an integer using socketserver and port, I get the following error ValueError: invalid literal for int() with base 10: '' (full stack trace at end). I marked the place where the error is with #<----- in the client. Note that I've tried all of the following: Increasing the buffer size, sending it as a string, trying every caste I could think of (to string then int, to float, to int before sending it, to byte then to int, etc.) though I may have missed one.
This is the code for my server:
import socketserver
import threading
import gameplayer
class GameServer:
class GameServerUDPHandler(socketserver.BaseRequestHandler):
def handle_register(self, socket, client_address):
number = len(self.server.base.players) # Zero based
number = number + 1 # One based
socket.sendto(bytes(number), client_address)
self.server.base.players[number] = gameplayer.GamePlayer(id=number)
print(self.server.base.players)
def handle(self):
data = self.request[0].strip()
data = str(data, 'utf-8')
print(data)
socket = self.request[1]
data = data.split('\n')
option = data[0]
print(option)
c_add = self.client_address
if option == "register":
self.handle_register(socket, c_add)
print("test")
elif option == "get_postion":
handle_get_postion(socket, c_add, data[1])
elif option == "change_postion":
hande_changed_postion(socket, c_add, data[1])
# print("{} wrote:".format(self.client_address[0]))
# socket.sendto(data.upper(), self.client_address)
def __init__(self, port):
self.server = socketserver.UDPServer(("localhost", port), self.GameServerUDPHandler)
self.server.base = self
self.players = {}
def start_server(self):
threading.Thread(target=self.server.serve_forever).start()
And my client (where the error is):
class GameClient:
def __init__(self, port, host):
self.port = port
self.host = host
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def register(self):
self.socket.sendto(bytes("register\n", "utf-8"), (self.host, self.port))
self.numberID = int(self.socket.recv(10240).strip()) #<- WHERE ISSUE IS
print("Received: {}".format(self.numberID))
Full Output (Error starts at part marked):
register
register
{1: <gameplayer.GamePlayer object at 0x10078e390>}
test
Traceback (most recent call last): #<---- Where the error starts in the output.
File "main.py", line 8, in <module>
client.register()
File "/Users/Mike/Desktop/Main/Programming/Work Space/Python/Game/gameclient.py", line 12, in register
self.numberID = int(self.socket.recv(10240))
ValueError: invalid literal for int() with base 10: ''
Change following line in the server code:
socket.sendto(bytes(number), client_address)
with:
socket.sendto(str(number).encode('utf-8'), client_address)
>>> bytes(3)
b'\x00\x00\x00'
>>> str(3)
'3'
>>> str(3).encode('utf')
b'3'
And the cause of the traceback
>>> int(bytes(3))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''