Connecting to socket with authentication in python

强颜欢笑 提交于 2020-01-14 03:10:16

问题


I'm trying to connect to a mongodb instance through a python socket. The url looks like this

username:password@host.com:port

how can I connect to this with a python socket?

The following code gives me this error: [Errno -5] No address associated with hostname

import socket
import tornado

full_url = '%s:%s@%s' % (username, password, host)
s = socket.socket()
s.connect((full_url, port))
stream = iostream.IOStream(s)

EDIT - the reason I ask is because asyncmongo doesn't support this type of url right now. I'm trying to see if I can write a patch. The asyncmongo library connects using a socket like the one in the code above.


回答1:


You should use a driver to connect to mongodb. If you are using Tornado (it looks like you intend to do so), try asyncmongo; if you are using a threaded web server/application framework (Django, Pylons, etc) you can use PyMongo directly.


Edit: As for why this code doesn't work, the socket module doesn't accept URLs for connection, just hostname and port. It is a low-level library. To connect to (web) urls, consider using urllib2 or httplib.


Edit 2: Authentication in MongoDB is not handled at the transport level, it's handled at the application level. I suggest you first read Implementing Authentication in a Driver, and then take a look at how PyMongo implements authentication (in connection.py and database.py). You'll also need to port or reimplement the MongoDB connection URI parsing for asyncmongo, which is documented here.



来源:https://stackoverflow.com/questions/6540515/connecting-to-socket-with-authentication-in-python

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