Getting an error while trying to pass arguments from command line - python

I am trying to create a python script file with multiple functions and pass 3 arguments to the main functions. These parameters are also passed onto other functions with the script. My code looks somewhat like this:
import benepar
import spacy
import json
import gc
import typer
from spacy.tokens import Doc,DocBin
from typing import Tuple, List
from pathlib import Path
def main(nlp_dir: Path,inp_File:Path,out_File:Path):
try:
seg_obj=load_nlp_object(nlp_dir)
print('Loaded nlp obj')
doc_train=DocBin().from_disk(inp_File)
docs=get_list_of_docs(doc_train,nlp_dir)
data=[]
except Exception as e:
print(e)
chunk_count=0
for d in docs:
try:
temp=seg_obj(d)
chunk_count=chunk_count+1
if chunk_count%5 == 0:
seg_obj=load_nlp_object(nlp_dir)
gc.collect()
#Other code
except Exception as e:
print(e)
#Saving linker data
for val in data:
with open(out_File,'a',encoding='utf8') as f:
json.dump(val,f)
f.write(",\n")
print('Data created successfully.')
def load_nlp_object(nlp_dir):
#Code
return nlp
def get_list_of_docs(bin_obj,nl):
n=load_nlp_object(nl)
dcs=list(bin_obj.get_docs(n.vocab))
return dcs
def benepar_split(doc: Doc) -> List[Tuple]:
#Code
return split_indices
if __name__=='__main__':
typer.run(main)
While running I get the following error:
Traceback (most recent call last):
File "C:\Users\Shrinidhi\Desktop\Sentiment Analysis\Project\create_linker_data.py", line 96, in <module>
typer.run(main)
File "C:\Users\Shrinidhi\Desktop\Sentiment Analysis\sentiment\lib\site-packages\typer\main.py", line 864, in run
app()
File "C:\Users\Shrinidhi\Desktop\Sentiment Analysis\sentiment\lib\site-packages\typer\main.py", line 214, in __call__
return get_command(self)(*args, **kwargs)
File "C:\Users\Shrinidhi\Desktop\Sentiment Analysis\sentiment\lib\site-packages\click\core.py", line 1128, in __call__
return self.main(*args, **kwargs)
File "C:\Users\Shrinidhi\Desktop\Sentiment Analysis\sentiment\lib\site-packages\click\core.py", line 1053, in main
rv = self.invoke(ctx)
File "C:\Users\Shrinidhi\Desktop\Sentiment Analysis\sentiment\lib\site-packages\click\core.py", line 1395, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "C:\Users\Shrinidhi\Desktop\Sentiment Analysis\sentiment\lib\site-packages\click\core.py", line 754, in invoke
return __callback(*args, **kwargs)
File "C:\Users\Shrinidhi\Desktop\Sentiment Analysis\sentiment\lib\site-packages\typer\main.py", line 500, in wrapper
return callback(**use_params) # type: ignore
TypeError: main() got an unexpected keyword argument 'inp_file'
I have debugged by code but I am unable to find the root cause. My command line command is python create_linker_data.py "Entity Linker\\ner_obj\\" "Named Entity Recognition\\sentiment_data\\3\\3.spacy" "Entity Linker\\data\\entity_linker_3.txt"

Related

eBay and Authlib Unconventional token type

I'm trying to use Authlib library to access new eBay REST API (as Authorization code grant)
Here is my code;
import json
import os
import webbrowser
from time import time
from authlib.integrations.requests_client import OAuth2Session
from rpi_order_data_sync import settings
def auth(seller):
def token_updater(token, seller=seller):
if not os.path.exists(seller):
open(seller, "w").close()
with open(seller, "w") as token_file:
json.dump(token, token_file)
scope = ["https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly"]
if not os.path.exists(seller):
ebay = OAuth2Session(
settings.E_APP_ID,
settings.E_CERT_ID,
redirect_uri=settings.E_RU_NAME,
scope=scope,
)
uri, state = ebay.create_authorization_url(
"https://auth.sandbox.ebay.com/oauth2/authorize",
)
print("Please go to {} and authorize access.".format(uri))
try:
webbrowser.open_new_tab(uri)
except webbrowser.Error:
pass
authorization_response = input("Please enter callback URL: ") # nosec
token = ebay.fetch_token(
"https://api.sandbox.ebay.com/identity/v1/oauth2/token",
authorization_response=authorization_response,
)
print(token)
token_updater(token)
return ebay
The problem is eBay's token response has an unconventional token type named "User Access Token" instead of "Bearer". Therefore I get this error;
Traceback (most recent call last):
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/authlib/integrations/requests_client/oauth2_session.py", line 37, in __call__
req.url, req.headers, req.body = self.prepare(
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/authlib/oauth2/auth.py", line 91, in prepare
sign = self.SIGN_METHODS[token_type.lower()]
KeyError: 'user access token'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/bin/rods", line 11, in <module>
load_entry_point('rpi-order-data-sync', 'console_scripts', 'rods')()
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/click/core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/home/thiras/HDD/freelancer/contentassasin/rpi-order-data-sync/rpi_order_data_sync/main.py", line 132, in sync_ebay_orders
orders = ebay.get(
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/requests/sessions.py", line 543, in get
return self.request('GET', url, **kwargs)
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/authlib/integrations/requests_client/oauth2_session.py", line 113, in request
return super(OAuth2Session, self).request(
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/requests/sessions.py", line 516, in request
prep = self.prepare_request(req)
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/requests/sessions.py", line 449, in prepare_request
p.prepare(
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/requests/models.py", line 318, in prepare
self.prepare_auth(auth, url)
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/requests/models.py", line 549, in prepare_auth
r = auth(self)
File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/authlib/integrations/requests_client/oauth2_session.py", line 41, in __call__
raise UnsupportedTokenTypeError(description=description)
authlib.integrations.base_client.errors.UnsupportedTokenTypeError: unsupported_token_type: Unsupported token_type: 'user access token'
I've noticed Compliance fix for non-standard section at Authlib documentation but couldn't figure out how to do this fix or even possible in this way.
I've found a solution and it also works with requests-oauthlib package. It seems working flawlessly so far. The main struggle was to create a fake request.Response model since request.Response has no setter for .text or .content attributes so modifying them was impossible.
So I've created a FakeResponse class that only mimics .json() method since it was the only method used by Authlib.
class FakeResponse:
""" Fake Class for Request Response class. """
def __init__(self, data):
self.data = data
def json(self):
""" Mocks requests.Response.json(). """
return self.data
After that I've created an access_token_response hook;
def non_compliant_token_type(resp):
data = resp.json()
data["token_type"] = "Bearer"
fake_resp = FakeResponse(data=data)
return fake_resp
Please let me know if you have a better answer or any recommendations to improve it.

Error while building a RESTApi using flask_restful

Flask RESTApi newbie here
I am trying to build a RESTapi service in Flask (and I am trying to save the output as a .txt file) using flask_restful for a code of mine using the pydifact module as follows:
import datetime
from pydifact.message import Message
from pydifact.segments import Segment
from flask import Flask, request
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class RestAPI(Resource):
def get(self, ABSENDER_ID, EMPFÄNGER_ID, ERSTELLUNG_DATUM_ZEIT, REFERENCE):
MSCONS = Message()
def erstellung_datum_zeit(dt_time):
# Needed for the UNB segment
dt_time = dt_time.strftime('%Y%m%d%H%M')
return dt_time
def UNA_UNB_segment(absender_id, empfänger_id, erst_datum, ref):
MSCONS.add_segment(Segment('UNA', ":+.? '"))
MSCONS.add_segment(Segment('UNB', ['UNOC', '3'], [absender_id, '14'], [
empfänger_id, '500'], [erst_datum[2:8], erst_datum[8:]], ref, '', 'TL'))
ERSTELLUNG_DATUM_ZEIT = str(
erstellung_datum_zeit(datetime.datetime.now()))
UNA_UNB_segment(ABSENDER_ID, EMPFÄNGER_ID,
ERSTELLUNG_DATUM_ZEIT, REFERENCE)
result = MSCONS.serialize()
final_result = result
PATH_FOR_TXT = r'C:\Users\kashy\OneDrive\Desktop\Codes\mscons.txt'
textfile = open(PATH_FOR_TXT, 'w')
textfile.write(result)
textfile.close()
return {'result': final_result}
api.add_resource(
RestAPI,
'/RestAPI/<int:ABSENDER_ID>/<int:EMPFÄNGER_ID/<int:ERSTELLUNG_DATUM_ZEIT/<int:REFERENCE>')
if __name__ == '__main__':
app.run(debug=True)
The ABSENDER_ID, EMPFÄNGER_ID, ERSTELLUNG_DATUM_ZEIT, REFERENCE should all be user inputs and they should be all in string format.
When I do /RestAPI/<str:ABSENDER_ID>/<str:EMPFÄNGER_ID/<str:ERSTELLUNG_DATUM_ZEIT/<str:REFERENCE>, i get the following error:
C:\Users\kashy\OneDrive\Desktop\Codes\pydifact> & C:/Users/kashy/Anaconda3/envs/py36/python.exe c:/Users/kashy/OneDrive/Desktop/Codes/api.py
Traceback (most recent call last):
File "c:/Users/kashy/OneDrive/Desktop/Codes/api.py", line 44, in <module>
self.url_map.add(rule)
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\werkzeug\routing.py", line 1401, in add
rule.bind(self)
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\werkzeug\routing.py", line 730, in bind
self.compile()
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\werkzeug\routing.py", line 790, in compile
_build_regex(self.rule if self.is_leaf else self.rule.rstrip("/"))
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\werkzeug\routing.py", line 779, in _build_regex
convobj = self.get_converter(variable, converter, c_args, c_kwargs)
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\werkzeug\routing.py", line 738, in get_converter
raise LookupError("the converter %r does not exist" % converter_name)
LookupError: the converter 'str' does not exist
and when I do
/RestAPI/<int:ABSENDER_ID>/<int:EMPFÄNGER_ID/<int:ERSTELLUNG_DATUM_ZEIT/<int:REFERENCE>, I get the following error:
PS C:\Users\kashy\OneDrive\Desktop\Codes\pydifact> & C:/Users/kashy/Anaconda3/envs/py36/python.exe c:/Users/kashy/OneDrive/Desktop/Codes/api.py
Traceback (most recent call last):
File "c:/Users/kashy/OneDrive/Desktop/Codes/api.py", line 44, in <module>
'/RestAPI/<int:ABSENDER_ID>/<int:EMPFÄNGER_ID/<int:ERSTELLUNG_DATUM_ZEIT/<int:REFERENCE>')
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\flask_restful\__init__.py", line 382, in add_resource
self._register_view(self.app, resource, *urls, **kwargs)
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\flask_restful\__init__.py", line 448, in _register_view
app.add_url_rule(rule, view_func=resource_func, **kwargs)
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\flask\app.py", line 98, in wrapper_func
return f(self, *args, **kwargs)
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\flask\app.py", line 1277, in add_url_rule
self.url_map.add(rule)
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\werkzeug\routing.py", line 1401, in add
rule.bind(self)
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\werkzeug\routing.py", line 730, in bind
self.compile()
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\werkzeug\routing.py", line 790, in compile
_build_regex(self.rule if self.is_leaf else self.rule.rstrip("/"))
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\werkzeug\routing.py", line 766, in _build_regex
for converter, arguments, variable in parse_rule(rule):
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\werkzeug\routing.py", line 226, in parse_rule
raise ValueError("malformed url rule: %r" % rule)
ValueError: malformed url rule: '/RestAPI/<int:ABSENDER_ID>/<int:EMPFÄNGER_ID/<int:ERSTELLUNG_DATUM_ZEIT/<int:REFERENCE>'
I am totally new to this and just started learning it using the Building a REST API using Python and Flask | Flask-RESTful tutorial.
Can anyone please tell me what is the mistake I am doing?
Your url routes have problem. In the first one, it should be string instead of str and in the second one you have a missing > at the end of int:EMPFÄNGER_ID and int:ERSTELLUNG_DATUM_ZEIT
Correct ones should be:
/RestAPI/<string:ABSENDER_ID>/<string:EMPFANGER_ID>/<string:ERSTELLUNG_DATUM_ZEIT>/<string:REFERENCE>
and
/RestAPI/<int:ABSENDER_ID>/<int:EMPFANGER_ID>/<int:ERSTELLUNG_DATUM_ZEIT>/<int:REFERENCE>
Note: I replaced Ä with A in urls above because that might also cause malformed url rule issue.

Click-config file produces error

I am using click-configfile (an extension of Click) to have it read command line args straight from a config file:
class ConfigSectionSchema(object):
"""Describes all config sections of this configuration file."""
#matches_section("POOL_CONFIG") # Matches multiple sections
class Pool(SectionSchema):
pooluser = Param(type=str)
pool = Param(type=str)
poolpassword = Param(type=str)
class ConfigFileProcessor(ConfigFileReader):
config_files = ["xenbuilder.config"]
config_section_schemas = [
ConfigSectionSchema.Pool
]
CONTEXT_SETTINGS = dict(default_map=ConfigFileProcessor.read_config())
class ZenConnection(object):
def __init__(self, pool, pooluser, poolpassword):
self.pool = pool
self.pooluser = pooluser
self.poolpassword = poolpassword
# Pool Connection param args
#click.group()
#click.command(context_settings=CONTEXT_SETTINGS)
#click.option(
'--pool',
help='Pool Server to connect to'
)
#click.option(
'--pooluser',
help='Connecting as Pool User'
)
#click.option(
'--poolpassword',
hide_input=True,
help='Password to authenticate in the Xen Pool'
)
#click.pass_context
def cli(ctx,pool,pooluser,poolpassword):
""" BSD Xen VM Builder """
ctx.obj = ZenConnection(pool, pooluser, poolpassword)
#click.pass_obj
def xen_session(ctx):
logging.info('INFO: Establishing Connection...')
try:
session = XenAPI.Session(str(ctx.pool))
session.xenapi.login_with_password(str(ctx.pooluser),str(ctx.poolpassword))
print("Connection Successful!")
logging.info('INFO: Connection Successful!!')
except:
logging.error("ERROR: Unexpected Error - ", sys.exc_info()[0])
raise
return session
I am making sure to follow as closely to the tutorial found here. However, when I run the code, I constantly get this stack trace:
Traceback (most recent call last):
File "/usr/local/bin/bsdxenvmbuilder", line 9, in <module>
load_entry_point('bsdxenvmbuilder==0.1', 'console_scripts', 'bsdxenvmbuilder')()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 565, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 2697, in load_entry_point
return ep.load()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 2370, in load
return self.resolve()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 2376, in resolve
module = __import__(self.module_name, fromlist=['__name__'], level=0)
File "/Users/ryankahil/Xen-Builder/bsdxenbuilder.py", line 52, in <module>
#click.pass_context
File "/Library/Python/2.7/site-packages/click/decorators.py", line 115, in decorator
cmd = _make_command(f, name, attrs, cls)
File "/Library/Python/2.7/site-packages/click/decorators.py", line 71, in _make_command
raise TypeError('Attempted to convert a callback into a '
TypeError: Attempted to convert a callback into a command twice.
I know that error is when you are using a decorator incorrectly. But I am not sure how it is incorrect. Can anyone with knowledge of click-configfile be able to provide some guidance on this?
A click function can either be a group (a collection of commands) or a command, it cannot be both. So the problem is in these two lines:
#click.group()
#click.command(context_settings=CONTEXT_SETTINGS)
You will need to remove one of these decorators.

I wrote a project with tornado, but this exception is always in my log file

This is the error log:
[I 160308 11:09:59 web:1908] 200 GET /admin/realtime (117.93.180.216) 107.13ms
[E 160308 11:09:59 http1connection:54] Uncaught exception
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/tornado/http1connection.py", line 238, in _read_message
delegate.finish()
File "/usr/local/lib/python3.4/dist-packages/tornado/httpserver.py", line 290, in finish
self.delegate.finish()
File "/usr/local/lib/python3.4/dist-packages/tornado/web.py", line 1984, in finish
self.execute()
File "/usr/local/lib/python3.4/dist-packages/blueware-1.0.10/blueware/hooks/framework_tornado/web.py", line 480, in _bw_wrapper__RequestDispatcher_execute
future = wrapped(*args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/tornado/web.py", line 2004, in execute
**self.handler_kwargs)
File "/usr/local/lib/python3.4/dist-packages/blueware-1.0.10/blueware/hooks/framework_tornado/web.py", line 448, in _bw_wrapper_RequestHandler___init___
return wrapped(*args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/tornado/web.py", line 185, in init
self.initialize(**kwargs)
File "/usr/local/lib/python3.4/dist-packages/tornado/web.py", line 2714, in wrapper
self.redirect(url)
File "/usr/local/lib/python3.4/dist-packages/tornado/web.py", line 671, in redirect
self.finish()
File "/usr/local/lib/python3.4/dist-packages/blueware-1.0.10/blueware/hooks/framework_tornado/web.py", line 309, in _bw_wrapper_RequestHandler_finish_
return wrapped(*args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/tornado/web.py", line 934, in finish
self.flush(include_footers=True)
File "/usr/local/lib/python3.4/dist-packages/tornado/web.py", line 870, in flush
for transform in self._transforms:
TypeError: 'NoneType' object is not iterable
[I 160308 11:10:00 web:1908] 200 GET /admin/order?order_type=1&order_status=1&page=0&action=allreal (49.89.27.173) 134.53ms
Can anyone tell me how to solve this problem? Thank you very much
I assume that OneAPM (blueware agent) is compatible with your python and Tornado version, however it's can be tricky.
Solution
Move self.redirect(url) from your handler initialize method to get method, like this
class MyHandler(tornado.web.RequestHandler):
def get(self):
self.redirect('/some_url')
or use RedirectHandler.
Every action that could finish request needs to be called in context of http-verb method (get, post, put and so on). The common mistake is making authetication/authorization in __init__ or initialize.
More detail
In Tornado's source there is a note about _transforms that is initialized in the constructor with None and set in_execute (oversimplifying - after headers_received).
A transform modifies the result of an HTTP request (e.g., GZip encoding).
Applications are not expected to create their own OutputTransforms
or interact with them directly; the framework chooses which transforms
(if any) to apply.
Reproduce
Sample that triggers this error. I'm including this only as a cross-check that blueware is not the cause:
import tornado.ioloop
import tornado.web
class SomeHandler(tornado.web.RequestHandler):
def initialize(self, *args, **kwargs):
url = '/some'
self.redirect(url)
# ^ this is wrong
def get(self):
# redirect should be here
self.write("Hello")
def make_app():
return tornado.web.Application([
(r"/", SomeHandler),
])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
And stacktrace:
ERROR:tornado.application:Uncaught exception
Traceback (most recent call last):
File "/tmp/py3/lib/python3.4/site-packages/tornado/http1connection.py", line 238, in _read_message
delegate.finish()
File "/tmp/py3/lib/python3.4/site-packages/tornado/httpserver.py", line 289, in finish
self.delegate.finish()
File "/tmp/py3/lib/python3.4/site-packages/tornado/web.py", line 2022, in finish
self.execute()
File "/tmp/py3/lib/python3.4/site-packages/tornado/web.py", line 2042, in execute
**self.handler_kwargs)
File "/tmp/py3/lib/python3.4/site-packages/tornado/web.py", line 183, in __init__
self.initialize(**kwargs)
File "test.py", line 8, in initialize
self.redirect(url)
File "/tmp/py3/lib/python3.4/site-packages/tornado/web.py", line 666, in redirect
self.finish()
File "/tmp/py3/lib/python3.4/site-packages/tornado/web.py", line 932, in finish
self.flush(include_footers=True)
File "/tmp/py3/lib/python3.4/site-packages/tornado/web.py", line 868, in flush
for transform in self._transforms:
TypeError: 'NoneType' object is not iterable

Twisted XML-RPC error

I get an exception on both client and server side when I run the first example at http://buildbot.twistedmatrix.com/builds/sphinx-html/291-15849/projects/web/howto/xmlrpc.html. The server code I used is below:
from twisted.web import xmlrpc, server
class Example(xmlrpc.XMLRPC):
"""An example object to be published."""
def xmlrpc_echo(self, x):
"""
Return all passed args.
"""
return x
def xmlrpc_add(self, a, b):
"""
Return sum of arguments.
"""
return a + b
def xmlrpc_fault(self):
"""
Raise a Fault indicating that the procedure should not be used.
"""
raise xmlrpc.Fault(123, "The fault procedure is faulty.")
if __name__ == '__main__':
from twisted.internet import reactor
r = Example()
reactor.listenTCP(7080, server.Site(r))
reactor.run()
Client side is below:
import xmlrpclib
s = xmlrpclib.Server('http://localhost:7080/')
print s.echo('Hello world')
The server side exception is:
Traceback (most recent call last):
File "/usr/lib/python2.6/dist-packages/twisted/web/xmlrpc.py", line 150, in render_POST
d.addCallback(self._cbRender, request, responseFailed)
File "/usr/lib/python2.6/dist-packages/twisted/internet/defer.py", line 260, in addCallback
callbackKeywords=kw)
File "/usr/lib/python2.6/dist-packages/twisted/internet/defer.py", line 249, in addCallbacks
self._runCallbacks()
File "/usr/lib/python2.6/dist-packages/twisted/internet/defer.py", line 441, in _runCallbacks
self.result = callback(self.result, *args, **kw)
--- <exception caught here> ---
File "/usr/lib/python2.6/dist-packages/twisted/web/xmlrpc.py", line 170, in _cbRender
allow_none=self.allowNone)
exceptions.TypeError: dumps() got an unexpected keyword argument 'allow_none'
Client side exception is:
Traceback (most recent call last):
File "./client.py", line 6, in <module>
print s.echo('Hello world')
File "/usr/local/lib/python2.6/dist-packages/xmlrpclib-1.0.1-py2.6.egg/xmlrpclib.py", line 986, in __call__
return self.__send(self.__name, args)
File "/usr/local/lib/python2.6/dist-packages/xmlrpclib-1.0.1-py2.6.egg/xmlrpclib.py", line 1239, in __request
verbose=self.__verbose
File "/usr/local/lib/python2.6/dist-packages/xmlrpclib-1.0.1-py2.6.egg/xmlrpclib.py", line 1037, in request
return self._parse_response(h.getfile(), sock)
File "/usr/local/lib/python2.6/dist-packages/xmlrpclib-1.0.1-py2.6.egg/xmlrpclib.py", line 1136, in _parse_response
p.close()
File "/usr/local/lib/python2.6/dist-packages/xmlrpclib-1.0.1-py2.6.egg/xmlrpclib.py", line 508, in close
self._parser.Parse("", 1) # end of data
xml.parsers.expat.ExpatError: no element found: line 1, column 0
Looks like you have an old version of xmlrpclib?
What version of python are you using?
Where is the xmlrpclib coming from that your xmlrpc server is using, and what version is it?
$ python -v
>>> import xmlrpclib
# /usr/lib/python2.6/xmlrpclib.pyc matches /usr/lib/python2.6/xmlrpclib.py
>>> xmlrpclib.__version__
'1.0.1'
>>> xmlrpclib.dumps((None,), allow_none=True)
'<params>\n<param>\n<value><nil/></value></param>\n</params>\n
i.e. this works for me. Perhaps you are somehow using an old version of xmlrpclib?

Categories