最近很多小伙伴都在问Mongoengine:ConnectionError:您尚未定义默认连接和尚未指定默认捕获模式这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展"frompym
最近很多小伙伴都在问Mongoengine:ConnectionError:您尚未定义默认连接和尚未指定默认捕获模式这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展"from pymongo import Connection" (to import mongo.connection using python) , got "500 Internal Server Error"、com.mongodb.connection.ConnectionPoolSettings的实例源码、connect-mongo:Error: Connection strategy not found、django ConnectionError: Error 104 while writing to socket. Connection reset by peer等相关知识,下面开始了哦!
本文目录一览:- Mongoengine:ConnectionError:您尚未定义默认连接(尚未指定默认捕获模式)
- "from pymongo import Connection" (to import mongo.connection using python) , got "500 Internal Server Error"
- com.mongodb.connection.ConnectionPoolSettings的实例源码
- connect-mongo:Error: Connection strategy not found
- django ConnectionError: Error 104 while writing to socket. Connection reset by peer
Mongoengine:ConnectionError:您尚未定义默认连接(尚未指定默认捕获模式)
在我的新Django项目中,我建立了一个MongoDb数据库并使用mongoengine模块,但是无法在视图的shell no中正确访问dabasenore。“ ConnectionError:您尚未定义默认连接”
我的settings.py包括以下内容:
DATABASES = { ''default'': { ''ENGINE'': ''django.db.backends.mysql'', ''NAME'': ''DaTaBaSe'', ''USER'': ''root'', ''PASSWORD'': '''', ''HOST'': ''localhost'', ''PORT'': ''3306'', }, ''tracking'': { ''ENGINE'': ''django.db.backends.dummy'', ''NAME'': ''analytics'', }}import mongoengineSESSION_ENGINE = ''mongoengine.django.sessions''mongoengine.connect(_MONGODB_NAME, ''localhost:27017'')AUTHENTICATION_BACKENDS = ( ''mongoengine.django.auth.MongoEngineBackend'', )
在models.py中导入mongoengine
from mongoengine import *from myproject.settings import _MONGODB_NAMEmongoengine.connect(_MONGODB_NAME, ''localhost:27017'')
预先感谢您的帮助
答案1
小编典典要将django与MongoDB结合使用,请勿使用https://www.djangoproject.com上可用的django软件包并安装其他软件包(如mongoengine),如果按照此过程进行操作,您会发现很多困难。
而是您需要使用djangoproject派生的django的no @
rel版本,并添加了MongoDB支持,我敢肯定,这将使安装过程和开发过程变得更加容易。
单击此链接以使用MongoDB安装和设置django。 http://django-mongodb-
engine.readthedocs.org/en/latest/topics/setup.html
设置django时,您可能还会发现以下错误。
“ * Django-
nonrel和MongoDB上的错误:AutoField(默认主键)值必须是代表MongoDB上的ObjectId的字符串(取而代之的是u‘1’。请确保您的SITE_ID包含有效的ObjectId字符串。“
请点击此链接进行修复。
https://gist.github.com/ielshareef/2986459
如果您需要更多帮助,请告诉我。
"from pymongo import Connection" (to import mongo.connection using python) , got "500 Internal Server Error"
I created the /var/www/cgi-bin/test.py in my web server machine (Linux). The service of mongoDB "mongod" is running.
When I run the test.py locally, "./test.py", I could get the correct result.
But when I use the URL: http://xxxxxx.compute-1.amazonaws.com/cgi-bin/python_test/test.py to run the test.py, I will get the "500 Internal Server Error".
If I remove the line "from pymongo import Connection", and use the URL above to access, I won''t get the 500 Internal server error. So, it should be the problem when I import the pymongo.connection.
Is it the problem of any configuration issue? Thanks so much for your help
========== test.py ==============
#!/usr/bin/python
import cgi
import sys
sys.path.append("/home/ec2-user/mongo-python-driver-2.6.3/")
#import pymongo.connection
from pymongo import Connection
def main():
print "Content-type: text/html\r\n\r\n"
form = cgi.FieldStorage()
name = form.getvalue(''ServiceCode'')
# name = "abcddd"
# con = Connection()
# db = con.test
# posts = db.post
# print name
if form.has_key("ServiceCode") and form["ServiceCode"].value!="":
print"<h1>Hello", form["ServiceCode"].value,"</h1>"
else:
print"<h1>Error! Please enter first name. </h1>"
.....
com.mongodb.connection.ConnectionPoolSettings的实例源码
@Test public void testConnectionPoolSettings() { int maxPoolSize = 42; int minPoolSize = maxPoolSize / 2; // min needs to be less then max long maxIdleTimeMS = Math.abs(randomLong()); long maxLifeTimeMS = Math.abs(randomLong()); // Do not use long because of rounding. int waitQueueMultiple = 5432; long waitQueueTimeoutMS = Math.abs(randomLong()); long maintenanceInitialDelayMS = Math.abs(randomLong()); long maintenanceFrequencyMS = Math.abs(randomLong()); JsonObject config = new JsonObject(); config.put("maxPoolSize",maxPoolSize); config.put("minPoolSize",minPoolSize); config.put("maxIdleTimeMS",maxIdleTimeMS); config.put("maxLifeTimeMS",maxLifeTimeMS); config.put("waitQueueMultiple",waitQueueMultiple); config.put("waitQueueTimeoutMS",waitQueueTimeoutMS); config.put("maintenanceInitialDelayMS",maintenanceInitialDelayMS); config.put("maintenanceFrequencyMS",maintenanceFrequencyMS); ConnectionPoolSettings settings = new ConnectionPoolSettingsParser(null,config).settings(); assertEquals(maxPoolSize,settings.getMaxSize()); assertEquals(minPoolSize,settings.getMinSize()); assertEquals(maxIdleTimeMS,settings.getMaxConnectionIdleTime(MILLISECONDS)); assertEquals(maxLifeTimeMS,settings.getMaxConnectionLifeTime(MILLISECONDS)); assertEquals(waitQueueMultiple,5432); assertEquals(waitQueueTimeoutMS,settings.getMaxWaitTime(MILLISECONDS)); assertEquals(maintenanceInitialDelayMS,settings.getMaintenanceInitialDelay(MILLISECONDS)); assertEquals(maintenanceFrequencyMS,settings.getMaintenanceFrequency(MILLISECONDS)); }
private Block pool(final String db) { return unit -> { ConnectionPoolSettings settings = unit.mock(ConnectionPoolSettings.class); unit.registerMock(ConnectionPoolSettings.class,settings); ConnectionPoolSettings.Builder builder = unit.mock(ConnectionPoolSettings.Builder.class); expect(builder.applyConnectionString(new ConnectionString(db))).andReturn(builder); expect(builder.build()).andReturn(settings); unit.mockStatic(ConnectionPoolSettings.class); expect(ConnectionPoolSettings.builder()).andReturn(builder); }; }
/** * Lazily instantiate the {@link MongoClient} instance. * * @return */ private MongoClient createMongoClient() { String host = applicationConfiguration.getMongoHost(); int port = applicationConfiguration.getMongoPort(); ConnectionString connectionString = new ConnectionString("mongodb://" + host + ":" + port); logger.info("Creating Mongo client for: {}:{}",host,port); MongoClientSettings mongoClientSettings = MongoClientSettings.builder() .applicationName("dragoman") .serverSettings( ServerSettings.builder() .applyConnectionString(connectionString) .addServerMonitorListener(new LoggingServerMonitorListener()) .addServerListener(new LoggingServerListener()) .build()) .clusterSettings( ClusterSettings.builder() .applyConnectionString(connectionString) .serverSelectionTimeout( applicationConfiguration.getMongoServerSelectionTimeout(),MILLISECONDS) .addClusterListener(new LoggingClusterListener()) .build()) .connectionPoolSettings( ConnectionPoolSettings.builder() .applyConnectionString(connectionString) .maxWaitTime( applicationConfiguration.getConnectionPoolMaxWaitTime(),MILLISECONDS) .minSize(applicationConfiguration.getConnectionPoolMinSize()) .maxSize(applicationConfiguration.getConnectionPoolMaxSize()) .addConnectionPoolListener(new LoggingConnectionPoolListener()) .build()) .socketSettings( SocketSettings.builder() .applyConnectionString(connectionString) .connectTimeout( applicationConfiguration.getMongoSocketConnectionTimeout(),MILLISECONDS) .readTimeout(applicationConfiguration.getMongoReadTimeout(),MILLISECONDS) .build()) .build(); return MongoClients.create(mongoClientSettings); }
public ConnectionPoolSettingsParser(ConnectionString connectionString,JsonObject config) { ConnectionPoolSettings.Builder settings = ConnectionPoolSettings.builder(); if (connectionString != null) { settings.applyConnectionString(connectionString); } else { Integer maxPoolSize = config.getInteger("maxPoolSize"); if (maxPoolSize != null) { settings.maxSize(maxPoolSize); } Integer minPoolSize = config.getInteger("minPoolSize"); if (minPoolSize != null) { settings.minSize(minPoolSize); } Long maxIdleTimeMS = config.getLong("maxIdleTimeMS"); if (maxIdleTimeMS != null) { settings.maxConnectionIdleTime(maxIdleTimeMS,MILLISECONDS); } Long maxLifeTimeMS = config.getLong("maxLifeTimeMS"); if (maxLifeTimeMS != null) { settings.maxConnectionLifeTime(maxLifeTimeMS,MILLISECONDS); } Integer waitQueueMultiple = config.getInteger("waitQueueMultiple"); if (waitQueueMultiple != null) { Integer waitQueueSize = waitQueueMultiple * DEFAULT_MONGO_DRIVER_WAIT_Q_SIZE; settings.maxWaitQueueSize(waitQueueSize); } Long waitQueueTimeoutMS = config.getLong("waitQueueTimeoutMS"); if (waitQueueTimeoutMS != null) { settings.maxWaitTime(waitQueueTimeoutMS,MILLISECONDS); } Long maintenanceInitialDelayMS = config.getLong("maintenanceInitialDelayMS"); if (maintenanceInitialDelayMS != null) { settings.maintenanceInitialDelay(maintenanceInitialDelayMS,MILLISECONDS); } Long maintenanceFrequencyMS = config.getLong("maintenanceFrequencyMS"); if (maintenanceFrequencyMS != null) { settings.maintenanceFrequency(maintenanceFrequencyMS,MILLISECONDS); } } this.settings = settings.build(); }
public ConnectionPoolSettings settings() { return settings; }
private void connect() throws ActivecheckReporterException { if (mongoClient == null) { logger.debug("Cannot run query. MongoDB is not connected. Trying to (re)connect."); try { // configure credentials List<MongoCredential> credentialsList = new ArrayList<MongoCredential>(); String username = properties .getString("mongodb.username",null); String password = properties .getString("mongodb.password",null); if (username != null && password != null) { credentialsList.add(MongoCredential.createPlainCredential( username,"*",password.tochararray())); } // configure server addresses List<ServerAddress> addressList = new ArrayList<ServerAddress>(); String socketPath = properties.getString("socket",null); if (socketPath != null) { addressList.add(new ServerAddress(new AFUNIXSocketAddress( new File(socketPath)))); } else { String url = properties.getString("url",ServerAddress.defaultHost()); int port = ServerAddress.defaultPort(); String[] urlParts = url.split(":"); if (urlParts.length > 1) { port = Integer.parseInt(urlParts[1]); } addressList.add(new ServerAddress(urlParts[0],port)); } ServerSelector serverSelector = new ReadPreferenceServerSelector( MONGO_READ_PREFERENCE); ClusterSettings clusterSettings = ClusterSettings.builder() .hosts(addressList).serverSelector(serverSelector) .build(); // actually configure and (re)create mongoClient ConnectionPoolSettings connectionPoolSettings = ConnectionPoolSettings .builder().maxSize(MONGO_POOL_SIZE).build(); MongoClientSettings settings = MongoClientSettings.builder() .readPreference(MONGO_READ_PREFERENCE) .credentialList(credentialsList) .clusterSettings(clusterSettings) .connectionPoolSettings(connectionPoolSettings).build(); mongoClient = MongoClients.create(settings); } catch (Exception e) { mongoClient = null; String errorMessage = "MongodbReporter Configuration Error for service '" + getoverallServiceName() + "': " + e.getMessage(); logger.error(errorMessage); logger.trace(e.getMessage(),e); // set report and status setoverallServiceReport(NagiosServiceStatus.CRITICAL,errorMessage); throw new ActivecheckReporterException(e); } } }
connect-mongo:Error: Connection strategy not found
app.use(session({
secret: settings.cookieSecret,
key: settings.db,//cookie name
cookie: {maxAge: 1000 * 60 * 60 * 24 * 30},//30 days
resave: false,
saveUninitialized: true,
store: new MongoStore({
/*db: settings.db,
host: settings.host,
port: settings.port*/
url: ''mongodb://localhost/blog''
})}));
附:https://cnodejs.org/topic/567a1120222744630726b244
在此感谢!
django ConnectionError: Error 104 while writing to socket. Connection reset by peer
django ConnectionError: Error 104 while writing to socket. Connection reset by peer错误提示:
Internal Server Error: /api/v2/chenxm/ Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, **kwargs) File "/home/chenxinming/StructureSearchViews/views.py", line 27, in post data = self.run(obj_keys, concept_name, startPos, endPos) File "/home/chenxinming/StructureSearch/structureSearch.py", line 546, in run data = self.getobjectData(union_obj_keys, type) File "/home/chenxinming/StructureSearch/structureSearch.py", line 462, in getobjectData concept_map = Object.bulkGetobjectConcept(obj_keys) File "/home/chenxinming/object.py", line 868, in bulkGetobjectConcept concept_li = p.execute() File "/usr/local/lib/python2.7/dist-packages/redis/client.py", line 2894, in execute return execute(conn, stack, raise_on_error) File "/usr/local/lib/python2.7/dist-packages/redis/client.py", line 2810, in _execute_pipeline connection.send_packed_command(all_cmds) File "/usr/local/lib/python2.7/dist-packages/redis/connection.py", line 603, in send_packed_command (errno, errmsg)) ConnectionError: Error 104 while writing to socket. Connection reset by peer.
经过检查和排查发现redis获取数据量过大,导致redis中断连接。
with cache.pipeline(transaction=False) as p: for english_name in english_li: p.hget(keyName._getConceptNaMetable(), english_name) concept_li = p.execu
原因是因为使用pipeline时,english_li的长度超过10w导致。修改限制english_li的长度数量
关于Mongoengine:ConnectionError:您尚未定义默认连接和尚未指定默认捕获模式的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于"from pymongo import Connection" (to import mongo.connection using python) , got "500 Internal Server Error"、com.mongodb.connection.ConnectionPoolSettings的实例源码、connect-mongo:Error: Connection strategy not found、django ConnectionError: Error 104 while writing to socket. Connection reset by peer等相关知识的信息别忘了在本站进行查找喔。
本文标签: