makmani makmani - 1 year ago 140
Python Question

How to send data from server to client?

I am making an application that tries to send data to a client then the client should print these data .

I am using Flask as my back-end framework that handles the server side, and another python script that generate random Id for the current client, the client is listening every 4 seconds for any new json data comes in, if it gets data , it should print them for me.

Back-end code:

@app.route('/data/api/interact/<string:client_id>', methods=['GET','POST'])
def interact(client_id):

global data

form = Interact()
data = ''

if form.is_submitted():
get_data =
if get_data == 'hello':
data = 'Hi how are you ?'
return redirect(url_for('data_handler', client_id=client_id,
return render_template('interact.html', form=form, client_id=client_id)

@app.route('/data/api/interact/handler/', methods=['GET','POST'])
def data_handler():
client_id = request.args.get('client_id')
get_data = request.args.get('data')
return json.dumps({'client_id': client_id,'data':get_data})

Client script:

handler_url = ''

class check_data(threading.Thread):
def __init__(self, client_id):
self.event = threading.Event()
self.client_id = client_id
def run(self):
global handler_url
while not self.event.is_set():
file = urllib2.urlopen(handler_url)
xml =
print xml

def new_client():
client_id = "ClientId"+str(random.randrange(1,500))
return client_id

client_id = "null"
while client_id == "null":
client_id = new_client()
if "null" not in client_id:
print "Client ID: "+client_id
client = check_data(client_id)

Now, everything is working perfectly, but if i sent data from the server to client it just print this :

{"data": "", "client_id": null}

whereas in the server am getting a complete json data which returned from

Answer Source

The client_id is not passed to the server, the server expects to get client_id and data as query parameters. Instead you are accessing the url without any parameters

file = urllib2.urlopen(handler_url).

Passing query string parameters to GET request can be done with

url = handler_url + '?client_id' + self.client_id +'&data=YOURDATA_HERE'
file = urllib2.urlopen(url)

You can probably use urlencode to make this in a more elegant way.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download