AdvancedaccesstoPostgreSQLfromPythonwithpsycopg2"classic"psycopghomepagePsycopgcharacteristicsLGPLlicenseWrittenmostlyinClibpqwrapperPython2.
4–2.
7PostgreSQL>=7.
4–droppedV2protocolsupportin2.
3ImplementsPythonDB-APIinterfaceconnectionwrapsthesessioncursorholdsaresultLatesthistoryBefore2010:alotofundocumentedfeaturesPy-PGadaptation,SSC,notifies2.
2:asyncsupport2.
3:notifypayload,2PC,hstoreLet'stalkabout.
.
.
TypesadaptationServer-sidecursorsTransactionshandlingAsyncsupportServernotificationsTypesadaptationServer-sidecursorsTransactionshandlingAsyncsupportServernotificationsPythonobjectsadaptationAnadaptermapsPythonobjectsintoSQLsyntaxbuilt-inadaptersforbasicobjects/typesAdaptersareregisteredbytypesincePsycopg2.
3:Liskov-friendlyAdapterexample:XMLfromxml.
etreeimportcElementTreeasETfrompsycopg2.
extensionsimport\adapt,register_adapterclassElementAdapter:def__init__(self,elem):self.
elem=elemdefgetquoted(self):return"%s::xml"\%adapt(ET.
tostring(elem))register_adapter(type(ET.
Element('')),ElementAdapter)Adapterexample:XMLelem=ET.
fromstring("Hello,'xml'!
")printadapt(elem).
getquoted()#'Hello,''xml''!
'::xmlcur.
execute("""INSERTINTOxmltest(xmldata)VALUES(%s);""",(elem,))PostgreSQLtypesadaptationAtypecastermapsPostgreSQLtypesintoPythonobjectsTypecastersareregisteredperoidGlobal,connectionorcursorscopeTypecasterexample:XMLdefcast_xml(value,cur):ifvalueisNone:returnNonereturnET.
fromstring(value)frompsycopg2.
extensionsimport\new_type,register_typeXML=new_type((142,),"XML",cast_xml)register_type(XML)Typecasterexample:XMLcur.
execute("""SELECTxmldataFROMxmltestORDERBYidDESCLIMIT1;""")elem=cur.
fetchone()[0]printelem.
text#Hello,'xml'!
dict-hstoreadaptationhstore:associativearrayofstringsfoo=>bar,baz=>whateverImprovedinPostgreSQL9.
0capacityandindexingAdapternewinPsycopg2.
3candealwithbothpre-9.
0and9.
0PostgreSQLdict-hstoreadaptationpsycopg2.
extras.
register_hstore(cnn)cur.
execute("SELECT'a=>b'::hstore;")printcur.
fetchone()[0]#{'a':'b'}cur.
execute("SELECT%s;",[{'foo':'bar','baz':None}])#SELECThstore(ARRAY[E'foo',E'baz'],#ARRAY[E'bar',NULL])hstore:SOuseful.
.
.
ifIonlycouldremembertheoperatorscur.
execute(#hasakey"select*frompetswheredata%s;",('tail',))cur.
execute(#hasallkeys"select*frompetswheredata&%s;",(['tail','horns'],))cur.
execute(#hasanykey"select*frompetswheredata|%s;",(['wings','fins'],))cur.
execute(#haskeys/values"select*frompetswheredata@>%s;",({'eyes':'red','teeth':'yellow'},))TypesadaptationServer-sidecursorsTransactionshandlingAsyncsupportServernotificationsProblem:outofmemoryIhavethisproblem:cursor.
execute("select*inbig_table")forrecordincursor:whatever(record)Well,itdoesn'twork:"outofmemory"!
Problem:outofmemorycursor.
execute()movesallthedatasettotheclientPGresultstructurecursor.
fetch*()onlymanipulatesclient-sidedataPGresult→PythonobjectsDECLAREtotherescue!
Namedcursorsconnection.
cursor(name)cursor.
execute(sql)→DECLAREnameCURSORFORsqlcursor.
fetchone()→FETCHFORWARD1FROMnamecursor.
fetchmany(n)→FETCHFORWARDnFROMnameNamedcursorIfyouneedtomanipulatemanyrecordsclient-sideBeststrategy:cur=connection.
cursor(name)cur.
execute()cur.
fetchmany(n)ReasonablentohavegoodmemoryusageandnottoomanynetworkrequestsTypesadaptationServer-sidecursorsTransactionshandlingAsyncsupportServernotificationsTransactionshandlingTheconnection"has"thetransactionallitscursorsshareitEveryoperationinatransactionDB-APIrequirementUntil.
commit()or.
rollback()youare"intransaction"badformanyreasonsClosethattransaction!
Peoplearenotoriouslygoodatrememberingboringdetails,aren'ttheyconn.
commit()/conn.
rollback()Useadecorator/contextmanager@with_connectiondefdo_some_job(conn,arg1,arg2):cur=conn.
cursor()#.
.
.
withget_connection()asconn:cur=conn.
cursor()#.
.
.
Goautocommitifyouneedtoconn.
set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)TypesadaptationServer-sidecursorsTransactionshandlingAsyncsupportServernotificationsAsyncinpsycopgAttemptfrompsycopg2,neverworkedcorrectlyconn.
execute(query,args,async=1)Redesigninspring2010,releasedin2.
2ThankstoJanUrbańskiBeingasyncisnowaconnectionpropertypsycopg2.
connect(dsn,async=1)AsynccodepathwellseparatedfromsyncpsycopgandlibpqsyncpsycopgandlibpqsyncAsyncinpsycopgconn.
fileno()Makestheconnectionafile-likeobjectconn.
poll()→[OK|READ|WRITE]poll()knowsthingsCallsthecorrectlibpqfunctionaccordingtotheoperationtobeperformed–connection,query,fetch,notifies.
.
.
andthestateoftheconnectionAllowseasyusagepatterncur.
execute(query,args)while"not_happy":conn.
poll()Asyncexamplecursor.
execute(SQL)while1:state=conn.
poll()ifstate==POLL_OK:breakelifstate==POLL_READ:select([conn.
fileno(elifstate==POLL_WRITE:select([],[conn.
fileno()],[])cursor.
fetchall()psycopgandlibpqasyncAsynchronousaccessFundamentalproblem:DB-APIisblockingcnn=psycopg2.
connect(dsn)cursor.
execute(query,args)cursor.
fetchall()AsyncconnectionshaveadifferentinterfaceSowecan'tuseDjango,SQLAlchemy.
.
.
Completecontrol,buthigherleveltoberedoneSolution#1The"TwistedSolution":whatproblem:o)everythingmustbecallback-basedanywaytxPostgres:asyncpsycopg2inTwistedd=conn.
connect(database=DB_NAME)d.
addCallback(lambdac:c.
execute(SQL))d.
addCallback(lambdac:c.
fetchall())Notice:manyfeaturesmissinginasyncNotransactions,SSC,…CoroutinelibrariesInterpreter-levelcooperativeaka"green"threadsEventlet,gevent,uGreen"Monkeypatch"blockingfunctionstime.
sleep(),socket.
read().
.
.
Cextensionscan'tbepatchedAcolleagueofminewasstrugglingwithpg8000.
.
.
Solution#2:"wait"callbackGloballyregisteredpsycopg2.
extensions.
set_wait_callback(f)Givescontrolbacktotheframeworkwhenit'stimetowaitControlcanbepassedtoadifferentthreadThePythoninterfaceisunchangedLessflexible,butclassicblockingDB-APICustomizedfordifferentcoroutinelibrariesOutsideofpsycopgscope,butcheckpsycogreenExamplewaitcallbackdefeventlet_wait_callback(conn):while1:state=conn.
poll()ifstate==POLL_OK:breakelifstate==POLL_READ:trampoline(conn.
fileno(),read=1)elifstate==POLL_WRITE:trampoline(conn.
fileno(),write=1)psycopgandlibpqgreenTypesadaptationServer-sidecursorsTransactionshandlingAsyncsupportServernotificationsServernotificationsPublish/subscribechannelsPostgreSQLLISTENandNOTIFYAddedpayloadinPostgreSQL9.
0ServernotificationsPayloadsupportfromPsycopg2.
3Receivedonexecute()Receivedonpoll()Theyloveasyncmode!
Notification:pushexampleListenforDBnotifiesandputtheminaqueuedefdblisten(q):cnn=psycopg2.
connect(dsn)cnn.
set_isolation_level(0)cur=cnn.
cursor()cur.
execute("listendata;")while1:trampoline(cnn,read=True)cnn.
poll()whilecnn.
notifies:q.
put(cnn.
notifies.
pop())Notification:pushexampleThanks!
QuestionsThisworkislicensedunderCreativeCommonsAttribution-NonCommercial-ShareAlike3.
0License.
PQ.hosting怎么样?PQ.hosting是一家俄罗斯商家,正规公司,主要提供KVM VPS和独立服务器,VPS数据中心有香港HE、俄罗斯莫斯科DataPro、乌克兰VOLIA、拉脱维亚、荷兰Serverius、摩尔多瓦Alexhost、德国等。部分配置有变化,同时开通Paypal付款。香港、乌克兰、德国、斯洛伐克、捷克等为NVMe硬盘。香港为HE线路,三网绕美(不太建议香港)。免费支持wi...
racknerd怎么样?racknerd今天发布了几款美国特价独立服务器的促销,本次商家主推高配置的服务器,各个配置给的都比较高,有Intel和AMD两种,硬盘也有NVMe和SSD等多咱组合可以选择,机房目前有夏洛特、洛杉矶、犹他州可以选择,性价比很高,有需要独服的朋友可以看看。点击进入:racknerd官方网站RackNerd暑假独服促销:CPU:双E5-2680v3 (24核心,48线程)内存...
小欢互联成立于2019年10月,主打海外高性价比云服务器、CDN和虚拟主机服务。近期上线了自营美国CERA机房高速VPS,进行促销活动,为客户奉上美国/香港八折优惠码:Xxc1mtLB优惠码适用于美国CERA一区/二区以及香港一区/二区优惠时间:即日起至10月底优惠码可无限次使用,且续费同价!官网:https://idc.xh-ws.com购买地址:美国CERA一区:https://idc.xh-...
postgresql9.0为你推荐
网易网盘关闭入口网易网盘怎么用????网易网盘关闭入口网易网盘 怎么没有了vc组合天然维生素c和合成维生素c有区别吗2020双十一成绩单2020双十一尾款如何合并付款?梦之队官网梦之队是什么呢?是那个国家的呢?他们又是参加那个项目的呢?得了几块金牌呢?lunwenjiance论文检测,知网的是32.4%,改了以后,维普的是29.23%。如果再到知网查,会不会超过呢?xyq.163.cbg.com『梦幻西游』那藏宝阁怎么登录?rawtools闪迪32Gsd卡,无法格式化,显示只有30M,并且是raw格式。如何恢复?ip在线查询我要用eclipse做个ip在线查询功能,用QQwry数据库,可是我不知道怎么把这个数据库放到我的程序里面去,高手帮忙指点下,小弟在这谢谢了www.vtigu.com破译密码L dp d vwxghqw.你能看出这些字母代表什么意思吗?如果给你一把破以它的钥匙X-3,联想
哈尔滨服务器租用 万网域名代理 cybermonday 西安服务器 fdcservers 韩国空间 idc评测网 免费cdn加速 回程路由 seovip dd444 服务器是干什么的 hktv 独享主机 云营销系统 免费稳定空间 双11促销 香港ip magento主机 时间同步服务器 更多