python中数据库连接池的最佳解决方案是什么? [英] What is the best solution for database connection pooling in python?

查看:251
本文介绍了python中数据库连接池的最佳解决方案是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开发了一些类似于DAO的自定义类,以满足我的项目的一些非常专业的要求,这是一个服务器端进程,它不能在任何类型的框架中运行.

I have developed some custom DAO-like classes to meet some very specialized requirements for my project that is a server-side process that does not run inside any kind of framework.

该解决方案非常有效,除了每次发出新请求时,我都会通过MySQLdb.connect打开一个新连接.

The solution works great except that every time a new request is made, I open a new connection via MySQLdb.connect.

将其切换为在python中使用连接池的最佳插入"解决方案是什么?我正在想象类似Java的通用DBCP解决方案.

What is the best "drop in" solution to switch this over to using connection pooling in python? I am imagining something like the commons DBCP solution for Java.

该过程运行很长时间,并且有很多线程需要发出请求,但不是同时发出所有信息……特别是在短暂写出一部分结果之前,他们做了很多工作.

The process is long running and has many threads that need to make requests, but not all at the same time... specifically they do quite a lot of work before brief bursts of writing out a chunk of their results.

编辑后添加: 经过更多搜索后,我发现 anitpool.py 看起来不错,但是我想我对python还是比较陌生我只是想确保我不会错过一个更明显/更惯用/更好的解决方案.

Edited to add: After some more searching I found anitpool.py which looks decent, but as I'm relatively new to python I guess I just want to make sure I'm not missing a more obvious/more idiomatic/better solution.

推荐答案

IMO,更明显/更惯用/更好的解决方案"是使用现有的ORM,而不是发明类似DAO的类.

IMO, the "more obvious/more idiomatic/better solution" is to use an existing ORM rather than invent DAO-like classes.

在我看来,ORM比原始" SQL连接更受欢迎.为什么?因为Python 面向对象,所以从SQL行到对象的映射绝对是必不可少的.在很多情况下,您会处理未映射到Python对象的SQL行.

It appears to me that ORM's are more popular than "raw" SQL connections. Why? Because Python is OO, and the mapping from SQL row to to object is absolutely essential. There aren't many cases where you deal with SQL rows that don't map to Python objects.

我认为 SQLAlchemy SQLObject (和关联的连接池)是更惯用的Pythonic解决方案.

I think that SQLAlchemy or SQLObject (and the associated connection pooling) the more idiomatic Pythonic solution.

将池作为单独的功能并不是很常见,因为纯SQL(不带对象映射)对于受益于连接池的复杂,运行时间长的进程不是很流行.是的,使用了纯SQL ,但是它总是在池化无济于事的更简单或更受控制的应用程序中使用.

Pooling as a separate feature isn't very common because pure SQL (without object mapping) isn't very popular for the kind of complex, long-running processes that benefit from connection pooling. Yes, pure SQL is used, but it's always used in simpler or more controlled applications where pooling isn't helpful.

我认为您可能有两种选择:

I think you might have two alternatives:

  1. 修改您的类以使用SQLAlchemy或SQLObject.虽然这乍看起来很痛苦(所有工作都浪费了),但您应该能够利用所有设计和思想,并且这只是采用广泛使用的ORM和合并解决方案的一种练习.
  2. 使用概述的算法滚动自己的简单连接池-循环的简单连接集或列表.

这篇关于python中数据库连接池的最佳解决方案是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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