使用python中的身份验证连接到套接字 [英] Connecting to socket with authentication in python

查看:111
本文介绍了使用python中的身份验证连接到套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过python套接字连接到mongodb实例.网址看起来像这样

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

用户名:password@host.com:端口

username:password@host.com:port

如何使用python套接字连接到此?

how can I connect to this with a python socket?

以下代码给我这个错误:[Errno -5]没有与主机名关联的地址

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)

编辑-我问的原因是因为asyncmongo目前不支持这种类型的url.我正在尝试查看是否可以编写补丁. asyncmongo库使用与上面代码中的套接字类似的套接字进行连接.

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.

推荐答案

您应使用驱动程序连接到mongodb.如果您正在使用Tornado(看起来像您打算这样做),请尝试 asyncmongo ;如果您使用的是线程化的Web服务器/应用程序框架(Django,Pylons等),则可以使用 PyMongo 直接.

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.

至于为什么此代码不起作用,socket模块不接受用于连接的URL,仅接受主机名和端口.这是一个低级库.要连接到(网络)URL,请考虑使用 urllib2

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.

MongoDB中的身份验证不是在传输级别处理的,而是在应用程序级别处理的.我建议您首先阅读在驱动程序中实施身份验证,然后看看PyMongo如何实现身份验证(在 connection.py 数据库. py ).您还需要为asyncmongo移植或重新实现MongoDB连接URI解析,该文档记录在此处.

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.

这篇关于使用python中的身份验证连接到套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆