python jsonrpc2 client example connecting to remote hello world example using httplib?

流过昼夜 提交于 2019-12-08 07:56:08

问题


I am trying to create a jsonrpc2 server that will accept json over http , process the data and return json back to the requesting client.

I am quite new to rpc servers and wsgi and have only used it as part of a webframework like django.

I am attempting to follow the example given with the jsonrpc2 documentation. The first step is creating a file hello.py

def greeting(name):
    return dict(message="Hello, %s!" % name)

The next step involves starting the service

runjsonrpc2 hello
runserver :8080

I know the service is working since when I use a browser on a remote machine and browse to http://myip.dydns.org:8080 , It responds with "405 Method Not Allowed" and I see debug information on my server shell

DEBUG:root:jsonrpc
DEBUG:root:check method

The next step is what I am having a hard time understanding. I want to know how to create a python client to send json to the service and get a response.

What I tried is :

>>> from httplib import HTTPConnection
>>> h = HTTPConnection("myip.dydns.org:8080")
>>> from json import JSONEncoder
>>> call_values = {'jsonrpc':'2.0', 'method':'greeting', 'id':'greeting'}

What are the steps involved to get the response from the webservice using python.

Sadly the jsonrpc2 documentation only uses a TestApp from a webtest library to test on localhost.

I could not find any sample python code that creates a client from a remote machine and gets a response for the greeting function.

Can someone help me to get started.

edit: I got a little further . But I still cannot get the contents of the response

>>> from httplib import HTTPConnection
>>> con = HTTPConnection("myip.dyndns.org:8080")
>>> import json
>>> con.request('POST', '/', json.dumps({"jsonrpc": "2.0", "method": "casoff_jsonrpc2.greeting", "id":1.0,"params":{"name":"harijay"}},ensure_ascii=False).encode('utf-8'), {'Content-Type': 'application/json;charset=utf-8'})

I see the server then echo to its shell

DEBUG:root:jsonrpc
DEBUG:root:check method
DEBUG:root:check content-type
DEBUG:root:response {"jsonrpc": "2.0", "id": 1.0, "result": {"message": "Hello, harijay!"}}

But on the client. I dont know how to get the result.

edit2: I finally solved this

All I had to do was

>>> con.getresponse().read()

回答1:


Try excellent package requests

I you intend to do anything with http clients in Python, I would highly recommend learning requests - it is an order of magnitude easier to learn and use than any other http related module in Python and for me it became sort of Swiss army knife when experimenting over http.

Example of how to use if for JSON-RPC is here: https://stackoverflow.com/a/8634905/346478



来源:https://stackoverflow.com/questions/23314254/python-jsonrpc2-client-example-connecting-to-remote-hello-world-example-using-ht

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!