سؤال

Here is one of my functions:

def connect():
    c = xmlrpclib.ServerProxy('http://username:password@host',
                allow_none=True,
            )
    return c

How do I check if the username and password are correct in this method before returning c?

هل كانت مفيدة؟

المحلول

You can check if the provided credentials are valid by using this trick (provided that the plone site has wsapi4plone correctly installed):

>>> server = xmlrpclib.ServerProxy("http://admin:admin@localhost:8080/plone")
>>> server.get_schema('Document')
{'creators': {'required': False, 'type': 'lines'}, 'description': ...
>>> baduser_server = xmlrpclib.ServerProxy("http://bad:bad@localhost:8080/plone")
>>> baduser_server.get_schema('Document')
Traceback (most recent call last):
...
ProtocolError: <ProtocolError for bad:bad@localhost:8080/plone: 401 Unauthorized>

So the corresponding code would be:

from xmlrpclib import ServerProxy
from xmlrpclib import ProtocolError
try:
    server = ServerProxy("http://admin:admin@localhost:8080/plone")
    server.get_schema('Document')
    return server
except ProtocolError:
    return None
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top