PK:'ADcpyamf/__init__.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Python C-extensions for L{PyAMF}. @since: 0.4 """ PK:u3;``cpyamf/util.soELF>O@@8@&# !!@?Q HH!H!PtdyyyQtdadMH;?ECKX^OWL@"G]A/J>_cP' S+T#V6DbI$ 23QB%5RU\*!:NY  Z(. )[8-4<&=F` 7901,aW  H&WY^|CE(vsӘqXHnMC~e J.N6w  + p}Q88Pn+gT2"]Sv_pl?C|$K?B)Ice!X!@!x p[!xX! J _!x@!xb! !x/@!x__gmon_start___init_fini__cxa_finalize_Jv_RegisterClasses_Py_NoneStruct_Py_ZeroStruct_Py_TrueStructPyTraceBack_TypePyExc_TypeErrorPyErr_SetStringPyClass_TypePyInstance_Type_PyThreadState_CurrentPyExc_NotImplementedErrorPyString_FromStringPyModule_GetDictPyString_FromStringAndSizePyCode_NewPyFrame_NewPyTraceBack_HerePyString_FromFormatPyErr_OccurredPyInt_FromLongPyDict_SetItemPyDict_NextPyString_Type_PyString_EqPyString_AsStringPyErr_FormatPyType_IsSubtypePyDict_SizePyDict_GetItemPyTuple_NewPyObject_CallPyExc_SystemErrorPyFloat_TypePyFloat_AsDoublePyFloat_FromDoublePyMem_MallocmemcpyPyMem_FreePyInt_TypePyLong_TypePyNumber_IntPyNumber_LongPyLong_AsLongPyLong_AsUnsignedLongPyExc_OverflowErrorPyLong_FromUnsignedLongPyObject_GetAttrPyUnicode_TypePyObject_IsInstancePyObject_HasAttrPyList_New_PyFloat_Unpack8PyDict_NewPyList_TypePyObject_GetAttrStringPyObject_CallFunctionObjArgsPyObject_GetIterPyList_AppendPyErr_FetchPyErr_WriteUnraisablePyErr_RestorePyUnicodeUCS2_DecodeUTF8PyCObject_FromVoidPtrPyDict_SetItemStringPyObject_HashPyMem_Realloc_PyFloat_Pack4_PyFloat_Unpack4_PyFloat_Pack8PyString_AsStringAndSizePyUnicodeUCS2_AsUTF8StringPyObject_IsTruePyObject_RichComparePyInt_AsLonginitutilPyLong_FromStringPyString_InternFromStringPy_InitModule4PyImport_AddModulePyObject_SetAttrString__pyx_module_is_main_cpyamf__util__pyx_type_6cpyamf_4util_cBufferedByteStreamPyType_Ready__pyx_type_6cpyamf_4util_cIndexedCollectionPyExc_NameErrorPyErr_SetObject__pyx_type_6cpyamf_4util_cIndexedMap__pyx_type_6cpyamf_4util_BufferedByteStream__pyx_type_6cpyamf_4util_IndexedCollection__pyx_type_6cpyamf_4util_IndexedMapPyDict_Typelibpthread.so.0libc.so.6_edata__bss_start_endGLIBC_2.2.5ui @!w!!ج!t!! ! !`!(!!X!!!!!X!th!0! !!!!P!خ!`!!w!@P!`P! Y!@ !!p! Vد!w!!! !!(!!X!@!p!x! !`!!pWX!th!!!!@!!!!pYر!!!u !!0!!`!`p!ز!w!0!! !!(!0!X!`!h!wp!@Px!`P!!!!!!VX!wh!!!!!!!ش!@!!w!! !!0!!`!p!@X!P!ȵ!h!!8!!8!!@!!H! !8!0!X!8!`!P!X!X!`!p!0!!X!!`!!X!!`!!w!!ȶ!!!`!!!!h!!! !p!(!!@!!H!!`!!h!!!x!!ĕ!!!!ʕ!!!ȷ!Е!!!!Օ!!!!ߕ! ! !(!!@!!H!!`!(!h!!!!!!!!!!!!ȸ! !!!!!!!!! !!(!'!@!!H!3!`!!h!>!!!!I!!!!`!!!ȹ!p!!!!!!!!! !!(!!@!!H!!`!!h!!! !!!!(!!Ж!!0!Ⱥ!!!8!!!!@!! ! !H!(!2!@!P!H!>!`!X!h!K!!`!!V!!h!!b!!p!Ȼ!i!!x!!q!!!!y! !!(!!@!!H!!`!!h!!!!!!!!!!!!ȼ!!!!!З!!!!! !0!(!!@!!H!!`!8!h!!!!!!!@!!!!H!Ƚ!!!P!!!!!!! !!(! !@!!H!!`!!h!!!X!!!!`!!$!!!Ⱦ!/!!!!2!!!!6! !h!(!:!@!p!H!E!`!x!h!Q!!!!\!!!!k!!!ȿ!p!!!!t!!!!{! !!(!!@!!H!!`!!h!!!!!!!!!!!!!!!!!!!!!Ę! !!(!ɘ!@!!H!Θ!`!!h!!!!!!!H!!!!P!!!!X!!0!!`!!P! !h!(!e!@!p!H!p!`!x!h!!!!!!!!!ƙ!!!!ș!!!!ʙ!!!!̙! !!(!Й!@!!H!!`!!h!!!!!0!!!!P!!!!p!!!!!!!!! !!(!К!@!!H!!`!!h!!!!!0!!!!P!!!!p!!0P!`mP!0PX!P!w!@!w!P!x!t!'@! P! P!v!!!! x!]!!!x!p]!`! !x(!P@!xH!mX!!`! xh!plx!!!*x! Y!`!!3x!\!!!nw!=! !!|w!E! !!sw!`A! ! !:x(!\8!!@!BxH!X!`!`!Mxh!x!!!Wx!P!!!cx!!@!!nx!!!!yx!!!!x!! ! !x(!8!!@!xH!9X!!`!xh!6x!!!x!`$! !!x!@!!!!x!p!!!x!!`!!x!!! !x(!p8!!@! yH!pX!!`!yh!\x!`!!-y!Ѕ!!!9y!! !!Fy! !!!Qy!! !!u![!! !]y(!'@!eyH!pY!my!X!P!ty!@!y!k !u(! k@!uH!0[!y!P!U!y!P!@U!ty!P !y(!pj@!uH!i`!uh!Z!y!@!u!r!y!Q!T!y!0Q! T!!!Y! ! ! ! !(!0!8!_@!H![P!`X!'`!(h!+p!,x!<!a!B!D!E!b!I!c!J!NȒ!P!!!!!! ! !(!0!8!@!H!P!X!`!h!p!x!!! !!!"!#!$!%!&!(ȓ!)Г!*ؓ!-!.!/!0!1!2!3!4!5 !6(!70!88!9@!:H!;P!=X!>`!?h!@p!Ax!C!F!G!H!K!L!M!O!Q!RȔ!SД!Tؔ!U!VH'H5G!%G!@%G!h%G!h%G!h%G!h%G!h%G!h%G!h%G!hp%G!h`%G!h P%G!h @%G!h 0%zG!h %rG!h %jG!h%bG!h%ZG!h%RG!h%JG!h%BG!h%:G!h%2G!h%*G!h%"G!hp%G!h`%G!hP% G!h@%G!h0%F!h %F!h%F!h%F!h%F!h %F!h!%F!h"%F!h#%F!h$%F!h%%F!h&%F!h'p%F!h(`%F!h)P%F!h*@%F!h+0%zF!h, %rF!h-%jF!h.%bF!h/%ZF!h0%RF!h1%JF!h2%BF!h3%:F!h4%2F!h5%*F!h6%"F!h7p%F!h8`%F!h9P% F!h:@%F!h;0%E!h< %E!h=%E!h>%E!h?HHB!HtHÐU=(!HATSubH=C!t H=E!bH@!L%@!H!L)HHXH9s DHBH!AH!H9r![A\fUH=@!Ht"HSB!HtH=g@!IAÐG(1fDG,fff.HyB!DG4fff.G4fff.H(HHt HIA1DHHW(H!B!HG(Htu HBHP(1HftH;A!HA!ffff.tH A!HA!ffff.tH@!HQA!ffff.tH@!H!A!ffff.H\$Hl$HLd$Ll$H(HIHtHtHEH;-@!H@!H9EHe@!H5N H8HtMtA$A$Ht EEtxH\$Hl$Ld$Ll$ H(EEo1HLIT$H;?!H;+@!tqH?!H5 H8PfDHEHLX(H\$Hl$Ld$Ll$ H(AfID$LP(>HCHߐP(DH;?!H-?!H5~ LE1H8LH?!HHxHL`PLhXHPHHXPHhXHtMtA$A$MAEAEIELH5>!HfDHEH1P(HCHP(IT$ IT$L+ID$LP(iHG@P(D!t%H9t/AD$1H$Hl$Ld$HfHCHP(H9uAD$1H->!H5 H8Hl$Ld$HH\$HHItNH=!t%H9t/AD$1H$Hl$Ld$HfHCHP(H9uAD$1H=!H5F H8fHl$Ld$HH\$HHItNH =!t%H9t/AD$1H$Hl$Ld$HfHCHP(H9uAD$1H =!H5H8Hl$Ld$HH\$HHItNH{u3HCHHl$PH\$HLd$XLl$`Lt$hLX(L|$pHxAH\$HHl$PLd$XLl$`Lt$hL|$pHxDH 8!H=:1HIMkAE111ۃAIFLP(DHEHP(D0IELP(DID$LP(Dff.SHHHtH[HUw!H=H1w!0sv!H(w!CȐHH5w!PPHtHH w!H=Hv!s'v!lHv!1HHv!PPHtHHv!H=zHv!%u!)Hv!1HthW4G,99}St^H='x!11nHOv!H2v!^tu! H)v!H==H1HfH=w!11Hu!Hu!\u! Hu!H=w!11Hu!Hu!Xt! Hu!fffffff.HHu!PtH7!HHtHUu!H=H1u!vst!5H(u!C1ffffff.HHu!PtHF7!HAHtHt!H=Ht!t!1Ht!1ffffff.HHt!@tH6!HHtHrt!H=HNt!s!(HEt!`1fff.HHEt!tHc6!H^HtHt!H=kHs! s!9&Hs!1fff.HHs!PhtH5!HHtHs!H=6Hqs!r! Hhs!1ffffff.HHes!P8t,tH4!HfHI5!HdHtHs!H=Hr!{&r!Hr!1fHHr!PtH5!HHtHr!H=Hr!Wq!Hxr!1ffffff.HHur!tH4!HHtH2r!H=KHr!QPq!Hr! 1fff.SHGHÉt[#HfDtHq!H=Hq!&p!Hq!fSHGHÉt[HfDtHOq!H=H+q!mp!H"q!=fSHGHÉt[CHfDtHp!H=Hp!o!Hp!fSHGHÉt[HfDtHop!H=HHKp! o!HBp!]fSHGH־Ét[bHDtHo!H=Ho!o!dHo!fSHG־Ét[HfDtHo!H=Hko!n!BHbo!}fSHGH־Ét[HDtHo!H=Hn!=n! Hn! fSHG@־Ét[HDtHn!H=HHn!m!Hn!fSHGHPpÉt[HڐtHGn!H=H#n!em!Hn!5뺐SHGHPxÉt[FHڐtHm!H=Hm!m!Hm!뺐SHGHPpÉt[HڐtHm!H=Hcm!l!HZm!u뺐SHGHPxÉt[HڐtH'm!H=Hm!El!vHl!뺐SHGHPpÉt[&HڐtHl!H=PHl!k!THl!뺐SHGHPxÉt[HڐtHgl!H= HCl!k!2H:l!U뺐SHGHPpÉt[fHڐtHl!H=Hk!%k!Hk!뺐SHGHPxÉt[HڐtHk!H=Hk!j!Hzk!뺐AUIATIUSHHGP(AD$At$,HcIT$ <@t]u]HcʼnH|1ҐHHH …D5AD$,IU1H[]A\A]1=k!>t~,EH1H|HHH H9u1@HfDtHj!H=H[j!Ni!&HRj!mZfDAUIATIUSHHGP(AD$At$,HcIL$ <@t}uy1҅~(Hc1H|HHH … HH!HH 3AD$,IU1H[]A\A]1=i!>t1҅~CH|f.HHH H9uHtH?i!H=Hi!-]h!@Hi!-nfDH\$Hl$HLd$Ll$H(HGIPt7HCDk,LHP0t6Dk,1H\$Hl$Ld$Ll$ H(HuUfDfDHtHwh!HZh!g! HQh!H=eH?h!H"h!dg!a Hh!SHGHPtPs4H{ Ht[fDHg!Hg! g!9 Hg!H=1[fHu H)![Hg!H~g!f! Hug!H\$Hl$HHGHPtS4+S,H\$Hl$HHtH/g!H=0H g!Mf! Hg!fH\$Hl$HHGHPt1ҋC4;C,‰H\$Hl$HHtHf!H=Hf!e! H}f!@Hf!SP0tNHcHt[HPf!H3f!sue!5H*f!H= >1[f.cHtHf!He!s,e!5He!ffffff.HHe!P(tHc}Hft$HfHuAH'!He!Hne!pd!5Hee!H=y1HVe!H9e!k{d!5H0e!fffff.H)e!SP0tNHcHt[He!Hd!%d!1Hd!H=c1[f.HtHd!Hd!c!1Hd!ffffff.HHd!P(tHc-Hft$HfHuAH&!H;d!Hd!`c!V1Hd!H=)1Hd!Hc!+c!21Hc!fffff.Hc!SP@tNHc~Ht[Hc!Hc!jb!&Hc!H=k1[f.HtHgc!HJc!jb!%HAc!ffffff.HHc,HtHHc!H=#Hb!a8b!Hb!1@H\$Hl$1Ld$HIHcHHt ID$HLH@hPHŋtHH$Hl$Ld$HfHCHP(@H\$Ld$HHl$Ll$ILt$H(HGHCLHPHIHc{4HHH{(HLAŋEEtaADtHcC4HS L$A$k4EC4Lu HCHP(H$Hl$Ld$Ll$Lt$ H(HEHP(Ha!1Hfa!`!,H]a!H=qHt wDfDHtH'a!1Ha!J`!,H`!DH`!LH`!`!,H`!nff.AWMcAVIAUIATIUJ,SHHHD$8L|$0HT$ LL$HD$8HD$HD$DHD$0D$DHD$DHT$Ht$LL_HMHHt$8H91Hu@H90DHHHuH~H"!H9wHtBHHH Ht)H9G;Fu HHt$8H HuI9tRI$H8H9LHH9t3HH8H9G;FuHHt$8H9uH|$ t;HT$0H|$ JHHD$0L)HIHt$8 HHH !HT$H5H81HH[]A\A]A^A_H;HD$0L)HIVHH8H !HO$HT$H5H81HH[]A\A]A^A_HtHMHt$8oHB !HT$H5H81SH!$L H UHmH5{AH81H[!H[!{Z![6Hv[!AUATUSHHL-!AEHcHIHc{HHkHHHh L`1H=nZ!HHHHDZ!HL9tH}H9t HtIEHt/AEAEu IELP(HH[]A\A]HEHHP(HEHKH54HPH>!H81DHMZ!H0Z!rY!.H'Z!Ht EEt-H=1'SfHCHP(fDHEHP(DfDH!H5H81gHY!HY!X!.HY!tHY!HmY!X!.HdY!A$A$*ID$LP(HBY!H%Y!gX!.HY!HY!HX!@X!.HX!HCHP(USHx;w4|!t[H!HHH[]@HG8HcH@HHHڃuHCHP(HH[H]HH&H[!1HރHZ!HCH=W!,HHt]11H!EEtTHW!HW!W!2HW!H=H1[H]HCHP(@HEHP(DHW!HrW!V!2HiW!HhW!HKW!V!2HBW!dHCHP(UH%W!HW!JV!|2HV!+f.H\$Hl$HLd$HHGPHHtGH}(HIċt!Mt`AD$H$Hl$Ld$H@HCHP(HV!HhV!|U!b,H_V!H=s륃}uHHHX!1HރHX!HCH=U! HHtotC11HEEt6HU!HU!T!,HU!PHCHP(HEH@P(DHU!HrU!T!,HiU!HCHP(HLU!H/U!qT!,H&U!H\$Hl$Hx&;w4}!HG HcHЃHG HЃfDtH+!H\$Hl$HÿHHHTW!1HރHEW!HCH=*T!HHtQ11HEEtGH^T!HAT!mS!+H8T!H=L1MHCHP(HEHP(DHS!HS!m$S!+HS!uHCHP(HS!HS!mR!+HS!`Ld$Ll$IH\$Hl$H(HA ZID$LP#=f DcHH/HU!1HރH U!HCH=T!HH'N11HEEHR!HR!Q! HR!H=EH\$Hl$Ld$Ll$ H(1fExsE;l$4fDfEl$,1fDAD$4D9AT$,1DAD$,A;D$4AD$,1`H5Q!H=S!1HHD11HdHQ!HQ!P!k HwQ!fH5YQ!H=2S!1cHH011HcH5Q!HQ!ZP! HQ!~f.H5P!H=R!1HH11Ht`HP!HP!O! HP!fDHEHP(fHCHߐP(DHCHߐP(DfDHCHߐP(DHCHߐP(DsHfDH P!HO!0O!7 HO!THO!HO!O! HO!*HO!HO!N! HO!HCHP(HtO!HWO!N!g HNO!HJO!H-O!oN! H$O!H O!HO!EN! HN!iDH\$Hl$1H(tH\$Hl$Hÿ HHHP!1HރHP!HCH=dP!HHtT11HEEtIH`N!HCN!"M!%H:N!H=NJHCHP(fHEHP(DHM!HM!"$M! HM!uHCHP(HM!HM!"L!HM!^H\$Hl$HLd$H(IH-!H~H9HHHHHO!1HރHO!HCH=O!HH11H EEdHL!HL!L![(HL!H=1YHCH9tgH7D$HHL!D$LfZ8H!H\$Hl$Ld$ H(f.CD$H$L!HL!IK!V(HK!8HCHP()HK!HK!K!g(HK! HPHK!HK!J!h(HK!fDHEHP(HCHfP(DZHTK!H7K!yJ!Q(H.K!rfHH5K!Ht$0tD$ZHt HD;HuAH' !HJ!HJ!I!(HJ!H=1HJ!HJ!I!(HxJ!fDSHHJ!H\$H =J!t$D$AHH[f.H=J!HuHNI!H[DH=iJ!HuH.I!fH=9J!HuH I!zHuGH !aHI!HuI!H!&HlI!H=1)HZI!H=I!H!_&H4I!fH\$Hl$HLl$Ld$H(HGIPtcHCHP(LcJ<^HIEteHcs,LHHs 2k,1H\$Hl$Ld$Ll$ H(@HCHP@AzDrDH=)J!11xHYH!H@!?!!H5@!H=A!11@H!@!H@!F?!!H?!ufDATL%7!USA$H[HHHH?!H}jHHtLA$A$t+H諺Hڋu HBHP(H[]A\ID$LP(DHO?!H2?!t>!Q!H)?!H=1;LiHfDWH?!H>!(>!H!H>!H=@!11H>!H>!=!!ufffff.ATL%!USA$HHHHH}>!HH} HHtSA$A$t2HJHڋu HBHP(H[]A\ID$LP(DH=!H=! =! H=!H=1LHfDOH=!H~=!udMHJT%~HHH9uIFDHLPgHе[]A\A]1A^D1=:!>tM~JD%HUf.HHH9u薸HH2H[udMHJT%~HHH9uIFDHLPHX[]A\A]1A^D1=W7!>tM~JD%HUfHHH9uHEHP(fDHCHߐP(DH=y8!11ȷH6!H6!w5!GH6!ѲH8Hq6!HT6!5!HK6!vfDHA6!H$6!rf5!H6!@LđA$H|$t1H[]A\Ð1@q!@!t>uvE<@BNLD$H=Z!LHC!I$LH1[]A\@1=!>@JfDE<@tH|$vǐH@dHc!HF!o!H=!H=!LuH!I$6DH=y!L@!t >U@z!z1>/L=H@H!Hf!!H]!H=6qU@!t1>L[HvH!H! !H!s1>1>#H|$AHH!Hn!l!He!1>-1>H!I$Y胎HuH|$H9H !H!c0!H!USHHHGPC4C0@@HHC tlbHHt'HS(u H{(HGP(Hk(1H[]H|!H_!d!q+HV!H=_jH=!11SH4!H!bY!e+H!fff.AWAVAUATUSHH<$1_HIyH$Dx4EE1E1fAIE9H$HB J, H| I9FH5LKHH1HH1HŋtrHEEuHEAHIP(E9zLLfHHu HCHP(HH[]A\A]A^A_HCHP(fHL轍xH H[@H!LH!!c-H!H=1蒕Hl1PHc!1HD!!L-H;!H:!LH!\!p-H!ffffff.H\$Hl$HLd$HH!IP0 H}8L辌tH$Hl$Ld$Hf.ތHHMHS!1HރHD!HCH=i!lHHt]11HaEEt\H5!H!9Z !3H!H=Y#:fHCHP(fDfDHEHP(DfDHfDH !H !3 !_3H !qH !Hd !9 !3H[ !=HCHP(.H> !H! !9c !3H !AVH !AUATUHSP0A!H}8AD+gE1L-" A9H}8L谊uHHH^!1HރHO!HCH=|!HH tp11HtEEtgHH !H+ !.m !+3H" !H={6[]A\A]A^fDD[]A\A]A^fHCHP(@HEHP(DfDHDDtH !H !% !2H !j@H !Hl !. !!3Hc !H!\fH\$Hl$Ld$HIH1蓂HHt$H5HL ËEEtHl$H$Ld$Hf.HEHP(@USHHtq/HHHX1H=!H˄HHEHڃEtHH[]DHEHP(HH[H]ÐH0HH.HHuH_!HB!w!!,H9!fH=D1vH!H!yC!7,H!EEuHEHP(H!H!y!2,H!H!H!w! ,H!^fffff.SO41W0H9|$9}H{ HcS0HπHtHC 1[H{ iHC H=!11IH*!H=H!SH!*H![ÐSw4HHcO0HcH9v6Hf.HH9wH9tH{ HcC0H(HHC t1[H=d!11賅H!H=Hp!9!Hg!肊[ff.Hl$Ld$IH\$ H(D$ 貂HHAD$<@tl1ƃD$ HZXtYID$HLPtKH~1҉H\$Hl$Ld$ H(1=!>f.H~HftHw!HZ!!-HQ!H=evH5!!H=!1+HHtJ11H/t'H!H!*!H!HCHP(H!H!!H!VH\$Hl$HLd$H(IHD$HGHt$P0tdC<@tN11@H|$V~fH|$fZA$N}1H\$Hl$Ld$ H(1=G!>U~HuH|$Ht}H!H=MH!!PH!҇fffff.Hl$Ld$IH\$@H(D$HH=!AD$<@tg1@D$H~ID$HLPH2|1H\$Hl$Ld$ H(@1='!>@또LD$H=<!LHD$HE!@!t >AD$<@DBH,|H@HK!H.!p H%!H=Ɲ9H=q!LuIHE.fH=Q!LhAD$<@nH1X{HJH{ H^  HU +Hpz9{HtH7 H \ H @1>U1>tH=!11H H  H @H\$Ld$HLl$Hl$H8IL% HD$D$H~H5 A$H9{H{H5 H9t {HA$A$uID$HLP(HT$Ht$H:|IET$LHt$1P0.zHZH H W 7H HyHHA$HՃA$bID$LP(RfD{HHDHk 1HރH\ HCH= ${HH 11H~EEH LH O H H=˂EEu HEHP(Hl$ H\$Ld$(Ll$0H8ffHEHP(fDgHCHߐP(D2H4 LH OV H JH H O, H u HCHP(LH LH K H H\$Hl$HLd$HH(IHHt HAԅu)H{81HtHMH$Hl$Ld$HAH$Hl$Ld$HDUSHHH(H-\ Hk(EHtuHGP(H{8Hk8EHtuHGP(H1[]ÐH\$Hl$HLd$Ll$HHHIH~VH= H HH AЉ$L 7HHH+ AAHNH5AH81vH! H F s/H H=H\$(Hl$0Ld$8Ll$@HHÐH^ H}H- H9t&H;=] tsH;= tj u:@tVAD$H9ft0H;' tNH; tEHt$@t.AD$1YAD$fDAD$1.HuAH HD$H HD$UmA@H5 HuHH5 HuHDEHL$L H5 1H蹗H|$H\$Hc HF  /H= =H9 H ^ /H HE HD$HEHD$u A3Efif9HD$AfH H  c/H HD$fH\$Hl$HLd$Ll$HHHIH~VH= H HVH XAЉ$L HHH AAHH5΍AH81rH H B 3H H=|H\$(Hl$0Ld$8Ll$@HHÐH^ H}H- H9t&H;=- tsH;≠ tjq:@tVAD$H9ft0H; tNH; tEHq$@t.AD$1YAD$fDAD$1.HrAHF HD$HB HD$UmA@H5 HrHH5 H{rHDEHL$L sH5C 1H艔H|$H\$H3 H CX 3H =H H H. 4H HE HD$HEHD$u A3Efif9HD$AfH Hz B 3Hq HD$fH\$Hl$HLt$Ld$ILl$HHHHSH5 I,HRL AH $LIHAH5HSHIH AH81oH H 2 H H=1yHHl$(H\$ Ld$0Ll$8Lt$@HHHJpH5 Ht$SKTH51 H9pHSHL$L H5 AH1EeH5 Ld$L-9 LAEpHH@H; t(H;^ L9wHn6H LP@EHu HD$Ht$LP0H|$mHHAEAEH|$)mHڋaHBHP(RDLD3pHHDt&Hnŋ@@mH&H Hf : "H] HCHP(fD[1DLcIELP(DHCHߐP(D6H H 9 H u HCHP(H=1vLH Ho 9 Hf lH HW H: C| ZH1 H) H EN cH ]HCHD$@+lHfDfH H < /H H H| 2 Hs HD$<@H\$Hl$HLt$Ld$ILl$L|$HHH~H-} H5> EH9t plHIl=B D$"H D$L(HEHAEAEu IELP(HHl$ H\$Ld$(Ll$0Lt$8L|$@HHDlHHLH 1HރH HCH=9 TlHI"11LEoA$A$ZH IH 5 'H H=c1s L|$H=D LHU EE H5: ILjHH&H; At)H; H9HhAE4_ @!t >AF<@"LuiH@H H  'H HEHP(E1D5AF<@tJLu8hHt.H7 H \ 'H "@H! LLP=hHfH H  'H H=9 LH= LIH5 HCHP(2Hb HE  x'H< CHCHP(4H H D 'H u HCHP(I@1>1>eID$LP(HCHߐP(DZfHH{ H^  'HU fHQ H4 v v'H+ ( OH5 ID$LP(HCHߐP(D$HCHߐP(Dz1D1ND1mf.HCHP(fDID$LP(DHt HW * _HN u HCHP(MA$A$ID$LP(H H *3 vH H H * mH nH H * dH DH Hv ( JHm ID$LP(HCHߐP(DH< H *a ]H H H53H8SbwH H + H H H + H H H * bHx :Ht HW * kHN HJ H- *o tH$ H H (E EH jDH\$Hl$Ld$HIH5aHHtUH_ŋt0t;H LP HtgH$Hl$Ld$H@HCHP(@^HtHg H=8HC g L5H: Uh1뚐H1 H=H hO \5H h1aH\$Hl$Ld$HIH5`HHtUH^ŋt0t;ID$LP HtiH$Hl$Ld$HfDHCHP(@]HtHg HJ  .HA H=BUg1또H1 H V .H fH\$Hl$Ld$HIHE_HHtUH]ŋt0t;H LP8HtgH$Hl$Ld$H@HCHP(@\HtHw H=HS x 6HJ ef1뚐HA H=jH y_ '6H /f1aATIUHSH H~H9H2]H}H5 H9]]HH HL 1HރH= HCH=b }]HH 11Hn`EEH> H! c 0H H=y~,e1cH}HH92HK]HHH[ŋt"H LP Htj[]A\HCHߐP(DH Hr  0Hi L@HEHP(HCHߐP(DH< H a 1H cZHIH H ( 1H H H  0H HCHP(}DH\$Hl$HLd$HHH~H5l H9uIHsHHHp HHH H$Hl$Ld$HqZuH{H5R H9KH[HHu8YHHyH H=Z|H  %H b1gXHGH H= |H_  %HV qb1f.H H5bwH8Z@xYfDH芬HILƮHA$A$ID$LP(AT1US ZHH  H& HH cXHH)  1LXHH k 2XHH ' H=ԁ11"XHH  WHH  H- H Hu3H{UHEHH8tIH H+H{t {{fDuHsH{FVHEHH8uH H  ;H| Hg  ;H^ fDH=&l`H% H []A\fDHsH{1҃UHEDHٞ H5 H=ǀ1AXHH H=PwUHH 7H= H59HWIHʛ 0H H=Z HUHH H=; H HUH,H H= H HfUHH H= H H@UHHh H= H HUH8Hr H= H HTHYHT H=} H~ HTHH6 H=W H` HTHTHP H  H Hw Hx Hy H H. HWH HWH HH HH HH HAaH HH HpH H'pH HH HkoH HmnH HH HH HmH HkH HH HɛHz H;kHt HjHn H_jHh HiHb HiH\ HiHV HhL% HI H2hLH@ HgH: H3gH4 HfH. H7fH( HeH" H;eH HdH H?dH HQH HcH HEH HWH HIH HH HH PH= 1I$PHHt/H5|HHQPŋWNHm HP  _<HG fH= HGP(DH) H N ;H fDH H= H5{RVH H  ;H T@H H  ^<H &fDHy H\  ;HS fDHI H, n ;H# H= H5zLQH9 H L%{ H H]HH HH HH HH H~H H|H HqH NHs HV ( t<HM HI H, n `<H# HCHP(H HH8OH H H " ;H H  ;H RH HH8 OH HN Hq v ;Hh Hה HH8NHU H" H- ro ;H$ RH HH8NH H H ( ;H HI HH8NNH H H  ;H H HH8NH HU HX O ;HO }H HH8MH9 H H yS ;H 6Ht HH8yMH H H . ;H H5 H)y*H H ( u<H #H=T H5/wHMN&H^ HA ( v<H8 H4 H Y ;H H H / ;H cH H  ;H 9H H  ;H 3H Ho  ;Hf Hb HE  ;H< H@ H H H-{ HD HHH HBH HBH HBH~ HB H{ HB(Hx H9HR HHd HuH^ HHX HIy*H Hl  <Hc H5 Hy*HH H+ m <H" H= H5buHKy*H H ) <H H= H- H5 )H( HA H= HHHHy*H Hx  <Ho H5 Hy*HT H7 y <H. H= H5sHJy*H H 5 <H H H H0 Hю H HHH HBH HBH HBH HB H HB(H HB0H H HhGy*H] H@  <H7 H5C Hy*H H A <H H= H5NsHIy*H H  <H UH H Hh H H HHH HBH HBH HBH HB H HB(H HB0H HB8H HB@H H HFy*H H >4 <H H5 HQy*H H > <H KH=| H5rHuHy*H Hm > <Hd H H H"  ~ H H` Hy H[ Hs H H 1H H[ 1H Z ffff.Ld$Ll$IL|$H\$IHl$Lt$H8H~L- L9$LFI|$H5 H9FGHHH 1HރH HCH= .GHHD11HJEEH H  .%H fH=hN1H\$Hl$Ld$Ll$ Lt$(L|$0H8I|$LL9H5 L1EHHCL5w L9nH;߉ tH;~ tHCTt?H= 11IH H  Q%H DH5a 1LDHHL9t,H;B H;݉ HBtj[I|$L9sIt$HHH\ HLHp fHCHP(HCHߐP(DfD1mDH H  <%H HCHP(H Hg  A%H^ H] H@  $%H7 rfHEHP(3HCHߐP(DH H 1 :%H !L1C}I|$H5 H9A|$x[LSDHH[AHHFH Hm  ]%Hd H H5z`H8CAH H3 H X ^%H HH H & ?%H H H  )%H ALHHHSHËEEHEHP(AW1AVAUATUSH(L=  D$ H\$ A|$ @H|?<@HHD$XAAH=E 1V@-' D$ @@te@!t@>uY@fKBHH CCGCGCGCGCGCGGHH>H5 H@AHHH @@HH@!t @>HH Hi HH@!t @>HHi HJ HH@!t @>D= HH3 @@t1@!t 1@>@H= >f. lH@@H t1@!t 1@>@H= >f.kH@@H t1@!t 1@>@H=o z>f.kHH H=H# H= H5hHD$?HI1E113@HHt/H= >HIsEEu HEHP(A$A$1Htu HCHP(MAA=H5v Lv=HH H $H5M LH >=HHH53 H#=HH@H H5 LH- 25HHҸ H { H tH=a 119H H=m^Hm  Hd >4HHR H=$_H. p H% @>s4HH Hl$MH 0 H PH\$Hl$HLd$Ll$H8FHՅH.D EtRC!C, C4C0C(61HHC teH\$Hl$ Ld$(Ll$0H8fufD3HtH7 H \ KH <H=ɸ 118H Hܶ  HӶ H=V H! }c $H H=O,41DH}HH92H}H9CHmHʼnH9ttHtVHp H50OH8,*HtSH H Ϭ $H g)HufDfDf@tHo LtcHo []A\H0 H }U $H DHEHP(HCHߐP(D+)HtHϬ H  $H @H)H}H5n H9uSHP(HHq HT } $HK $HCHP(D{)uH|HHRH~HŋHCHP(ATIUHSHm H~H9H)H}H5m H9()HHcH 1HރH HCH=B ])HH!11HN,EE]H H pC $H H=M 11DH}HH92H}H9(H]ÉH9teHtoHxzHl H5LH8(&HH LHl []A\Dfu&HufDHl H5KH8r(H H p> $H H Hҩ r $Hɩ @HEHP(HCHߐP(DaH&H}H5k H9HF%H%HfDHS H6 rx $H- 0H) H pN $H HCHP(D3&\HJyHH~HzHËEEHEHP(AWIAVAUATUSHL-j H4$H5E AE$HHH5@ 1HN&HH+H}L% j L9!HEHD$H|$FEEH5¨ H<$)$HH]H5 1H%HHjEEH{L9yHCHD$H|$%HHALx1H= HO%HIAEAEaH5 H<$Q#HH;%HHH 1HHHn HC$HIEEP)A$A$H5g L"HIy$HHH 1HLHܦ HCH Hߦ HC &$HHA$A$EEH5 L"HHH5 H<$!HHH5 1H#HI#HHL`1HH]#HIEEaA$A$6H5 LO!HIH|$!HH##HHHX1HL"HHA$A$7EEH5` H<$ HHH|$!!HH"HIHh1HH."HHA$A$EEH5Ȥ L HH "HIHO 1LHH= ID$!HHEEA$A$[fAMLAEAEu IELP(HH[]A\A]A^A_HEHP(fHCHߐP(DHEHP(D,HCHߐP(DEIELP(DHCHߐP(D_ID$LP(DHCHߐP(DHEHP(DHEHP(DLHCHߐP(D#ID$LP(DHCHߐP(DgID$LP(DHCHߐP(DHEHP(DcHCHߐP(DHEHP(DID$LP(DHEHP(DTID$LP(D+HCHߐP(DID$LP(HCHP(HEHP(DMHĠ H  (H fDH=B1&;H E1Hf  (H] Du HCHP(Ht EEt)MtA$A$uID$LP(uDHEHP(DLCH}H5b H9HHD$H@H E1H ͞ (H :DHy H\  (HS HO E1H/ q (H& LqwH{H5Na H9HHD$Z>HUH۞ 1E1H  (H SH H Ν (H H 1E1H]  (HT HP MH0 r (H' H# ME1H B (H H MHӝ  (Hʝ -HƝ MH  (H @H MHy  (Hp :Hl MHL  )HC H? MH a )H yH ME1H 1 )H H MHœ  )H \H MH כ )H DH MHh  )H_ H[ MH; } -)H2 H. MH P /)H H MH # 1)H؛ {Hԛ MH  6)H cH ME1H ƚ E)H{ Hw MHW  C)HN HJ MH* l G)H! H MH ? L)H H MHК  Y)Hǚ *HÚ MH  [)H RH MHv  `)Hm %^HjHHHD$SHFlHD$EEHEHP(c4HzjHHHD$)HkHD$HCHP(f.ATIUHSH[ H~H9HH}H5[ H9HHlH 1HރH HCH= -HHj11HEE=H Hј c B$HȘ H=i;1DH}HH92H}H9CHmHʼnH9ttHtVHZ H5:H8HtSHZ H= e N$H4 g{HufDfD@@tH LtcH7Z []A\H H× c 8$H DHEHP(HCHߐP(DHtH Hb e O$HY @HH}H5}Y H9uSHHH! H cF =$H $HCHP(D+uHFgHHRHhHŋHCHP(ATIUHSHX H~H9HH}H5X H9HHcH 1HރH HCH= HH!11HEE]HΕ H V #H H=81DH}HH92H}H9(H]ÉH9teHtoHxzHW H5T8H8HHI LH]W []A\DufCHufDH1W H57H8"Hɔ H V #H H H Xē $Hy @HEHP(HCHߐP(DaHH}H5wV H9HHiHfDH H X( $Hݓ 0Hٓ H V #H HCHP(D\HcHH~HveHËEEHEHP(H\$Hl$HLl$Ld$HXHIHVH- H8L 2:H 9A$LOH8EH9H5)HOHT AH81H H ʑ H H=51@Hn H{HHAIHiAċA%H}H5T H9HmHcʼnH9gH D$ HT$ \$$DLPHHT H\$8Hl$@Ld$HLl$PHXfHCHP(bHfDkAH HD$HD$STH5G HGHHD$AAH5$ HH DCHL$L )8H5v 1H*0H|$Hl$s& HHƐ H  H HHR H51H8 HoHf HI  H@  H}H5hR H9H HS HH H֏  H͏ IHC HD$HCHD$XpE@ HfSi ;H_HHHFaHŋHCHP(H H ; H lHD$H\$Hl$HLd$H8HIHVH5L 4AH 4$LIH4AH5B%H5HIHHP AH81J HS H6 x H- H=1A1H\$ Hl$(Ld$0H81H LP`H7P fH^H5O H{H9PHkHcʼnH9pu@HD HD$SH5m Hu HSHL$L 4H5r AH1,RH|$H#&n HH H 0 H 3 HHӌ H  H {HCHD$MfD H{H5N H9H&HHfHN H5t-H8| rH H H 7 H H Hˋ  H‹ HD$O @LH\HHjH]HŋHCHP(DHf'ff.H\$Hl$HLt$Ld$ILl$HHHHVL% 'H52L 0AH 0$LIH0AH5!H1HIHL AH81H H lj >H| H=-.1HHl$(H\$ Ld$0Ll$8Lt$@HHH-H HD$SH5 HH:SHL$L 81H5o AH1()Ld$L-!L H5b LHD$AEHHH;K t(H;6K XL9OHzI|$H5JK H9Il$HcʼnH9>^H> Ht$LPXH|$HHtAEAEH|$HڋPHBHP(AH LP@ÉiHYH Hb  bHY @HCHP(fDfD1DLf7IELP(DH Hׇ  WH· u HCHP(H=j+1 LH H Ɇ UH~ H} H`  HW H?HH H+ m {H" dDHCHD$fDH@H3I H5(H8$HH H ݅ oH D:I|$H5H H9uL:HuLVHHnHBXHŋHCHP(cH f/H H߅ ! 1Hօ UHD$H\$Hl$HLl$Ld$ILt$HHHHsVEfH+H +AЉ$L >+HHH2G AAH`,H5AH81H( H M 1H H=( H\$ Hl$(Ld$0Ll$8Lt$@HHH^ L%F H{L9H[HcÉH9H]H{L9TH[HcÉH91HH^IU8tI]81S@L%9F I}8HGP(DHHD$HD$AċUqoADH5 HHcH5ӄ HHADEHL$L *H5i 1H"H|$HtjH|$HNDHH3 H X 1H H H & 1Hۂ HHE H5$H8 H7H H ΁ 1H |fDHE HD$HEHD$}u AE@fLDH{H5_D H9HHvHfOHCD H5,#H84/H1Hρ H  1H @LH{H5C H9uHHPHHHc HF  1H= 6uHQHI?L#SHAAKIFLP( H9HFHwHfDHS| H6| .x{ )H-| HyHg> H5PH8XSHAH{ H{ ,{ )H{ VfLH{H5= H9uhHpHt1fDADHHc{ HF{ ,z )H={ uHKHIL#MHA$A$ID$LP(D;dHRKHHHLHŋHCHP(DHtfH} __del__%s (%s:%d)cpyamf.util.IndexedMap.clearcpyamf.util.IndexedMap.append%s() keywords must be stringsexactlycpyamf.util.IndexedMap.mapMissing type objectCannot convert %s to %scpyamf.util.swap_bytesan integer is required__init__at leastat mostcpyamf.util.cIndexedMap.clearcpyamf.util.cIndexedMap.map__pyx_vtable__read4294967295__builtin____builtins____name__cBufferedByteStreamcIndexedCollectioncpyamf.utilcpyamf.util.is_broken_float__import__cpyamf.util.complete_import__cinit__seektruncatepeek cpyamf.util.cIndexedMapcpyamf.util.IndexedCollectioncpyamf.util.IndexedMapcpyamf/util.cutil.pyx__iter____getitem____copy__writecloseflushtellremaininggetvalueat_eofconsumeread_ucharread_charread_ushortread_shortread_ulongread_longread_24bit_uintread_24bit_intwrite_ucharwrite_charwrite_ushortwrite_shortwrite_ulongwrite_longwrite_24bit_uintwrite_24bit_intread_utf8_stringwrite_utf8_stringread_doublewrite_doubleread_floatwrite_float__add____str__endiangetByReferencegetReferenceTouse_hashexceptionsgetMappedByReference;(8HXhx0H`x8hXx @`XhH0H(`xhH (8Phh(H ( 8P xx h   X ( @ HX p  H  0 P Xp    X  H  8 X  H  (   H@ ` (  "& (@H)`(*+=?@D@xE`xGhIhKK(L L@N`xOPQ(RSTW0ZPX[p[^bglsHthxuxvxz0hȠ8(xx8Xxȼ880PHpXxXzRx h 4`LX dP|H@H7Dp### #$JQ0DpJL dJL PJL JL $0eJ[xOAMDMD4 DLaDd`aD|dDdDhaD~D(aDdD gA$0gA<gATgAl8gAgAgA@gA_A_A(_Ap_A,_AD_A\H_At_A$*BED C(D0$:BED A(F0JQ0APwN ,|N D H\Dt@HD`HLD lJK pJY04BEE E(D0E8DLXJQP$lBBA A(G0pAAD 0JL N XJQ0 XP $ gJL0DpD \>AD |(JQ0JL $BEL C(D0PjJL jJL $jJL D@ZBHA d RBHA  ZBHA  RBHA @ zBAD , BHE A(A0, BHE A(A0D AAG0d LJL0 JQ0 @JG  JG  jJL 4 BBB B(A0D8Gp< .FJQ0\ 0AAG $| 1BID D0 P5AAG 4 6BBB B(A0A8D@ 7JL , 9BIB A(D0L x;AG0l ;,A |JN  >rAAG  P@A @A4 PAJQ0T BJL0t CJQ0 FJQ@ IkJL  I_AAG  J.JQP 0M.JQP4 @PJMLP$T UgJMQP,| hZBHB D(A0 8aJN  bJN  bJN  ckBDD ,fJO LgBCA $lypJMQ@4~ BDB B(A0A8D`(/JQ@8fDnD{JO <H{JO \JO |XJG 8BDD 8MBDD 4hBEB B(A0A8DPBDD 4MBDD T@_JQ`tJL@yJMLP`JMLP JMLPRG @RG 4WG0TWG04t@BEB B(D0A8DPw J _Xox8  В!D. ooo,oH!KK.K>KNK^KnK~KKKKKKKKKLL.L>LNL^LnL~LLLLLLLLLMM.M>MNM^MnM~MMMMMMMMMNN.N>NNN^NnN~NNNNNNNNN! C-extension for L{pyamf.util} Python module in L{PyAMF}. @since: 0.4 strict__main____cinit____dealloc____init__readwritecloseflushtellremaining__len__getvalueat_eofseekpeektruncateconsumeread_ucharread_charread_ushortread_shortread_ulongread_longread_24bit_uintread_24bit_intwrite_ucharwrite_charwrite_ushortwrite_shortwrite_ulongwrite_longwrite_24bit_uintwrite_24bit_intread_utf8_stringwrite_utf8_stringread_doublewrite_doubleread_floatwrite_floatappend__add____str____iter____richcmp____getitem____copy__getByReferencegetReferenceTocleargetMappedByReferencemapbufvaluesizexposmodeobjvaldataselfotheruse_hashexceptionsopidxrefmapped_objMemoryErrorpyamf.utilReferenceErrorutilNaNNegInfPosInfIOErrorValueErrorOverflowErrorTypeErrorgetvaluegetvaluereadseektellidNotImplementedErrorRuntimeErrorBuffer closedBad value for modeinteger out of rangeinteger out of rangevalue must be Unicode or strUnable to coerce buf->StringIOString value expected!@<>Not a valid endian typeexpected int for xexpected int for xexpected int for xexpected int for xexpected int for xExpecting float for valExpecting float for valReference not foundObject not foundBad reference typeUnknown referenceUnable to add to mappedUnable to map object Reads C{size} bytes from the stream. Writes the content of the specified C{x} into this buffer. @param x: @type x: Close the stream. Returns the position of the stream pointer. Returns number of remaining bytes. @rtype: C{number} @return: Number of remaining bytes. Get raw data from buffer. Returns C{True} if the internal pointer is at the end of the stream. @rtype: C{bool} Sets the file-pointer offset, measured from the beginning of this stream, at which the next write operation will occur. @param pos: @type pos: C{int} @param mode: @type mode: C{int} Looks C{size} bytes ahead in the stream, returning what it finds, returning the stream pointer to its initial position. @param size: Default is 1. @type size: C{int} @rtype: @return: Bytes. Truncates the stream to the specified length. @param size: The length of the stream, in bytes. @type size: C{int} Chops the tail off the stream starting at 0 and ending at C{tell()}. The stream pointer is set to 0 at the end of this function. Reads an C{unsigned char} from the stream. Reads a C{char} from the stream. Reads a 2 byte unsigned integer from the stream. Reads a 2 byte integer from the stream. Reads a 4 byte unsigned integer from the stream. Reads a 4 byte integer from the stream. Reads a 24 bit unsigned integer from the stream. Reads a 24 bit integer from the stream. Writes an C{unsigned char} to the stream. @param x: Unsigned char @type x: C{int} @raise TypeError: Unexpected type for int C{x}. Write a C{char} to the stream. @param x: char @type x: C{int} @raise TypeError: Unexpected type for int C{x}. Writes a 2 byte unsigned integer to the stream. @param x: 2 byte unsigned integer @type x: C{int} @raise TypeError: Unexpected type for int C{x}. Writes a 2 byte integer to the stream. @param x: 2 byte integer @type x: C{int} @raise TypeError: Unexpected type for int C{x}. Writes a 4 byte unsigned integer to the stream. @param x: 4 byte unsigned integer @type x: C{int} @raise TypeError: Unexpected type for int C{x}. Writes a 4 byte integer to the stream. @param x: 4 byte integer @type x: C{int} Writes a 24 bit unsigned integer to the stream. @param x: 24 bit unsigned integer @type x: C{int} Writes a 24 bit integer to the stream. @param x: 24 bit integer @type x: C{int} Reads a UTF-8 string from the stream. @rtype: C{unicode} Writes a unicode object to the stream in UTF-8. @param obj: unicode object Reads an 8 byte float from the stream. Writes an 8 byte float to the stream. @param val: 8 byte float @type val: C{float} @raise TypeError: Unexpected type for float C{val}. Reads a 4 byte float from the stream. Writes a 4 byte float to the stream. @param x: 4 byte float @type x: C{float} Append data to the end of the stream. The pointer will not move if this operation is successful. @param data: The data to append to the stream. @type data: C{str} or C{unicode} @raise TypeError: data is not C{str} or C{unicode} t8 !`!!!!t80 !!P!`!Ew@P`P Y@! Vw@!!!@!E `!pWt8!@!!pY!u!!`w80!!0!`!Ew@P`P!!Vw@!!!@!Ew !!@XP!h!8!8!@!H!8!X!`!X!`!0!X!`!X!`!w!! `!! h!! p!! !!!!x!ĕ!!ʕ!!Е!!Օ! !ߕ! !! !!(!!!!!! ! !!! !! !'! !3! !>! !I! !`!!p!!! !! !! !! !!  !! (!Ж!0!!8!!@! !H!2! P!>! X!K! `!V! h!b!p!i!x!q!!y! !! !! !! !!!!!!!З!!!0!!!!8!!!!@!!H!!P!!!!! !!!!!X!! `!$! !/!!2!!6!h!:! p!E! x!Q! !\!!k!!p!!t!!{!!!!! !!!! !! !! !!!Ę!!ɘ!!Θ!!!!! H!!P!!X!0!`!P!h!e!p!p!x!!!!!ƙ!!ș!!ʙ!!̙!!Й!!!!!!0!!P!!p!!!!!!К!!!!!!0!!P!!p!0P`m0PPw@wPxt' P Pv! x]!xp]`!xPxm! xpl!*x Y`!3x\!nw= !|wE !sw`A !:x\!Bx`!Mx!WxP!cx@!nx!yx!x !x!x9!x6!x`$ !x@!!xp!x`!x!xp! yp!y\`!-yЅ!9y !Fy !Qy !u[!]y'eypYmyXPty@yku ku0[yPUyP@UtyPypjuiuZy@uryQTy0Q TGCC: (Debian 4.3.3-5) 4.3.3GCC: (Debian 4.3.3-8) 4.3.3GCC: (Debian 4.3.3-8) 4.3.3GCC: (Debian 4.3.3-8) 4.3.3GCC: (Debian 4.3.3-5) 4.3.3LOJ _,O<\J_RJinitutil__pyx_module_is_main_cpyamf__util&__pyx_type_6cpyamf_4util_cBufferedByteStream=__pyx_type_6cpyamf_4util_cIndexedCollectionT__pyx_type_6cpyamf_4util_cIndexedMapk__pyx_type_6cpyamf_4util_BufferedByteStream__pyx_type_6cpyamf_4util_IndexedCollection__pyx_type_6cpyamf_4util_IndexedMap/home/aurel32/debian/co-packages/glibc/glibc-2.9/build-tree/amd64-libc/csu/crti.S/home/aurel32/debian/co-packages/glibc/glibc-2.9/csuGNU AS 2.19.1;kUO^8K9/K;YintSi[1iB?1?-o *b# N# ># 1# 4# /#( ! #0 V=#8 B2#@ ]"#H N#P , #X NC"#` $#h &b#p NS*b#t Q,p#x K0F# Y1T# 2# 6# Q?{# BH# #I# BJ# BK# BL-# 8Nb# P#   i6 _&# ,# KRb#    bS  7K . 79Mfe Tgb# gW# xgW Tb# W# b# b-# Zb# Bb#$  #( K #0  #8 F #@ W| #H Q #P o9f#X V.l#` =r#h @  #p y #x   # 3 ; # Gq # y.x# 8Ui# :# ED # b# ! # 2:$i# I( # H) # 3,# :D-# G.x# J/W# '0# OI1 # Y2 # i3i# 4 # 05@# *6# 7 # 8# 9# Q4:# Q;# E<# ===# -> #ee&h<j Tkb# kW# kb#J6~]7$b41?EbZZZp kqbm bb4bb4b bbb7-IBHbbbbAB~bJbbU[bJ  b 7! ' bA 0u d# V# _G# &# = # [#( #0 u&#8 =#@ N#H #P 7#X g#` J#h #p n&#x 5# Y4# Y# # 6# !# PA# !# `Z# # +# L# E# a # R# .# ?E# BP# # G# I# G+#~A P H# # I`# P`# Qʆ# {˱#( #0 O#8 #@ `#HR<р S QD# # e #yS  ٟ 7# O h# 9s# Z$ݙ#)^ G   +   h(  b  b> & ; 4;`Q W bq m 1">  i -   bycX! A; &@W&3KQfWbu  S   , M8"# :## *$b# %8%#~} - CB(# )b# Q*b# *+b#doc,#(.x CB #get #set #doc # - # $/Ge9  T b#  W# h i#B   T b#  W# ?Q 5#( #_ T $b#  $W#  $b# pA %i# ? &b# '#$  T b#  W#  b# / #    Tb# W# b# /Z#+@ u T b#  W# X# N# # #( Q#0 R#8rI( Tb# W# # 0# # uY mC  b&~_isH `&# 0# RT# /# S# { #( #0 #8 7b#@,_ts  `&3# 4# B65# K7b# 8b# 9b# 1.;#( B<#0 R=#8 3>#@ @@#H wA#P Q#B#X ,ED#` E#h *F#p 4H#x Jb# Kb# M# XNi#[!,)b55b;B  Tb# W# b# C5# 5!# S#( J#0 G#8 Z#@ q Z#H d,#P *E#X #` *#h N2#p !b#x 7"b#| N#b# 9P%b# /&!# ['b# )(b# SB)b# b*b# +#/ R?Qb .pZ#s#ni# # # #]Rfe 0gb# 9hb#8s Ttb# tW# Du# v# Mw# &xb#(posy#, z#0 TD{#4PPHu B# # L # # M'# '#( 3M#0 #8 5#@  s#H #P Q=M#X W'#` D#h R#p T#x # # 0# *;K# .l# 9# # # ]3# G# *2# X # 2 #  /# H J# A e# J# qe# # =# # ,# :# V# #8 8e#18A Tb# W# D# /Ub# b b# CZ# #( #0 TD#4$8 *O:# T-L# U-:# Fg# ^S# n #( #0AS@ 8# +##8%@ 8#T8$ 8#b44$L4@g4R4m4O8 8A#ebb b'bGG-bmm9Sybbibb8bbibb8b0bK6bffFQb[rbbb?bbFb/[bJ85beiPMkbb5b5b.b.($H#7 8$#l,H1r 82A# %3#8map4#@r'4HA 8B7#p T b#  W# X b# Lb# *b# r(b# "# J#( UF#0 +X#8 N#@ Z#H #P )#X b#` X#h N   b# 4* b# V b#$  ! :,;"r>!r>r>tbr> s>s>r.s>P2t>\%5b!K5{/58 5b? 5@ 5b q45 1005 08594G"K484?4b@4 q4 04 104%14b"K4{/484b?4@4b q4 104 04HB4 #KB48C4?D4b@E4 qs4 0w4 10a40bp#K0{/080b?0@0b q0 100 00&P0#KP08Q0?R0b@S0 q0 00 10o00 10:0 0B0"/$K/8/?/b@/ q/ 00 10/X;$K8? q 0Hb%<'8b?b 0 0AT=B%>BR=!S=8=%>B=#=b==~G=:+=u9=*=C>M%x>!"val>iG?[&x?!"val?i.>F2&x>!"val>i ?]&x?!"val?i>?&x>!"val>i& 'MZb8?b 0 0b_'&5Cb8b?b q  0  0#!#$!$$$$% %%%#!3=b'J0=1=vN2=b"key4="pos5= A= ?IE=78$'L$x$!"r+"m+v*(Kv*;E(K?b 10jWS@bb(tS@b(.&? ='2,bOOw((KU8b) 0O'NEHPPw)(KHU*8I) 0WP'LPPwa)(KU(!T8'A P$Pw)(KAU*8B#) 0P P'<-0P4Pw*(K-U*8-F) 0-0P9OW7bL*oW7vW7aW7"eX7b"pY74+*@P[Pw*,*i,#*,-*$7*$A*U8`7b*o`7"pa74"tmpb7-*`PP*,*V$*.*''>9PPwu+/o9U/x9T02$P9#D$1.P$$\$$h$%t$2|$P%$'89PPw+/o9U/x9T0p#9##1.#$#$#%#2#P%#':o:Q#Qws,/oo:U/xo:T0"p:#"1@.".$"$"%"2"Q%#'<}:0QSQw,/o}:U/x}:T0!p~:#!1. "d$"$""%."26"6Q%>"3 2>`QT-42>42>5tb2>")Qk>Q0#!i>#I!#=!#1!1.T!~.`!.l!6.x!6":b TT(.5o:&5v:5x:0!0:#!#!1`.!:$!$!%!%!%!63Ms:bT9U.5os:5vs:5xs:0G"u:#e"#Y"1.q"$}"$"%"%"%"67L9b@UU F/5o9P 5v9 5x9. 0 #9#'###1 .3#d $?#$K#%W#%_#%g#6z 9bUYV /5o9 5v9A 5x9 0#P9####1.# $$$ $%$%!$%)$3; @`VXB o04# @{ *& @ *# @ *> @i *d  @ *C@! *B@o0D7badK@!68XY05o85x80$8#$1.$ $$%$2$X6W_ YmYAk14K_y4!_*8`8?aP qt) 0x3Y6K)pYY14K)@*8)c8?)P q)) 0)Y6u bYZ24Ku 4{(u -*8v bv?w b) 0 0Z)0 Y)q Z)(0 Y):0 Y 10 6~#5Z![34K54!5*85*8?5bP)q5Z) 06Z6210[[`34K14!1*818?1bP)q1\[) 01M[6rR([\44K(L4(o*8(8?(bP)q([) 0([6P-&\t\44K-&4v-&#*8.&F8?/&bP)q=&?\) 0@&0\60  \\|%54K 4! *8 8? bP)q \) 0 \6X\n]054Kh4!Cb*8*?b*@)q9]) 0]66p]]cK64K4!*88?bP)q]) 0]6T]D^64KO4Tr*88?bP)q^) 0^6bP^^U74K44i&*8bI*?b)q^) 0l^6^0b^'_74K4486*8bY*?b)q^) 0^64b0__a84K#44iF*8bi*?b)qb_) 0L_6AYzb_`84Kz344z8V*8{by*?|b)q_) 0_6>*Xb`w` m94KXC44X[f*8Yb*?Zb)qjB`) 0m-`6g6b``.94K6f446F*87b*?8b)qH`) 0K`6 b`WaQy:4K44*8b*?b+)q&"a) 0) a6Bb`aat:4K44?*8b *?bN )qa) 0}a6ba/b ;4K 44 *8b!*?b^!)qa) 0a6#&b0bb! <4K!44"*8b%"*?bn")qZb) 0Ib6*bbb"<4K"44#*8b5#*?b~#)qb) 0b6IjbbOc#=4Kj#44j"$*8kbE$*?lb$)q|c) 0 c6[HbPcc$=4KH%44H2%*8IbU%*?Jb%)qZzc) 0]ic6A?&bcd%#>4K&&44&fB&*8'be&*?(b&)q8c) 0;c6n=bdod&>4K/'44R'*8bu'*?b')q:d) 0)d6bpdd(/?4K?(44b(*8b(*?b()qd) 0d6S bde)Y@4K )4) b)44 }*b*T8**I+*8b~+*?b+@b)qe) 0Te)05d)(0e0$ P#$1P$$$$2 %e2% e6Q/bf:go,A4K/,4)/b@-44/-0b*T1i-*W2b..*I3d.*84b.*?5b.@6b)qg) 0f)0O$f)(0}f)U0f0$|#$1$$$$2 %Cf2%;f6AS b@g)h/uB4KS /4S G 04{(S U0*T 0*8U b0*?V b1@W b)q g) 0 g)0p lg)(0 g6} 0hhS1 C4K 1*8 18? bP@ b8@ P)qA ~h) 0E Qh 0/ 64 hGiC2C4K {2*8 2*? b 3@ b)q i) 0 h)0 h6. bPiiC3/D4K {3*8 b3*? b 4@ b)q i) 0 zi)0 oi6S5iajC4D4K5{44v54*854*?5 58@5P)q5j) 05i65(w5pjkf5wE4Kw554vw55!Sx5*8y55*?z5-6@{5b8@|5P)q5j) 05j 1056q1 kkv6 F4Kq164vq16*8r16*?s1=78@t1P)q1fk) 01?k6F#1kbl7F4K#174v#17!S$1b*8%18*?&1`8@'1b8@(1P)q^1+l) 0b1k 10L16"plm8SG4K84!9*8'9*?p98@P)q.l) 02l6m\m9G4K:4!':*8J:8?P q) 0"m6h7`mm:-H5oh7:5ih7;9ri7J;9xj7;6 ,muo;H4K,4;4v,p<*HT,<*8,=8?,bP@,b*@,^=)q)-n) 0--n)0,n)(0-Xn6Ye=bor=!J44P_=>43`=!J>4"a=I?4 b=Z?48c=.@4d=Q@9keyf=@8f=:posg=D*CBh=!JA*+i=!JEB) =q)=q7bad=)?I=/q0%=#5%#)%Z6JA6rtBK4KA6B4t6A6C4.PA6C*vB6C*TC6D*8D6GD*?E6}D8@F6P)!j6Fr)Ol6r)} o6r)q6r 06;B%Fr|rk6iK#%#t%#h%#\%#P%B%ktt[6#%#t%#h%#\%#P%>-*8?-*?@-T*@A-H*@B-)qx-) 0|-0'c-#'#'1$'.'ڜ65O3@-l4KO3H4vO3ʝ4TO3>P3*8Q36*?R3@S3b*@T3*@U37 q3) 03)0w3n (036320%xm4K24v2w>2*PR2*!S2*82,*?2@2b*@2*@2@ q=3) 0B3@)02Q):0.3p3RH70n5oH7բ"pI74<88K7h8`[K7`:etbK7X0'@ N7# (368 =n5o8C"p83F6ayn5o6ţ<N86h8`[6`:etb6X0(p 6#$(1 $0(2<(6po4K44ZTMj8P*4*8ͥ?b*@<*@8@ bP q) 0)058 10V)(0dK!.?bp4?8?Q?C?b7bad? @-o<lp,o?,o.o.o%p2p6F,@*q4K,44v,*8,/?,b*@ ,i*@ ,ԩ*@ ,C q@,) 0E, 0(,6N*bOq4K*4Ī*%* *T6*V8*Z*8*b?*b)q+):0* 10 +) 0+6MdbPr4Kd34{(d*%e8Ŭ*T6f8*8gbW?hb)q :0 10) 06 bs4Kŭ4R.*tZ?*8bˮ?b*@'*@bp)qS)0")(0?) 0W{)10$W):0<q0$ #$1 $$$$2 %:2%,6z2/b̯t4K/4T/M80XtZ1?*82b*?3b@4b)q] (0h) 0)0u)100$0 ~#$1` .$($$2 %2%6Yb^ w4K4mS5߱*d05b*8b?b*@b)q)0 )10o L0 C0 U0 :0 (0) 0"8 )).B$ 2v#$1 $$$$2 %2%;$v#$<$$$$2 %2%B$ v#$1 .$$$2 %2%0$P #$1 $$$$2 %2%69bԳx4K 4vV*-ش8H8ZTT*8bߵ?b*@(*@8@bP qT 0) 0Y)(0,)10.G :0F68bx5o8>5v85a89e8bR"p80*  8#z*#q*#h*1 $7*$A*64'8b 5y5o'89p(8 9tmp)8.>*)S*8#*<)S$*.*do@bRyxo@6^+D/bN{4KD/ӹ4t6D/4.PD/*)E/*[F/*8G/b7*?H/b)!r/)Ot/E)} w/x)q/E :0/ C0/ 0/;B% s/z#%#t%#h%#\%#P%< .%$%$%;5yx/z#Gy;5y/z#Gy= 7{* 9L/8 M/K@=P {*^/[1 *Y/83I/l P!6m33b9J}4K3r4t634.P3*)3*[3*83b*?3b)!3)O3u)} 3)q14u :0 4 C0-4 044;B%P3|#%#t%#h%#\%#P%<P.%$%$%;5y3|#Gy;5y 4|#Gy= 3}* 938 3K@= }*31 *30833l 0!@}}b@k@"x@64K4t6Z4.P*{(*T*b*xT*8k*?*@b*@=8@bP)!-)O)}  P q):0H)C0F) 0E;B%-##%#t%#h%#\%#P%<-.%$%$%=@ b* 9A8 @1 *C5yu #GyCJ}h "#\}1 $f}.r} 83|  !6j-&G{4K&4mS&*R&5*05&*8& *?&bV*@&*@&G*@&ba q')10'0)C0m' ')U0'8)'4) 0't L0'):0'NC5ypx'#Gy;$!/'l#$4>.*8.*?.8@.P)q.) 0.?J}Z.#\}1$f}.r}6%6@8L4K646*6*86&8?6P)O6 } 6 q/6 036?J}J06#\}1p$f}.r}o62/0@4K040N*80?0b*@0*@0u*@0 q1 100) 01?J}P1#\}1$f}.r}-6%pև4K%4% *T%8y*8%8?%bP)O%p)} %)q% 0%0/b`%#bA.Pb1$^b.jbT>;b q;!#W(;b q;X*>J4*>CB*>C+>D2;pcx?;)q< 0p#5p1p.o .oe%p2p6t%p 4K%4T%*8%f*?%b*@% *@%g*@ %b&@ %b*0@ %88:@ %bP qb%)101% :0T%) 0g%C5y<%#GyC5yA%#Gy0/b ]%#bAӋ.Pb1p$^b.jb-1b>8b?b@b q 0 (0 10 :0B 0 L0u U0  C0@#$!$$$$% %%%@#$!$$$$% %%%@ތ#$!$$$$% %%%@#$!$$$$% %%%@ #$!$$$$% %%%!#$!$$$$% %%%U>CB>#>/>L> 4>~4>yA>#>7bad>6'b `?*M**T*8bH**?@b*@)q 0&) 0kB& 1F&@$&$&$&2& %&B&01`.&$&.'$'$'2)'21' 29' ;$_ k g#$<_ k $$$$2 %k 2%e 0U#U#U1$HU$TU$`U$lU$xU2U%U%UB/1p.r$$$2+ 23 2;2C2Kl 2Sm2[ 2c 2k<2sFB$@#$1p$$$$2 % 2% B$#$1$$$$2 % 2% B$ %#$1@$$$$2 %; 2%5 B$5e#$1$$$$2 %b 2%\ ;$  ^#$<  $$$$2 % 2% B$ #$10 $$$$2 %"2%BU` N#U#U1 $HU$TU$`U$lU$xU2U %U%UBU #U#U1!$HU$TU$`U$lU$xU2U%U%U0U@!?#U#U1p!$HU$TU$`U$lU$xU2U%U%U0>!8#\#P1!.h.t$.1.$%6E1b`"4K1[4t614.P1*82bo?3b8@4bP)qm)10N :0 0;B%7E#%#t%#h%#\%#P%<$%$%$%>_'8#'#}'#q'1".'.'P2'#2'^ D6t6&a6k6"p6"o6-,,,,Ɣ$Д.ڔ)68nr5t8&5a85k8"p89o80"8## #10#$Д$ڔ6P%p\4K%4%*T%i9*8%8?%bP)O%^)} %)q% 0%0|a#%#a=#$a.a<$a60w%k4Kw%L4w%*Tx%i*8y%:8?z%bP)O%)} %')q% 0%0|a0$}%#a=p$$a.a<$a6%p4 4K%4+%M*{(%M*8%8?%P)O&H } & q& 0&0%$&#%1%.%0|a@%>#aA$a1p%$a.a{?#?bx?!"val ?i!#a@ؘ$a!$a$a-@ >!^,1%.k0|a% ?#aAa e G$a10&$a.a6s $@!_$4K$]4T$*8$?$b*@$*@$*@$[u8&@$bP q$ 10$) 0$ #0%p&$#%1&.%i0|a'?#aA]"a"h$a1P'$a.a6Hh$`$'G4Kh$4Th$*8i$r?j$b*@k$*@l$*@m$Fs8&@n$bP q$ 10$) 0$%0&'$#&1'.$&0|a0(>#aA}%%$a1p($a.a6U ('64K(B4bA(@R(il@(i*K'(=*8(;*?(q*@(*@(i *@(  qt)) 0z),B|a((#aA)(2($a1($a.a; 0|a0)(#aA(($a1p)$a.a 6$69R  4K$ 4T$ *8$ ?$b*@$*@$n*@$8&@ $bP qS$ 10E$) 0X$\802&)N$#D&1*.O&0|aP*?#aA77$a1*$a.aS61#9<B4K#4T#E*8#?#b*@#*@#l*@#?8&@#bP q$ 10#) 0 $6;0]&*$#o&1 +.z&0|ap+>#aA::*$a1+$a.ad6=_A4K4t6h4.PI*1*HF'*889@*?*@bt8@bP)!F=)O=)} =)q= 0;B%F==#%#t%#h%#\%#P%3> $a1p-$a.a=-w* 98 K1.*m83l !6T`ADp4K4t6%4.P*{(bb*8|8?bP)!A)OB)} 8B)qB 0;B%AA#%#t%#h%#\%#P%#%#t%#h%#\%#P%K)} 1K q 2 0 2;B%JK1#%#t%#h%#\%#P%*!S-?*T-4c?*8-?*?-bG@*@-@*@-bA@-&@-*0@-,B q.)10A.Y -<.)U0:.\):0?.Y) 0.ZB L:-#*L#LBP:-Y#1:.B0|a ; ?#a=p;?$a.aCmK o!8>nK x!8>oK !8Ip !8Jq !8Jr !8'6s !8Jt !8R9uK !8*v ! G 8Zw7 !8Xx `! 8Nys !8r!z h!8yU{K !8'| p! 83}۴ !8(~ ! ' 8L !8) !8 ĕ!8P x!8E ʕ!8n !8B۴ Е!8,A !8-7 Օ!89 !8  ߕ!8: !8K !8U  ! k 8[ !8  !8 ۴ !8  (!8I=۴ !8; !8 WK !8I !8<  !8C ! W 8 G !8H !8";7 !88 !8.s '!8 !8|9G 3!8> !8G >!8 !87 I!8lO ! o 8K_ `!8  ! 8K p!8  !8"2s !8_ !8 XG !8: ! ? 8*/ !8rL !8s !8J !8 Hs !8K !89G !8,R  ! 8C Ж!8  (!8K_ !8#  0!8L !8.  8! 8 L  !89  @!8s 2!8 H!8,/ >!8 P!8:G K!8  X!8Vs V!8# `!8[ b!8 h!8? i!8 p!8tV q!8#* x!8 <K y!8 !8Vs !8T !8!s !8|  !8lK !8T  !8VS !8S !8f  !8@ !8t[ !8Z ! 7 8L' З!8D  !8g4o !8e. !8'Mo !8 G 0!8  !8 !8N۴ !8M 8! # 85E !8  !8"Go !8 @!81۴ !8 H!8o !80 P!8(o !82# !8C۴  !8@ !8P"۴ !8 !8yY !8X4 !8'UK !8C X!8Z G $!8 `! 8Bۿ /!8: !8o 2!8 !8 o 6!8k" !8UG :!8" h!89s E!8  p!8+?G Q!87 x!8>  \!8L !8=6۴ k!8=5 !83o p!8- !8[ t!8 !8v: [ {!8[D  !8  !8 [  !8& G !81 ! 7 8\I' !8N !8 7 !8kG !8_BK !8 ; !8jBK !8( !8=۴ !8, !8uB۴ Ę!8, !8=۴ ɘ!8, !8ۿ Θ!81 !8U !8  !8+!/ !80" !8]# !8$ !8#% !8b#&  !8G' (!8H( 0!8I) 8!87J* @!H6?+>H&7,<H@-@H@.>H9/!H90>Hs41@HA2!H A3>HA4!8c95 H!8!A6' !8)7 P! } 8D:8m !8:9 X!8(B:' 0!8:; `!83B<' P!8,= h!8,8> e!8HB?[ !8:@ p! S 8c=AC p!8<B x! 8CCC !8<D !8<E !8<F !8<G !8=H !8 =I ! 9 8j7J) !8:AK ƙ!8WCL ș!8bCM ʙ!8EAN ̙! 8tCO Й!8=P !8CQm !8%=R !8CSm !81=T !8CUm 0!8`>V !8WAWm P!8l>X !8kDYm p!8x>Z !8vD[ !8>\ !8D] !82^ !8D_ К!8>` !8Da !8>b !8Dcm !8>d !8De 0!8>f !8Dg P!862h !8Di' p!  DI4 /V 9 68) ! _ p8u'O ! #8Lu `! =8RJ ! {8W ! +8 ^ `!  o8 ! C 8[3  ! i 8EY  ! 8&%  ! 85 ! <8V# `!  28x" ! ' B8S ! ! M 98AU!= @!8^F! !8+l"= !803"  !8GV#= ! 8|W# ! 8k$$ !  8pg$  ! = 8M$- !8w% ! y r87v%i `! 8i% !8D%i ! S8x% !  e8=,& `! ' 8817O& ! M 85&=  !8O' !8Z6(O  ! J8!( !8 6  ! ~ 8A6 !8O:6u  !8*N6 `!8V6S !8`6 !8(97A ! ~p 8pXp7` !8+w7u  !8&7 !8U7S P!87 `!8W87 !8718 `!8;58u !8"Co8 !8|8S !8"8 @!8e8  ! ~ %828x ! $ 8 +9 !8  9u !8D@G9 @!8/T9S !8DWZ9 !89 ! ~B 8(92 ! $h 89X !8?9u !8y? : !8#:S 0!8! : `!8d: ! ~ 8B: !8_:X !8W':u !8Q: !8:S !8: @!86-; ! . q8A; !  8^= !KPK[-L?Sy]L"x~KW ~KK KG ~K ~K /~Kn ~K~KLW~K8&~KS&~KL~K%,K#J-K.K/K74K6K?.hMv*jb !M, 7~ !M7~ @!M 8~ !M7Xo9~ @!M5:~ !M#:~ @!1;/home/aurel32/debian/co-packages/glibc/glibc-2.9/build-tree/amd64-libc/csu/crtn.S/home/aurel32/debian/co-packages/glibc/glibc-2.9/csuGNU AS 2.19.1U%% : ; I$ > $ > $ >   I : ;  : ;I8 I !I/ : ; : ; I8 &I : ;  : ; ' II : ; '  : ; : ; I8 : ;I : ;  : ;I8  : ;.: ;' : ;I: ;I4: ;I.: ;' I  : ;! "4: ;I#1$41% 1&.: ;' '.: ;' I@ (: ;I ) : ;*4: ;I+.1@ ,1-.1@.41/: ;I 01UX Y1 U2 13.: ;' @4: ;I5: ;I6.: ;' I@7 : ;84: ;I 94: ;I:4: ;I ;1X Y< = U>1X Y?1RUX Y@ A B1UX YC1RUX YD.? : ;' @E1UX YF41 G4: ; I H4: ;II4: ;IJ!I/K4: ; I? < L4: ;I? < M4: ;I?  U%h /home/aurel32/debian/co-packages/glibc/glibc-2.9/build-tree/amd64-libc/csucrti.S O Ku=/0K JK _$0 cpyamf/usr/lib/gcc/x86_64-linux-gnu/4.3.3/include/usr/include/bits/usr/include/usr/local/include/python2.3util.cstddef.htypes.hstdio.hlibio.hobject.hmethodobject.hstructmember.hdescrobject.hintobject.hfloatobject.hstringobject.htupleobject.hlistobject.hclassobject.hpystate.htraceback.hframeobject.hcompile.hunicodeobject.hboolobject.hlongobject.hdictobject.hpyerrors.h O t C+f C CG?YMKlfltmfmtsf s ttf tt;gY0X=u"H1&!rWft$<KKKKKK=u/uttxY7wY;=u.KX uJ X m$Y;=t.KX tJ X ~$Y;=m.KXmJ Xm$Y;=l.KXlJ X $ %8@g ֱ;=hF\8@/#,].fm<Krj# L!;JE<.  XwA&q'$8 828F$H>%Bo YWzX փN<2 -V JJfJXG+q1xR;Y;Y[YkN*\%h@vS r:p+  LL\HPtb*F$%W~+O8X փG f(AZwU=v/%N.p2%If2xyX3Jf.V  %\|-X< J J J   %.G)rJX,XJ v< J . .X~ X.%~X]8^8}0 XsJ Xf. .Y X <t/X{+tq Xv< < . .s. X wJ B8tHt89f`tnXX Xv< <f    fN\%X.s;~0`tnXX Xv< <f    fN\%X.s;~0`tnXX Xv< <f    fN\%X.s;}06xt6xX< v< <f "   fN\%X.s>~06xt6xX< v< <f    fN\%X.s>~86xt6xX< v< <f "   fN\%X.s>~06xt6xX< v< <f    fN\%X.s>8 tK X= wJ w" XN.d<<." v< <fgXJK5JV<* .e'X jf.f J*Xh. .eZwU=v%a]~%t'~9*%{&.Z<&< f<ZwU=v%a]~" v< <fiXJK5JV<* .e'X jf.h J*Xh .er%t*~>%~z-  J J  t tm< J t. J %~.G[~<>8~8|0XoJ.X   ttwX t Xv< Jf1}%~w J  t t v< Jf = }<t,u#1~8}*>,@*~>*.Hh  *&3a#<d%ȟ}<Jq  <wW;=/KXg  y <wT =sY;=gE`tnXX Xv< <f    fN\%X.s;q0<r<Xf  Ju< X f Y w XvZM/ Zw=/ .=}& u< u J˻J%}fZzzf=LL Z[,Lh,}ttss~tsshtu ZMH=~,tuwU=v/(~XHst~tu t  Zw= .ZM/ ZM,Lh2~Jr0Y}<(tstsst tssts#t*-}* >-/--/--- -/-i---0 0-/ --&-/ -- ---0 0-~-*Jw<pJ< <u J   f[r.%\.' %ps@3.-  fet%aH@!._X/f^ # \!^t!X X^JK!0= J.\!t^JK! J,\ JJ]"X \J" MM\JY# \N!^P"~ Y k)*  t t t v< J.fet%].3J . $ç;=g!t Jt< Jt< fNJwt!X(w+[O$) 9Xpt<!ֻ,t]ZwU=v%ivLt0@%d~-.nt!  $ XZwU=v%E]?ct>@*%)f<Jf<f!=> "H>=|<J< X X!=>J  twX Zw=J$"/.  Xv< Xk @tJ Y X XH%f%bfQ',Sju;=0Dxt. %qn'|8 <u.h<#< Jw.&Jwt < (XfJ.  tbtȣź< r<<wJ<  w<XXwt < v< J!.1e.tktȣ! gXJf Xv< <fXfJg'X;/.W(t(3'~1X<.tXJJg& wX tX<& Y tktt|f hXJf Xv< <fZfJ%;/"f!Yt$= Zt$X Zfȃ$ M~'JvJZfK% NuZ9${. < t  eXX =9!Y>/JQ<%%wU=v(i$ryJ-%JY4~XJ~fYiiv~KfKhny ZwU=v%Rt=WY;=g`<X`  .J+n8%i#3KA7Lf 3. =Lop <Oo3X .;=gx# .s. .J}tt}tKg vt t% ȒlJ <v$%$w"8xh>;ugt{t{tt{t{tt{t{tt{t{tt{t{tt{t{tt{t{tt{truu,tntutou3ADsvu=u6ADsswru>:I3ADsswru>:_3AD tBt t   t  ֒w0 tA70w0P($L ZwU=v7.*!t_!.6!I6.I.gJn/6I6.I.g4YA7Lf]fU+.U<%(%]c' ,J4* KK4PKta@j*4* ȃ;=g.~.  t~XJ~0nt~ffff v< < f 6 fX|} v< <ft{Jff{f {f |fvt f| <}t.| <}t.}  tXY;=k.rXY;=2;=ng/  Xv t Xv t Xv tZ v< < f 6 fzX<|J tf v< < f 6 fzX<|J tf v< < f 6 f}~t,tttvtvtvtytY;h*f @})t /2202*-f2%E"|'%8tHt8zXA8tHt8zX?8tHt8zX?8tHt8:XJet{X@7A  J$teX t t t XvX J.H%X=䑃> -r2L;=0uWK˩t{J;=0uWK{{^3LJv 3.=L3ol Np3=sY;=/K(4KJv 3.=K3ol Np4=sY;=/L(3=~Jh]NXS`f1Ntxp  tvt 2;=g~/J ȼ;<XgJ"$> ZwU=v%Wt5~JhKX4@Ktv \X /t58J%5#;=gI$> ZwU=v%Wt6~Jh]KX= r4Kt*s.6J=Jn>%5#ڃ;=gR# vtJwt X-=R -R ZKL .Zw= .Zzz=/ ZM .ZZM/ ZZM/ Zw=/  ~rtvtstsstsst tsstsstsst%~J+~.-K!), A=R  D*--=R  C*/-0s--- --0-- -----0-- ---,-̃;=yڃ;=H($> ZwU=v%Wt6~JhJX5@Jtv \X /t68I%6#;=gH$> ZwU=v%Wt7~Jh]JX= r5Jt*s.7J=Hn>%7#ڃ;=g# v< ff;u<  u< u JCJ%bfKJY;=Ѽ=Jٿ֓rWK" "sY;Y)Y;ֿX@=ݾfS@N*\ Jڃ;=g*^z)S*eX]>N*\f]=eX<d8;=gyڃ;=g#eJ*U#x»)*MUX]@N*\+f]=T*FUX+@Th.+8;=gy(ڃ;=g#U- *>;=0vKה0{<;=0vK{0~.~AD $JQ0$JL ,BEL C(D0$jJL $jJL $jJL $ZBHA $PRBHA $ZBHA $RBHA $pzBAD 4BHE A(A04BHE A(A0$pAAG0$pLJL0$JQ0PJG JG $jJL <`BBB B(A0D8Gp$`FJQ0$AAG ,BID D0$`AAG <@BBB B(A0A8D@$@JL 40BIB A(D00AG0,AqAG0$pNJP@$|JN $@rAAG APA$JQ0$JL0$JQ0$JQ@$kJL $ _AAG $.JQP$.JQP$JMLP,gJMQP4PBHB D(A0$PJN $PJN $@JN $@kBDD $JO $pBCA ,ppJMQ@<  BDB B(A0A8D`$`/JQ@fDnD$p{JO ${JO $pJO @ JG $@!BDD $`$MBDD <'BEB B(A0A8DP$6BDD $9MBDD $=_JQ`$`AJL@$EyJMLP$JJMLP$P JMLP$ VRG $VRG $pWWG0$@XWG0< YBEB B(D0A8DP__pyx_kp_NegInf__pyx_kp___iter____pyx_vtabptr_6cpyamf_4util_IndexedCollection__pyx_vtabptr_6cpyamf_4util_cIndexedMap__pyx_doc_6cpyamf_4util_18BufferedByteStream_read_utf8_stringetypePy_tracefunc_unused2_fileno__pyx_tp_as_buffer_IndexedMap__pyx_f_6cpyamf_4util_19cBufferedByteStream_truncate__pyx_k_remaining__pyx_init_filenames__pyx_kp___richcmp____pyx_doc_6cpyamf_4util_18BufferedByteStream_write_24bit_uint__Pyx_PyInt_AsLong__pyx_v_nbsq_ass_slice__pyx_pf_6cpyamf_4util_18BufferedByteStream___len__tp_getattrPyExc_TypeError__pyx_pf_6cpyamf_4util_11cIndexedMap___cinit__sq_itemco_argcountnb_add__pyx_pf_6cpyamf_4util_18BufferedByteStream_read_24bit_uint__pyx_f_6cpyamf_4util_19cBufferedByteStream_has_available__pyx_pf_6cpyamf_4util_18BufferedByteStream_read_char__pyx_pf_6cpyamf_4util_18BufferedByteStream_read_utf8_stringob_refcnt__pyx_filenamesPyTuple_Typesq_ass_item__pyx_f_6cpyamf_4util_19cBufferedByteStream_read_uchargetsegcountprocPyList_Type__pyx_kp_read_ulong__Pyx_InitCachedBuiltinssq_inplace_repeat__pyx_pf_6cpyamf_4util_18cIndexedCollection___dealloc__cl_setattr__pyx_v_opnb_lshift__pyx_L1_error__pyx_pf_6cpyamf_4util_18BufferedByteStream_write_24bit_uintsq_inplace_concattp_is_gcco_firstlineno_shortbufnb_powercl_getattr__pyx_kp_pos__pyx_vtable_6cpyamf_4util_IndexedMapvtableob_sstatesq_repeat__pyx_obj_6cpyamf_4util_cIndexedMapcurexc_value__pyx_pf_6cpyamf_4util_18BufferedByteStream_read_ulong__pyx_kp_exceptionssq_concat__pyx_pf_6cpyamf_4util_18BufferedByteStream_read__pyx_f_6cpyamf_4util_19cBufferedByteStream_write_floattp_itemsize__pyx_kp_OverflowError__pyx_vtable_6cpyamf_4util_BufferedByteStreaminitproc__pyx_tp_as_mapping_IndexedMapPyString_Type__pyx_ptype_6cpyamf_4util_cIndexedCollectionin_classcodec_search_cachePyGetSetDef__pyx_opt_args_6cpyamf_4util_19cBufferedByteStream_seek__pyx_doc_6cpyamf_4util_18BufferedByteStream_read_uchar__pyx_v_equaltp_bases__pyx_pf_6cpyamf_4util_18BufferedByteStream_peek__off_t__pyx_pf_6cpyamf_4util_18BufferedByteStream_seekcl_nameis_unicode__pyx_pf_6cpyamf_4util_17IndexedCollection_8use_hash___get____pyx_kp_write_uchar__pyx_pf_6cpyamf_4util_18BufferedByteStream_write_ulong__pyx_arg_ref__pyx_L10__pyx_L11__pyx_L12__pyx_L13__Pyx_PyIndex_AsSsize_t_lockPyFloat_Type__pyx_ptype_6cpyamf_4util_cBufferedByteStream__pyx_f_6cpyamf_4util_19cBufferedByteStream_writesetattrofunc__pyx_setprop_6cpyamf_4util_17IndexedCollection_use_hashf_valuestacktp_dealloc__pyx_k_read_ucharnb_long_typeobjectnb_floor_divide__pyx_kp_3__pyx_kp_4__pyx_kp_5__pyx_kp_6__pyx_kp_7__pyx_kp_8__pyx_kp_9bf_getwritebuffernb_inplace_lshift__pyx_pf_6cpyamf_4util_18BufferedByteStream_write_short__pyx_tp_as_number_BufferedByteStreaminvalid_keyword_type__pyx_f_6cpyamf_4util_19cBufferedByteStream_write_char__Pyx_PyInt_AsChar__pyx_pf_6cpyamf_4util_18BufferedByteStream_consumeempty_stringf_stacktop__pyx_kp___getitem____pyx_doc_6cpyamf_4util_18BufferedByteStream_getvalue__pyx_kp_x__pyx_v_6cpyamf_4util_system_posinf__pyx_k___len____pyx_pf_6cpyamf_4util_18cIndexedCollection___richcmp____pyx_k_ReferenceError__pyx_pf_6cpyamf_4util_18BufferedByteStream___add____pyx_kp_seek__pyx_kp_read_float__pyx_kp_MemoryError__pyx_f_6cpyamf_4util_18cIndexedCollection_appendvaluestp_richcompare__pyx_k_seek__pyx_k_ref_IO_write_endPyThreadStatenb_remaindervisitproc__pyx_kp___copy____pyx_k_getReferenceTo__pyx_L4_argument_unpacking_done_Py_TrueStructis_identifiernb_inplace_multiplyob_sval__pyx_k_value__pyx_vtable_6cpyamf_4util_cBufferedByteStreamnum_max__pyx_f_6cpyamf_4util_19cBufferedByteStream_read_24bit_inttp_comparef_stacksize__pyx_kp_flushPyMemberDef__pyx_k_objinterninterpob_typetp_freetick_counter__pyx_getprop_6cpyamf_4util_18BufferedByteStream_endian__pyx_type_6cpyamf_4util_IndexedCollection__pyx_tp_as_mapping_IndexedCollection__pyx_int_neg_1getter__pyx_tp_as_buffer_cBufferedByteStream__pyx_k_append__pyx_mdoc__pyx_f_6cpyamf_4util_19cBufferedByteStream_seek__pyx_kp_mode__pyx_builtin_IOError__pyx_obj_6cpyamf_4util_BufferedByteStream__pyx_L5_argtuple_error__pyx_k_write_longco_nlocals__pyx_pf_6cpyamf_4util_18BufferedByteStream_getvalue__Pyx_PyInt_AsUnsignedChar__pyx_vtabptr_6cpyamf_4util_cIndexedCollection__pyx_kp_idxnb_and__pyx_k_read_long__pyx_v_cur_pos__pyx_type_6cpyamf_4util_cIndexedMap__pyx_k_mode__pyx_kp_read_short__pyx_tp_new_6cpyamf_4util_cIndexedMaptp_callasync_exc__pyx_arg_xPyExc_RuntimeErrorgilstate_counterf_localsplus__pyx_pf_6cpyamf_4util_17IndexedCollection_10exceptions___set____pyx_vtabptr_6cpyamf_4util_IndexedMapob_item__pyx_methods_6cpyamf_4util_cIndexedMap__pyx_getsets_6cpyamf_4util_IndexedMaptp_str__pyx_k_getvalue__pyx_pf_6cpyamf_4util_18BufferedByteStream_tellco_filename__pyx_v_ref__Pyx_PyObject_IsTrueternaryfunc__pyx_v_6cpyamf_4util_platform_neginfPyTypeObject__pyx_k_consumePyTraceBack_Type__pyx_builtin_MemoryError__pyx_doc_6cpyamf_4util_18BufferedByteStream_write_ulong__pyx_ptype_6cpyamf_4util_IndexedCollection__pyx_pf_6cpyamf_4util_18cIndexedCollection___getitem____pyx_v_SYSTEM_ENDIAN__pyx_k_write_ushort__pyx_k___add__sq_contains__pyx_doc_6cpyamf_4util_18BufferedByteStream_seek__pyx_v_6cpyamf_4util_system_neginf_chainf_exc_valuetp_setattr__pyx_string_tab__pyx_kp_self__pyx_f_6cpyamf_4util_19cBufferedByteStream_complain_if_closedrichcmpfuncunsigned char__Pyx_PyInt_AsShortf_nlocalsmp_ass_subscript__pyx_v_objbf_getreadbuffer_IO_lock_t__pyx_k_at_eof__pyx_kp_read_ushort__pyx_pf_6cpyamf_4util_18BufferedByteStream_read_ushort__pyx_k_read_double__pyx_v_6cpyamf_4util_platform_nan__pyx_pf_6cpyamf_4util_18BufferedByteStream_write_uchartp_dictoffset__pyx_f_6cpyamf_4util_18cIndexedCollection_getReferenceTo__pyx_f_6cpyamf_4util_is_broken_float__pyx_obj_6cpyamf_4util_cBufferedByteStream__pyx_k_idx__pyx_k_close__pyx_pf_6cpyamf_4util_18BufferedByteStream_read_long__pyx_pf_6cpyamf_4util_10IndexedMap_appendPyNumberMethods_Py_ZeroStruct__pyx_pf_6cpyamf_4util_18BufferedByteStream_read_24bit_intPyMethodDef__pyx_tp_as_mapping_cIndexedMap__pyx_f_6cpyamf_4util_19cBufferedByteStream_read_utf8_stringgetwritebufferproc__pyx_v_mapped_obj__pyx_f_6cpyamf_4util_19cBufferedByteStream_write_ushort__pyx_kp_valuefunction_name__pyx_vtable_6cpyamf_4util_IndexedCollection__pyx_doc_6cpyamf_4util_18BufferedByteStream_at_eofmp_subscript__pyx_doc_6cpyamf_4util_18BufferedByteStream_read_longtp_clear__pyx_empty_tuple__pyx_f_6cpyamf_4util_19cBufferedByteStream_getvalue__pyx_1__pyx_f_6cpyamf_4util_19cBufferedByteStream_write_24bit_intarg_passed_twicein_weakreflist__pyx_kp_append__pyx_k_ValueError__pyx_k_MemoryError__pyx_doc_6cpyamf_4util_18BufferedByteStream_write_shortnum_min__pyx_doc_6cpyamf_4util_18BufferedByteStream_readuse_tracing__pyx_b__pyx_v_6cpyamf_4util_pyamf_NaN__pyx_f__pyx_tp_traverse_6cpyamf_4util_cIndexedMap__pyx_m__pyx_n__pyx_r__pyx_kp_dataco_freevars__pyx_doc_6cpyamf_4util_18BufferedByteStream_write_float__pyx_v_buftp_init__pyx_getsets_6cpyamf_4util_IndexedCollectionobjobjargprocob_size__pyx_tp_as_buffer_cIndexedCollection__pyx_kp_write_doubletp_dict_IO_write_ptrtp_as_mapping__pyx_kp_write_ulongsetattrfunc__pyx_k___copy____pyx_f_6cpyamf_4util_19cBufferedByteStream_pack_int__pyx_v_6cpyamf_4util_system_nan__pyx_k_write_shortrefs__pyx_k_IOError__pyx_sq_item_6cpyamf_4util_cIndexedCollectionfirst_kw_arg__pyx_v_cpy__pyx_doc_6cpyamf_4util_18BufferedByteStream_write_24bit_intPyExc_NotImplementedErrorbinaryfunc__pyx_kp_read_double__pyx_k_read_ulong__pyx_pf_6cpyamf_4util_18BufferedByteStream_write_char__pyx_kp_NotImplementedError__pyx_kp_mapped_obj__pyx_pf_6cpyamf_4util_18BufferedByteStream_closeob_ival__pyx_doc_6cpyamf_4util_18BufferedByteStream_write_ushort__pyx_k_idtmp_value__pyx_tp_new_6cpyamf_4util_BufferedByteStreamcodec_error_registry__pyx_kp___add____pyx_k_NegInfkwds2__pyx_kp_36__pyx_f_6cpyamf_4util_19cBufferedByteStream_write_longcpyamf/util.cgetiterfunc__pyx_f_6cpyamf_4util_get_native_endian__pyx_type_6cpyamf_4util_cIndexedCollection__pyx_v_datanb_nonzero__pyx_pf_6cpyamf_4util_17IndexedCollection_append__pyx_pf_6cpyamf_4util_18BufferedByteStream_read_float__pyx_k_exceptionsintintargfunccodec_search_path__pyx_kp_at_eofdescrsetfunc__pyx_f_6cpyamf_4util_19cBufferedByteStream_pack_uinttmp_type__pyx_k_TypeError__Pyx_Raisef_lastidescrgetfuncunused__Pyx_CheckKeywordStrings__pyx_pf_6cpyamf_4util_18cIndexedCollection___iter____pyx_kp___dealloc__nb_octnb_inplace_add__pyx_doc_6cpyamf_4util_18BufferedByteStream_appendkw_name__pyx_k___getitem____pyx_tp_as_buffer_IndexedCollectionco_code__pyx_pf_6cpyamf_4util_18BufferedByteStream_remaining__pyx_k_self_IO_save_base__pyx_kp_ref__pyx_doc_6cpyamf_4util_18BufferedByteStream_read_charPyUnicode_Typereprfunc__Pyx_ErrRestore__pyx_tp_as_buffer_cIndexedMap__pyx_setprop_6cpyamf_4util_10IndexedMap_exceptionsmapped__pyx_kp_val__Pyx_PyInt_AsIntcurexc_traceback__pyx_builtin_OverflowError__pyx_pf_6cpyamf_4util_10IndexedMap_clear__pad2__pyx_kp_write_floatfrom_listpy_funcnameexact__pyx_builtin_ValueError__pyx_type_6cpyamf_4util_IndexedMapPyTryBlock__pyx_vtabstruct_6cpyamf_4util_BufferedByteStreambf_getcharbuffer__pyx_doc_6cpyamf_4util_18BufferedByteStream_write_char__pyx_tp_new_6cpyamf_4util_IndexedMap__Pyx_PyInt_AsUnsignedLong__pyx_vtabstruct_6cpyamf_4util_cIndexedCollection__pyx_v_new_len__pyx_doc_6cpyamf_4util_18BufferedByteStream_truncate__pyx_pf_6cpyamf_4util_10IndexedMap_10exceptions___set__PyExc_NameError__pyx_pf_6cpyamf_4util_10IndexedMap_getMappedByReference__pyx_obj_6cpyamf_4util_IndexedMappy_srcfilenb_divide__pyx_lineno__pyx_f_6cpyamf_4util_19cBufferedByteStream_read_24bit_uint_nextPyObjectnb_xornb_negative__pyx_optional_args__pyx_tp_as_sequence_cIndexedCollection__pyx_v_test__pyx_pf_6cpyamf_4util_17IndexedCollection_10exceptions___get____pyx_v_one__pyx_f_6cpyamf_4util_complete_import__pyx_v_endian__pyx_v_new__pyx_tp_as_number_IndexedMap__pyx_doc_6cpyamf_4util_18BufferedByteStream_write__Pyx_PyNumber_Int__pyx_f_6cpyamf_4util_18cIndexedCollection_getByReference__pyx_kp___init____pyx_vtable_6cpyamf_4util_cIndexedCollection__pyx_pf_6cpyamf_4util_10IndexedMap_getReferenceToprintfuncco_flags__pyx_v_size__pyx_kp_read__pyx_ptype_6cpyamf_4util_cIndexedMap__pyx_k_val__pyx_methods_6cpyamf_4util_IndexedCollection__pyx_pf_6cpyamf_4util_18BufferedByteStream___init____pyx_v_6cpyamf_4util_NaN__pyx_f_6cpyamf_4util_19cBufferedByteStream_append__pyx_v_6cpyamf_4util_pyamf_PosInf__pyx_v_use_hash__pyx_v_num_bytesco_name__pyx_kp_write__pyx_clineno__pyx_kp_29PyBufferProcsf_ncellsco_stacksizeml_flagstp_new__pyx_kp___str__b_handler__pyx_f_6cpyamf_4util_19cBufferedByteStream_write_short__pyx_module_is_main_cpyamf__util__pyx_f_6cpyamf_4util_19cBufferedByteStream_read_longf_exc_tracebackmore_or_less__pyx_v_pyamf__pyx_kp___main____pyx_getsets_6cpyamf_4util_BufferedByteStreamnum_expectednb_inplace_true_divide__pyx_pf_6cpyamf_4util_17IndexedCollection___init__nb_inplace_divide__pyx_k_RuntimeErrordestructorPyCFunction__pyx_tp_as_number_cIndexedCollection__pyx_arg_size__pyx_type_6cpyamf_4util_cBufferedByteStream__pyx_f_6cpyamf_4util_19cBufferedByteStream_closef_trace__pyx_vtabstruct_6cpyamf_4util_cIndexedMap_sbuf__pyx_kp_32_IO_save_end__pyx_k_write_double__pyx_kp_37__pyx_kp_38__pyx_kp_39__pyx_v_6cpyamf_4util_SYSTEM_ENDIANtp_del__pyx_L8_break__pyx_f_6cpyamf_4util_18cIndexedCollection__clearstdouttp_name__pyx_pf_6cpyamf_4util_18BufferedByteStream_write_doubleclosure__pyx_v_encoded_string__pyx_kp_NaN__pyx_pf_6cpyamf_4util_18cIndexedCollection___cinit____Pyx_PyInt_AsUnsignedShort__Pyx_SetVtablec_profilefunc_PyThreadState_Currenttp_as_sequence__pyx_kp_maptmp_tbtp_as_buffer__pyx_v_6cpyamf_4util_NegInfnb_inplace_and__pyx_f_6cpyamf_4util_11cIndexedMap_getMappedByReference__pyx_k_read_ushort__pyx_f_6cpyamf_4util_19cBufferedByteStream_at_eof__pyx_pf_6cpyamf_4util_17IndexedCollection_getByReference__pyx_filename__pyx_v_valueshort unsigned intsysdict__pyx_tp_as_mapping_BufferedByteStream__import____pyx_v_6cpyamf_4util_platform_posinff_blockstack__pyx_L0__pyx_kp_obj__pyx_L3__pyx_L4__pyx_L5__pyx_L6__pyx_L7__pyx_L8__pyx_L9__pyx_f_6cpyamf_4util_19cBufferedByteStream_write_24bit_uinttp_alloc__pyx_kp_RuntimeError__pyx_pf_6cpyamf_4util_18BufferedByteStream_write_longin_dicttstate_head__pyx_kp_ValueError__pyx_v_pos__pyx_pf_6cpyamf_4util_10IndexedMap_8use_hash___set____off64_t__pyx_v_6cpyamf_4util_pyamf_ReferenceErrorcoercion__pyx_kp_id_IO_read_base__pyx_f_6cpyamf_4util_build_platform_exceptional_floats__pyx_obj_6cpyamf_4util_cIndexedCollection__pyx_kp_54__pyx_k_write_uchar__pyx_kp_59_IO_buf_endf_tstate__pyx_v_6cpyamf_4util_pyamf_NegInf__pyx_f_6cpyamf_4util_19cBufferedByteStream_read_floatinitutil__pyx_pf_6cpyamf_4util_17IndexedCollection_clear__pyx_methods_6cpyamf_4util_BufferedByteStreamtp_getattroallocfunc__pyx_doc_6cpyamf_4util_18BufferedByteStream_read_24bit_uint__pyx_pf_6cpyamf_4util_10IndexedMap___init__c_traceobj__pyx_pyargnames__pyx_k_NaN__pyx_f_6cpyamf_4util_11cIndexedMap_append__pyx_k_readtp_methods__pyx_v_ret_IO_write_basemodule__pyx_vtabstruct_6cpyamf_4util_IndexedMaptp_mro__pyx_kp_other__pyx_k_map__pyx_k_24global_dictintintobjargproc__pyx_doc_6cpyamf_4util_18BufferedByteStream___init____pyx_tp_clear_6cpyamf_4util_cIndexedMap__pyx_f_6cpyamf_4util_19cBufferedByteStream_remaining__pyx_v_done__pyx_kp_util__pyx_pf_6cpyamf_4util_18BufferedByteStream_write_float__pyx_doc_6cpyamf_4util_18BufferedByteStream_write_doublef_code__pyx_doc_6cpyamf_4util_18BufferedByteStream_consumenb_or__pyx_f_6cpyamf_4util_11cIndexedMap_map__pyx_int_4294967295L__pyx_k_utilunaryfunc__pyx_v_current_size_IO_marker__pyx_args__pyx_pf_6cpyamf_4util_18BufferedByteStream_6endian___set____pyx_tp_dealloc_6cpyamf_4util_cIndexedMap__pyx_methods__pyx_k_13nb_floatdlopenflagsPyExc_SystemError__pyx_k_19__pyx_doc_6cpyamf_4util_18BufferedByteStream_read_double__pyx_k_41__pyx_f_6cpyamf_4util_19cBufferedByteStream_readtraverseproc__pyx_kp_17inquirynb_invertf_lineno__pyx_doc_6cpyamf_4util_18BufferedByteStream_write_long__pyx_kp_read_charml_doc__pyx_k_32__Pyx_PyObject_Appendml_name__pyx_tp_clear_6cpyamf_4util_cIndexedCollection__pyx_getprop_6cpyamf_4util_17IndexedCollection_exceptionsPyClass_Type__pyx_basenum_pos_args__Pyx_RaiseArgtupleInvalidlong doublekw_args__pyx_f_6cpyamf_4util_19cBufferedByteStream_write_utf8_string__pyx_k___main____pyx_kp_28tp_as_number__pyx_k_read_short__pyx_k_22__pyx_k_23bf_getsegcount__pyx_pf_6cpyamf_4util_10IndexedMap_10exceptions___get____pyx_kp_remaining__pyx_getprop_6cpyamf_4util_10IndexedMap_use_hashtp_weaklistoffset__pyx_k_29__pyx_tp_as_number_cBufferedByteStream__pyx_k_PosInfPyFrameObjectml_meth__pyx_kp_write_char__pyx_kp_op__pyx_k_read_float__pyx_kp___len____pyx_kp_30__pyx_kp_31tp_doc__pyx_kp_34__pyx_kp_35GNU C 4.3.3__pyx_k_read_chargetattrofuncnewfunc__pyx_v_minint__pyx_pf_6cpyamf_4util_18BufferedByteStream_6endian___get____pyx_pf_6cpyamf_4util_19cBufferedByteStream___dealloc____pyx_tp_as_number_cIndexedMap__pyx_kp_peek__Pyx_AddTraceback__pyx_k___iter____pyx_getprop_6cpyamf_4util_10IndexedMap_exceptionsPySequenceMethods__pyx_ptype_6cpyamf_4util_BufferedByteStream__pyx_pf_6cpyamf_4util_18cIndexedCollection___len____pyx_kp_40__pyx_kp_41__pyx_kp_42__pyx_kp_43__pyx_kp_44__pyx_kp_45__pyx_kp_46__pyx_kp_47__pyx_kp_48__pyx_kp_49tp_weaklist__pyx_k_peek_IO_buf_base__pyx_k_34__pyx_f_6cpyamf_4util_19cBufferedByteStream_read_char__pyx_k_37__pyx_k_39nb_positive__pyx_doc_6cpyamf_4util_18BufferedByteStream_write_utf8_stringhashfuncgetattrfunc_IO_read_end__pyx_getprop_6cpyamf_4util_17IndexedCollection_use_hash__pyx_kp_50__pyx_kp_51__pyx_kp_52__pyx_kp_53__pyx_v_idx__pyx_kp_55__pyx_kp_56__pyx_kp_57__pyx_kp_58py_globals__pyx_k_10__pyx_k_11__pyx_k_12__Pyx_InitGlobals__pyx_k_14__pyx_k_15__pyx_k_16__pyx_k_17__pyx_k_18__pyx_f_6cpyamf_4util_19cBufferedByteStream_read_ushort__pyx_tp_as_sequence_IndexedCollection__pyx_tp_as_number_IndexedCollection_IO_FILE__pyx_vtabptr_6cpyamf_4util_cBufferedByteStream__pyx_t_1__pyx_t_2__pyx_t_3__pyx_t_4__pyx_t_5__pyx_t_6__pyx_t_7__pyx_tp_as_sequence_BufferedByteStream__pyx_v_old_other_pos__pyx_kp_getReferenceTocurexc_type__pyx_k_20__pyx_k_21__pyx_tp_new_6cpyamf_4util_cIndexedCollection__pyx_cfilenmtp_hash__pyx_k_25__pyx_k_26__pyx_k_27__pyx_k_28__pyx_kp_tell__pyx_k_42__pyx_k_45nb_hex__pyx_k_50__pyx_v_otherob_shashempty_dict__pyx_methods_6cpyamf_4util_cBufferedByteStream__Pyx_RaiseDoubleKeywordsError__pyx_f_6cpyamf_4util_19cBufferedByteStream_peek__pyx_k_tell__pyx_k_opc_tracefunc__pyx_k_30__pyx_k_31func_name__pyx_k_33f_nfreevars__pyx_k_35__pyx_k_36__pyx_k_38PyIntObjectpy_frame__pad1__pad3__pad4__pad5__pyx_methods_6cpyamf_4util_IndexedMap__pyx_f_6cpyamf_4util_19cBufferedByteStream_write_uchar__pyx_k_5py_code__pyx_tp_as_sequence_cIndexedMap__pyx_k_40_markers__pyx_k_43__pyx_k_44setter__pyx_k_46__pyx_k_47__pyx_k_48__pyx_k_49__Pyx_PyInt_AsUnsignedInt__pyx_k_dataf_back__pyx_kp_use_hash__pyx_kp_consume__pyx_v_result__pyx_vtab__pyx_tp_new_6cpyamf_4util_cBufferedByteStreamtp_memberstp_traversemp_length__pyx_kp_PosInf__pyx_k_51__pyx_k_52__pyx_k_53__pyx_k_54__pyx_k_55__pyx_k_56__pyx_k_57__pyx_k_58__pyx_k_59__pyx_pf_6cpyamf_4util_18BufferedByteStream_read_short__pyx_ptype_6cpyamf_4util_IndexedMapf_exc_type__pyx_k_xnb_inplace_xor__pyx_f_6cpyamf_4util_19cBufferedByteStream_tell__pyx_k_flushtp_subclasses__pyx_pf_6cpyamf_4util_19cBufferedByteStream___cinit__nb_inplace_power__pyx_doc_6cpyamf_4util_18BufferedByteStream_peek__pyx_tp_dealloc_6cpyamf_4util_cBufferedByteStream__pyx_v_modeco_names__pyx_doc_6cpyamf_4util_18BufferedByteStream_read_ulong__pyx_pf_6cpyamf_4util_17IndexedCollection_getReferenceTo__pyx_f_6cpyamf_4util_18cIndexedCollection__reftp_setattro__pyx_kp_buffreefunc__pyx_k_pos__pyx_f_6cpyamf_4util_18cIndexedCollection_clearnb_multiply__pyx_kp_TypeErrornum_foundnb_true_divide__pyx_doc_6cpyamf_4util_18BufferedByteStream_read_24bit_inttp_getsetf_locals__pyx_builtin_TypeErrorPyLong_Type__pyx_k_write_ulong__pyx_pf_6cpyamf_4util_18BufferedByteStream_write_ushort__pyx_vtabptr_6cpyamf_4util_BufferedByteStream__pyx_builtin_id__pyx_pf_6cpyamf_4util_10IndexedMap_8use_hash___get__tp_iternextsq_length__pyx_kp_read_uchar__pyx_f_6cpyamf_4util_is_big_endian__pyx_kp_truncategetreadbufferprocinvalid_keywordtp_descr_get__pyx_k_OverflowErrorPyClassObjecttp_iter__pyx_v_bytes__pyx_f_6cpyamf_4util_19cBufferedByteStream_read_ulongnb_inplace_floor_divide__pyx_builtin_NotImplementedErrorkwdict__pyx_kp_write_shortPyExc_OverflowError__pyx_builtin_RuntimeError__pyx_doc_6cpyamf_4util_18BufferedByteStream_tellgetcharbufferproctp_basenb_rshift__pyx_int_0__pyx_int_1__pyx_int_2__pyx_pf_6cpyamf_4util_10IndexedMap_mapco_constsf_globals__pyx_pf_6cpyamf_4util_18BufferedByteStream___str____pyx_pf_6cpyamf_4util_17IndexedCollection_8use_hash___set____pyx_f_6cpyamf_4util_swap_bytestp_printlong long unsigned intrecursion_depth__pyx_v_self__pyx_k_3__pyx_k_4_cur_column__pyx_k_6__pyx_k_7__pyx_k_8__pyx_k_9__pyx_kp_ReferenceError__pyx_setprop_6cpyamf_4util_17IndexedCollection_exceptions__pyx_kp_write_ushortPyDict_Typenb_inplace_remainder__pyx_pf_6cpyamf_4util_18BufferedByteStream_flush__pyx_k_writeempty_list__pyx_doc_6cpyamf_4util_18BufferedByteStream_close__pyx_k_buf__pyx_setprop_6cpyamf_4util_10IndexedMap_use_hash__pyx_f_6cpyamf_4util_19cBufferedByteStream_consume__pyx_kp_size_object__pyx_f_6cpyamf_4util_19cBufferedByteStream__increase_buffer__pyx_v_6cpyamf_4util_PosInfPyCodeObject__pyx_k___dealloc____pyx_tp_as_sequence_cBufferedByteStream__pyx_v_6cpyamf_4util_float_brokenkw_allowednb_absolute__pyx_pf_6cpyamf_4util_10IndexedMap_getByReference_IO_backup_base__pyx_k_sizef_restricted_IO_read_ptrcl_dict__pyx_f_6cpyamf_4util_18cIndexedCollection__increase_size__pyx_tp_traverse_6cpyamf_4util_cIndexedCollection__pyx_kp_read_long__pyx_L3_error__pyx_pf_6cpyamf_4util_18BufferedByteStream_read_uchar__pyx_doc_6cpyamf_4util_18BufferedByteStream_read_float__pyx_vtabstruct_6cpyamf_4util_IndexedCollection__pyx_kwdsf_iblocknb_inplace_or__pyx_vtabstruct_6cpyamf_4util_cBufferedByteStream__pyx_kp_close__pyx_pf_6cpyamf_4util_18BufferedByteStream_write_24bit_intstdin__pyx_pf_6cpyamf_4util_18BufferedByteStream_write_utf8_string__pyx_tp_new_6cpyamf_4util_IndexedCollectionob_fval__pyx_setprop_6cpyamf_4util_18BufferedByteStream_endiantp_repr__pyx_tp_as_sequence_IndexedMaptp_cachePy_ssize_traise_errorpycobj_old_offsetsq_slice__pyx_f_6cpyamf_4util_19cBufferedByteStream_unpack_intnb_inplace_rshift__pyx_kp_write_long__pyx_v_old_pos__pyx_v_diff__Pyx_StringTabEntry__pyx_pf_6cpyamf_4util_18BufferedByteStream_append__pyx_tp_dealloc_6cpyamf_4util_cIndexedCollectionc_profileobjcl_delattr__pyx_v_c__pyx_v_dPyInstance_Typelong long int__pyx_v_i__pyx_skip_dispatch_Py_NoneStruct_flags2__pyx_k_getByReference__pyx_v_valPyMappingMethods__pyx_kp_getByReferencef_builtins__pyx_doc_6cpyamf_4util_18BufferedByteStream_read_ushort__pyx_f_6cpyamf_4util_19cBufferedByteStream_unpack_uint__pyx_obj_6cpyamf_4util_IndexedCollection__pyx_v_hmodules__pyx_v_l__pyx_v_n__pyx_v_p__pyx_v_r__pyx_v_s__pyx_pf_6cpyamf_4util_18BufferedByteStream_truncate__pyx_v_x__pyx_pf_6cpyamf_4util_18BufferedByteStream_write__pyx_f_6cpyamf_4util_11cIndexedMap_clear__pyx_k_use_hashtp_flags__pyx_doc_6cpyamf_4util_18BufferedByteStream_read_short__pyx_k___init____Pyx_Import__pyx_tp_as_mapping_cIndexedCollection__pyx_k_mapped_obj__pyx_k_NotImplementedError__pyx_kp_getvalue/home/buildbot/slaves/pyamf/debian64-py23/build @raise TypeError: Unable to coerce buf -> StringIO __pyx_k___str__nb_subtractb_level__pyx_v_6cpyamf_4util_complete_init__pyx_k_write_float__pyx_tp_as_mapping_cBufferedByteStream__pyx_k___richcmp____pyx_k_truncate__pyx_vtable_6cpyamf_4util_cIndexedMap__pyx_tp_as_buffer_BufferedByteStream__Pyx_InitStrings__pyx_doc_6cpyamf_4util_18BufferedByteStream_write_ucharPyInt_Type__pyx_doc_6cpyamf_4util_18BufferedByteStream_remaining__pyx_v_bytes_left__pyx_k_write_char__Pyx_GetNameco_varnames__pyx_type_6cpyamf_4util_BufferedByteStreamiternextfunc__pyx_methods_6cpyamf_4util_cIndexedCollection__pyx_kp___cinit__co_lnotabthread_idcl_bases__pyx_pf_6cpyamf_4util_18BufferedByteStream_at_eofnb_int__pyx_pf_6cpyamf_4util_18BufferedByteStream_read_double__pyx_f_6cpyamf_4util_19cBufferedByteStream_write_ulong__pyx_k_othertp_descr_set__Pyx_ParseOptionalKeywordsnb_coerceshort int__pyx_v_buffer_vtable_offset__pyx_f_6cpyamf_4util_19cBufferedByteStream_write_doubletp_basicsize__pyx_f_6cpyamf_4util_19cBufferedByteStream_read_doublenb_inplace_subtract__pyx_v_leco_cellvars__pyx_v_maxint__pyx_k___cinit____pyx_kp_clear__pyx_v_big_endian__pyx_pf_6cpyamf_4util_18cIndexedCollection___copy__nb_divmod__pyx_kp_IOError__pyx_f_6cpyamf_4util_19cBufferedByteStream_read_shortobjobjproceval__Pyx_TypeTest__pyx_k_clear__pyx_v_exceptionsPyInterpreterStateP33PCCPPTUP\T\ePejPjkTPeQekQptwtwpUUxQQPPPP P/3PMPP_cPpw%w0pU/\/9Q9\Q+\+Q\ QQpT%S%9T9ST%SpQ*V9V%V 9U9UUU /\\=\%\ 4]]A]%] 9P5TPajPyP0FwFw 0NUNy\y~U~\0`T`tVtTVTV0QQktPPPwIw U \ UI\TVT,V,:T:IVQBQP*,PGIPPfwfw PnUn\U\PTVTVTVPQQPPPwiw U)\).U.i\T$V$:T:LVLZTZiV:Q?bQ$PJLPgiPpwwpUSS;nSP1^;^],][]P6_d_P'\j\V"VlVSSnSw/ wUTP/ S0 4 w4 } w0 > U0 > TA C PH O P{ } P w w U P P P w w U= W U U T= G T T8 < PB F P w 1 w U T P/ 1 P@ D wD w@ N U@ N T] ] P P w  w U T P  P $ w$ w 1 U 1 T@ @ P P w w U T P P  w ~ w  U  T" " P| ~ P  P? D P " P7 7 P: ? P w w U T P P w Tw U TPRTP`awaw`sU`mTzQQQvxPPSw7wUTQ3Q57QPP7S@AwAw@SU@MTZeQjQQVXP`ePeSwwUTQQQPPS !w!w 4U )T)4Q;FQKQQ79PAFPFSwwUTQQQQPPSwgwU T Q&Q+cQegQP!&P&gSpqwqwpUpyTyQQQQPPSw?wUTQ;Q=?QPP?S@AwAw@PU@MTWbQgQQSUP]bPbSwwUTQQQPPSw_wU T"Q'[Q]_QP"P"_S`awaw`pU`mTwQQQsuP}PSwwUTQQQPPS !w!w 0U -T7BQG{Q}Q35P=BPBSwwUTQQQPPSwwww w( w0Un\q \T6V6CPCURUlVlqRq VQp]q ]?dQQQ?QUqRqQRQdqQQ QP'6PUkSqzSzPSP Swwww "w("Jw0)U)\J\)T)hShqPqSJS)Q)]J]aQQqRRBqRRRQCQEJQ,.P[hPPVVPJVPkwk9w0PwUwS9SPwTw\9\PwQwV9V]]PPPzP9P@AwAw@KUKbSiSSS_aPipPPwWw U SWSQ SQUWQPWV`nwnw `xUxSSQQQ{}PVwqwUTPP44PPU&5S6qSw"wUTPPPPUP08w8w0;U0;TMOPQXPP>@PEJUvSSwrwUTPPIKPPUPwwUTPPPPUSS $w$lw (U -T02P7>PjlPpww pU\\pTU|VVPSww0 U SSS3SSbS T \\SS3SSbScf] VV"%P:fVf^V^SVwwww w(w0w8 "wUv!]{!!]! "]Tt!\{!!\! "\Q!w !!!?!w ?!{!{! "w Rx!^{!!^! "^ XY "w' ' T  T  !T!!!5!T5!?!?!G!TG!!!!T! "% S% ^ Q^ !S!5!Q5!q!S{!!S!!Q! "Sr!V{!!V! "V ";"w;"$w "J"UJ""\"$\ "J"TJ""S""T""S7##S$$S "J"QJ""V"$V""T##T""Q##Q""P ##P""S""P##U#$SV""]"7#]T#$]$$w$$w$$w$$w $$w($y'w0$$U$3%S)&D&Se&z&S&'S$%T%%S%%SD&N&S%%P%y'\%%P%&V&y'V0%3%P)&D&SN&z&S&y'S''w''w''w'V)w ''U''U((U((U''T''Q''T((Q((Q''Q''Q''Q((Q'(P((S(V)S''S''S/(2(P((V((V((S(,)V`)v)wv)/+w `)})U}))V)Q*V+/+V`)})T))\))\)/+\))P**P **P))P)/+S))V)*VN*Q*P0+>+w>+,w 0++U0+N+TN+b+Qb+x+Tx++Q++Tx++P&,+,Px+}+S++Px++V++P]+b+Px++P,,w,[1w0,,U,-\-[1\,,T,-]-[1],,Q--Q,;-S--S-.S..SF/k/S-0p0S--Q--Q.".QG.I.Qp.u.Q:0p0Q--P--V-/V/0V0[1V8-;-P..P..Ph/k/Pp0[1Sj-m-P//V00V`1p1wp12w `11Ul11P11P'2,2Pv1{1S11Pv11V11P22w2'5w022U24\4'5\22T23S34S4-4Sp44S33P4 4P 33P44S-4p4S4'5S?3B3P4 4V-4p4V44V0545w455w 05F5U05@5TQ5c5t~55t\5^5P~55P55P55w55w57w 55U55T6&6h66h6$6PJ6J6PM6S6Pr6w6P66P66P66P 7;7w;78w0 7G7UG77S78S 7G7TG77]78] 7G7QG77V78V77P.838PG8M8PJ7d7Pd78PU7Y7PY7m7\77\77P838\B88\89w99w 89U9!9S099S89T9+9\099\89Q9&9V09H9VH9T9QV99V9&9P0949Pf9h9Pw9z9P99P9?9P?99P99w99w9:w::w : :w( ::w09:U:\:]]::]9:T:X:V]::VR:V:P::P::w:<w ::U:;S;;S;<S::T:2;\2;G;QG;X;\X;];Q];<\2;S;S;;S;;P];;S <6<w6<=w <B<UB<<S= =S==S <L<T=<<\<<Q<<\<<Q<=\<<S ==S<<P< =S==w=>w ==U==Sr>{>S>>S==T=>\>'>Q'>8>\8>=>Q=>>\>3>S{>>S==P=>{>S??w? ?w ? ?w ?Z@w ??U?U?S??S?Z@S??T ?t?\t??Q??\??Q?Z@\t??S??SR?U?P??S`@b@wb@j@wj@k@wk@Aw `@x@Ux@@S'A0AS:AAS`@}@Ti@@\@@Q@@\@@Q@A\@@S0A:AS@@P@0ASAAwAAwAAwACw AAUABSBBSBCSAATA4B\4BIBQIBPB\PBQBQQBC\4BMBSBBSBBPQBBS C"Cw"C*Cw*C+Cw+CrDw C8CU8CtCSCCSCrDS C=CT)CC\CCQCC\CCQCrD\CCSCCSqCtCPCCSDDwDDwDDwDDw DDUDDVDDPDDPEEwE Ew EEwEEw EEw(EGw0EEUEE^EF^FG^EETEE]EF]FG]EEQEESEESEFQFFSFFSF?GSEEPFFPFFPFFS?GGS7F:FPFFVjGGV`EjEPEEPEEPGGwGGwGGwGGw GGw(G}Jw0GGUGH^H*I^+I}J^GGTGH]H&I]+I}J]GGQGGSGGQGGSHHSHHQH!IS+IaISI JSGGPHHPHHP(I(IPGGPaIIS J}JS&H)HPaIIV JSJVHHPHIPIJIPJJwJJwJJwJzLw0JJUJKKSKzLSJK`KPL`7K;KPKKPKKPJJPJKPKzLPJJPJJPJ=KV>KKVKKVKPLVLLwLPw0LLULLSM+MSqM6NSUNsNSNOSOPS:PrPSPPSLLTLLVMPVLMXqMMXM6NXNOXOPX:PrPXPPXLM\qMM\M6N\NO\OP\:PrP\PP\LLPMMP1N6NPO OPLMPMMPMNPNNPNPPLLS(M+MP6NUNSpNsNPOOSP:PSrPPSPPwPZRw0PPUPdQSQQSQRS!RLRSURZRS;QaQPQRP!R-RP\QQ]QQ]RZR]dQQSQQSRBRSLRURS`RqRwqRSw `RuRUuRRSRRSRRSRRQRRQR SQ SSQRRVRSVRRSRRP S1Sw1STw S5SU5SESS\SSSSSSSSSESWSSSSSSTSJSRSVSSPTTwTjUw T"TU"TcTSTTSTjUST,TTTT\TTQTT\TTQTjU\TTSTTS`TcTPTTSpUrUwrUtUwtUvUwvUxUw xUyUw(yU}Uw0}UUw8UegwpUUUUVwVVVVwV\W\WXwX5Y5YMYwMYYYZwZZZX\wX\\\]w]U_U_u`wu`aaawa^b^bbwbccAcwAccccwc$d$dgewgeffegwpUUTUUSUUTU VSVVS\WnWTnWWS X XT X0XS5YMYS\\SJ\X\SU__SaaS1gegSpUUQU6VVVVV&WXV XbXVYMYVZ%[V\\VJ\X\V\\VU_]_Q]__Va\aVaaV^bbV1gegVUV]XX]5YMY]YZ]%[[]\$\]J\S\]X\\]\_]7_U_]_a]aa]aa]bb]1b;b]^bjb]bb]bb]bb]cc]AcKc]pczc]cc]cc]cd]$d.d]Td^d]dd]dd]dd] ee]:eDe]geqe]ee]ee]ee]f'f]JfTf]wff]ff]ff]gg]U&Vw&VYVYV:Ww:W\WW X XYwY5Y5YU_w_awaawa^b^b1gwUU^UV^V\W]nWX^XY^Y5Y]5YMY^MYY]YZ^Z%[]%[\^\\]\$\^$\J\]J\\^\\]\_^_7_]7_U_^d_a^aa]ajb^jbb]b.d^.dTd]Td^d^^dd]dd^dd]dqe^qee]ee^ee]ee^ee]ee^ef]f'f^'fJf]JfTf^Tfwf]wff^ff]ff^ff]feg^W\WSWXSY5YSMYeYS\\S&W\WVWXV`XbXPY5YVYYVYZPZ2ZVZ=[V=[O[PO[X[VX[`[P`[J\V\\V\\P\U]V_-`VbbVccPcAcVpccVccPccVddVdgeVf1gVVVPV\W\WX\XXPY5Y\MYY\ZZPZ%[\p[s[P\\\X\\V\\\]]P]U_\__\-`a\a^b\bcVAcc\cTd\d e\gef\V VP-X0XPeY\S\J\SX\U_S_aSa1gS3V6VPV\WVWXVX X_XXPY5YVMYYV/Z2ZPZZVZ%[_\\_'\J\_X\\_]]PU]$_V$_7__7_U_V_-`_-`9aV9a\a_\aaVa^bVbb_bc_AcpcVcdVddV e:e_gefV`[m[P\\PffP`[m[P\\Pg gPWWXUURUVRVVRnWWR5YCYRJ\X\Rf__R__P__R__P__RaaR__P[gegPpggwgiw0pggUgYhVhhiVpggTggS,hThShhSiXiSgch]hhi]OhYhPhhPggP,h4hPhhPggPIhThShhhShiSXiiSggPIh^h\hhh\hh\hi\Xii\ hChPChiPiiwiiwiiwijw iiUi jSjjSj jPDjFjPiiPjFjVjjwjjwjjwjjw jpnw0jjUj kVkkVkpnVjjTjk\kk\kpn\jjXjjXjkXkkXknkXnkkXkkXkkXklXllXl mX m?mX?mmXm nX npnXk kPkkPm mP1n?nPAnFnPjjPj kSkkPkkSRkukPkkSkkPk:lPCllPllPl mS m?mPBmmPmnP nnP npnSjjPkkPJkukPl:lPCllP m$mP2m?mPmmPmmPmmPmnP nnPjjPkkPkkPllPn nPpnqnwqnrnwrnynwynDow pnnUnnSnDoSnnP o oPnnPn oVPoRowRoTowToVowVoXow XoYow(YoZow0Zo^ow8^oAqwPodoUdoowop@pqwqAq@-p[pSppSpAqSo`p]epp]qAq]5p8pP8p\pVppVqAqVloooPooVoo^o8pV8p>pP>pbp^epwpVwpp^ppVpq^qqPqAq^}odp_epp_qAq_ooVwppVppVo-pSeppSPqfqwfq=sw PqsqUsqqVqqVArWrVrrVs=sVPqsqTPqsqQsqq\q=s\qqQArMrQRrWrQrrQvqxqPqqSArWrSrrSqqSqqPr=sSqqVqqPrsV@sBswBsKswKsMswMsNsw NsRsw(Rs5uw0@sUsUUssV.tt\JtWt\^tt\t5u\wssSJtTtS.t:tQCtJtQSt^tQttQXs[sPussPsIt^Jt]t^^t5u^ssP^ttSt5uSssP^ttVt5uV@uAuwAuHuwHuuw0@uWuUWuuSuuwuuwuuUuuSvvwvvwvqvw0v vU vpvSvvwvxwvvUBwVwUvvTvvSw.wSBwQwTQwtwSwxS*xAxSxxSvw]w&wU&w=w]=wBwUBww]wwUww]wwUwx]w8w\ww\ww\xx\4xAx\vvPwwSx}xSvvPw3wVqwtwPwwV*x}xV}xxSxxwxLyw xxUx1y\6yLy\xxTxxUxxP6yLyVx,yS6yLySPyQywQyRywRyYywYyzw PydyUyyUPy_yT_yySyySy3zSqzzSyyQyyQyyPy,zQ.z3zQyyPzzPlyoyPyyVyyVyyPzzVyyPyySzqzSzzwz_{wzzUz{S{{U{^{SzzR{{RzzQzzTzzQ{{QzzP{{P]{]{P`{a{wa{{w`{{U{{S{{U{{S`{{T{{Tn{{Q{{Qk{v{Rv{{P{{R{{R{{P{{P||w|}w0||U||\|}\|&|a&|g|w g||\||w ||\|}w )|,|P|}V||Q||Q| }Q}}Q||S|}S0}3}PJ|`|P}||P||P|}S}}w}~w0}}U}1~S@~~S}}T};~\@~~\,~6~P_~i~Pk~m~P~~P}}P@~~V~~PB~N~P~~w~w0~~U~W\\\~~a~wPwPw~~P\VHRP<AP P %P68P+P+ASP€PDSJUP %PPWbPwwځUځ҃]׃]TiSSS׃SSŁ\.V.6\6<V<W\WV˂\˂ڂVڂ\ÃVÃ̓\׃V\iSȃS׃S<AQPPSQSQ7:PVJVքwք+w ڄUڄSST\&\&+TQ V Q!V!+QP!P01w12w29w9w 0=U5SgUU=cUcgUwwUu\\TԅVԅTfVfTVTT8T8VBVQ˅SkS8@Q@SBSą)UfUU8UU˅kS8SBSfpP P38PPP 3PPP&Xz]8]C]ׇPPPPP 3PPׇP߇PaPۈwۈwU\\TVTVTVۉTT*hThVrVQSShpQpSrSYUۉUU*hUUShSrSP5=PchPމP5P=cP%PHOP(VX]h]s]PPۉPP*5P=cPȊ݊PPPPwwU^^TSS3ASRuSSQ͌VVUsV3AVVRuVV.׌\_R\u\Ō͌VsVVA]VŏVRVVŌHsHA]HŏHRHŌ܌]܌QgU]UnQn3]AR]u]ҌSUsSŏSŌҌS|PPS),PS"P"3SA]SuSŏS!RSŌ͌VVUVŎV3VuŏVuVŌ͌VP,S,sVŎVAuVSŏV!S!RVuSPX=WRRP+0R0KPZyRRuR"KPP,SP]uSS!SwWwU^ÑW^*T*SÑؑSfoSyԒSϓSݔSŕSXÑwf2wtwŕ@*w#^V^]V]ÑyVy]V]Vݔ]ݔŕVŕ*]*WVSoyS^\fy\\ϓ\ݔ2\t\ŕ\ՑؑP2tSŕS*WS^S\ Pfy\ђԒPPSϓݓPݓSݔ2S2t\tSŕ\ŕ*Sw~P~ POP`Pf{PDOPzP`bwbjwjlwlpw pqw(q[w0`wUwޗ^ߗv^w[^`wTwڗ\ߗr\w[\`QQ?UQ֗חPnnPZ_PŖؗVߗpV V_1VPʖPחSߗP-S-OPOSP S +P+oSP]bPbsSszPzSP?S_[S`xwxXw `~U~ǝ\̝X\`ToV̝XVP'PSXPP̝XS`xwxGw `~U~Ş\ʞG\`TP'PoVʞGVPʞGSPhwhHw PnUn\H\PsT_VHVP PCHPvyPHSPRwRVwVZwZw PeUe\\PqTqV8hVhmTV¡VFHPPPPS¡SxSޠPVVxV8HVhV¡VxV8HSpsP¡SxS٢w٢w ݢUݢ(V2VTS2eSkzS]ST#Se+S]S(PPPTT-\e\ILPwwwsw >&S*צSSҫ2S PP2PAHP5XP18P[~PPPƮPʧP PͧPxPPMTP&SP2^SASɪުV2AVwwU__T\\PVV8OV{͹VEoVHzVP͹SESzS-0PSVP,P,SѸPѸS8bSbjPj{S{PSEVESSSHzSzVлSVIV8VO{VVoHVVST8SHSлSTTV 8VVHVPwwww w(w0w8pwvV_5VV7VCiVuVVV HVTzVVJpVy\5\\7\Fi\x\\\ H\Wz\\Mp\{S5SS^5^Ma^^^^=(w(¿SڿݿP${S{w55eweSV S w7w7Sw V HHSpwx{P¿$S<?P}VS VSHSzVVo5w Mw pw SSS5MSSSpSPSaS7SSPMa\\7F\ix\\ \HW\z\\PM}V aVV7CViuVP5]Ma]]]](SMeS aSS7SpwwpUSSpTTTTpQVVQVQAQQQQW\QQH*H*/P/HTTwwUTQPSSw~wUTQ"PTiSj~Sww UVVTSSSSSSPUWPP\\Pw{w UbVl{V$T$-SlS&@S-]S&S@{SYbPP!&P-g\&\HKPwDw UVDVTS S'S!SSTPTST S%P%'S'5P:GPGNTXTSPPP SSS!DS\\ PPawaNw PeUeuSSS.SuxSS.NSuVVPPRwRVwVZwZow PeUe \!o\PqTqV8qVqTVTTV!KVuV#QVFKPPPS!uS#SPVKuV#V8KSuwVw|S|PSPSPV TSV8KVqVVVuVVQoVqwSS=@Pprwrvwvzwzw pU\\pTVXVV(VkVfkPPPS8bSS(kSPVV(kVXdQSQPQSQTPSP'P'6QbQXkSS8SbS(SSXkVV8VbV(VPwwww w(w0w8wU0_1_T{w{11ewew??w,],.^]Z] .]8^]h]]]]?]Io]y]]]#]-P]Z}]]]]4]>a]k]]]'SSPS1S\S PM^MV8^8V.^1V^VV^^V^^V^V?VBNwNwk@k1@1Ge}}@@@ @ C@CZw``ewe#@#@@  @?wexxwP\\Z\\ /\\\;\BS1GSS ZSSY\PMV(V}VVeVVPwwww Up\q\T1VVT!V!-T:JTJnVqV+VsVPlmPPlmSqS0sS.1PlnVV0sVSVSP!S!-P-:S:JPJTVT]TlmSmnVVV!V:nVV+0VVSSPwww w UJ\K \TQVHVKVxVVPFGPPFGSSSxSNQPFHVVxVQSQP Q S*Q*3TKUPUWSWePjwPwQQSGSKSS5xS SVHVKVV:xVP+w+ow:U:]o]:T:MSMVTVSTSS}SSS;oS:Q:DVVVVxVVV;oVUs}UDCVZVVxVDVIVVPP\\\}\\;\SFHVHQSQZPZVSV}SPSPSXSPSSS SVCV}VVDIV;VCHSS PV\\\}\\\;o\?fPeoPpwwpU@\E\pTST6SEJSJSTn{T/SSiSpQ;VEVV,V#6S6;VJbVbnSVSPV-/PpS PiSPS1;PX#;VJnVVpVV1iVVS,1SPREYRRPRP*RRPP3w3w?U?^^?T?QSQZTZSS3AT3]SUS?Q?VVV3AVV3]VUVI\u3\]U\H3HA3H]UHV+VVA]VV3VV]Q]Q3]A3]]U]SSSSPPSWZPS"P"3SASSSVVV3V]VVV!V+ZSPPSS3SV"S"+P+BSS]nPnS?EPEUSmXZtR <RHMRpR3]R?hPPVVA]VV3V]dVVV!?VSS PwwUs]}]TVTiV}T V TVT|VVQdS}SSS S2=Q=HSSSS_iP PNdSP2SHzSXSS@`SNx^ ^2^H^^,/P^SMRSSNiV V2VHVy|PVn\ \2\Rz\\\\PPPPPPPPP CwC)w OUO^)^ OTO[V[tTtV0T0aVaxTxVTV(T0VVTVVT)V RQRfStSSLPSSQSmSS)SfSVdfVfoSoxPxSSPPmS(SSPSn\7:S:C\CLPL\\P(\(:P:\\c\P\PPP)PXS4PS(4SPSS@cS4:\P^\,/PVaVVV5mV(VVafS05SPt\\m\\\)\xPPPePnPPPPPPhP)P0IwIw 0TU0NTN\\0TQTVVWZPSwrw UTC\Hr\Q:VHrVPHrSwBw0UT]B]Q\B\PBSPnwn" w0PyUPpTp]" ]PyQy\" \|P" S0 2 w2 7 w7 9 w9 ; w ; ? w(? @ w0@ D w8D w0 X UX a \a e Ue [ \b  \  \ \A\0 X TX a _b _0 X QX  w   8 w8   w  Q. ; QP b Q  Q  Q8 h Q  Q ' Q _ ^8  ^  ^  ^ 6 w6 b @b  w, 8 @8  w w X SQ V Sk n Pn  S Y V8  V @ V  V ' V  V Y V}  P8  V  V@  V  P  V'  V V [ \[ ] ]  ]  \8  \v  \ A\\  S ) S. = PP W PK V Pn { P  P  S " S'  S ] ]  ]8  ]  ]v  ]  ] A]]  S  SPO'OJJ_ _ (3 (3@PXc@PXc+%+%NkNk,,nn0L0L/ / 'x'xG[G[!!!!7## $$t%%&&%&PE`EEEPE`EEEHH0IЦAЦAצAS AS#1C*;2;1CBIPaXahoѮv~Ѯx§ӧʧӧxڧM_M_2A۪2Aɪ۪,.0ѸӸո oлŻ"0"0T0bڼ0ڼڼ^h} vqtoh} >^2ͽֽݽͽֽݽ$$EKBH*.EKBH*.lrlr22'0q0q'HRUX .o.o eshx}3>-0(v/n*Dp~Xep~Xe@D04"+-&{l9@X{KMEHD0XD5XD !DaNauN.N#`#o`#o`q#o:=Qo@Fk8k8k%B?ZVYx\k?/e?s0(@s0-@s0 :` :e : !!+Q;P+Q;P+C;P ; };o-Eeot,t,t ipEU8`Hx-E"U`"EU?`? !?`Rt`Rt`),@`/5`Rz `Rz`Rvy|2P~Cc0PCc0P4c),@c/5Poc0Poc0Pac~)p>VVn)'PrPr#' np " snp " snpsy|O z       r        r        r          JJ__.symtab.strtab.shstrtab.gnu.hash.dynsym.dynstr.gnu.version.gnu.version_r.rela.dyn.rela.plt.init.text.fini.rodata.eh_frame_hdr.eh_frame.ctors.dtors.jcr.data.rel.ro.dynamic.got.got.plt.data.bss.comment.debug_aranges.debug_pubnames.debug_info.debug_abbrev.debug_line.debug_frame.debug_str.debug_loc.debug_rangesXXoxx`% ` -885o,,Bo Q.[DD eJJ`JJkOOq__w__yyh~h~!(!(8!8@!@H!H!В!В!X: `!X XV  #2'@40[?OCJ0<X>%< hFXx8,D J J O _ _yh~!(!8!@!H!!В!!`! !"  O'!5(!C8!P 0Of`!uh! O !8! ^ O  P6 P h P 0P @P `P73 P#l P# Q# 0Q#  `Q TM T @U U `Ve@!!# !+0!=8!J@!X XOH! YM`! pYM1 Yk! Zap! 0[aP!3 [df \d \a \~  p]a= ]do P^g ^g 0_g _gW `g `g `g `ag7  a_r  0b_  b_  b_  Pc_R  c_  d_  pd_  d*/ !S  f:  @g  0h  hw&  Pi|Y  i  pj  k  k#  plY  mL  `ml  m  o r/P!<h!P!g t! pw!!9 Pys! {! |P!! PXZH!f g!(!  Ѕ>1!T!u!!!!!# T!n   j j8 jn Z PR Z RJ pz| `! ! X! pO pL  P  j `1!_!n(!|!! !!x!!!!!0!p! `FI!U   ` @ @E!Q@!l 0! 0 , q3 pNph!|! | @r0!  PO    5p!A km _ .!!X!`!P! .J!U!`0!w !8! ! g!"!E!Q!w! P!!!!!! PP P @ @k! D!T!j!v!@ !O! (!p!!!!! ! !5 !K 8!m !  !H ! !8 !H! !HE!!k!h!!!8!!!X!""!HH"!t"x!"o! "!"!"! #x! #!1#! <#!Y# pp#!#  #x!#!#!#!$!$!"$ `/Y$ f$ n$ p{$ {)% pf% @ x% @!%!% `$M%!& '5& 6l&!x& 9M&!& =_&@!&H!'!' `AT'!k' Ey'!' J'!' P /(!F( Vt( V( pW( @X( Y&) !0M)`!Pv)!)! )! ) !0*!PC*P!j*`! *!*!0*!P*!+@! >+`! f+!0+@!P+!+! ,!0,!P_,!0,!P,0!,`! ,!$-!xR-!0p-!P-!-@! -!-!x.! ,.`!?.! Q.h!f.! z.p!.! .!.!.x!.ĕ!.!.ʕ!.Е!.!/Օ! $/!5/ߕ!E/! V/!f/!u/!/!/!/!/! /!/ !/!/! 0!0! -0!B0'! V0!j03! }0!0>! 0!0I! 0!0`!0!0p!0!1! 1!01! C1!Y1! n1!1! 1!1! 1 !1! 1(!1Ж!10!2!28!2!&2@!12 !;2H!P22! d2P!z2>! 2X!2K! 2`!2V! 2h!2b!2p!3i!3x!03q!@3!R3y! c3!x3! 3!3! 3!3! 3!3!4!4!64!E4!S4!^4З!h4!u4!4!4!4!4!4!4!4!4!4!4!4! 5!5 !%5!35!@5!O5!]5! n5$! 5!5/!5!52!5!56!5:! 5E! 5Q! 5\!6k! 6p!,6t!;6{!J6!Z6! m6!6! 6! 6! 6!6Ę!6ɘ!6Θ!6!6! 7!7!70!)7P!47e!?7p!J7!U7!`7ƙ!k7ș!v7ʙ!7̙!7Й!7!7!70!7P!7p!7!7!7К!7!7!80!8P!8p!&8!7X8!q8`!$8!>8!|'9`!,]9!p9 !9 !9 !+:!`:`!=:!3:!C;@!:@;!Cx;!:; !C;!:(<!a<!< !<! =!E=`!s}=!=!s=!T6>`!fu>!9> !>!8 ? !qY?!?В!?!?0!?H!???@@"@/@@!x[@h@x@@@@ @ @@@ _@A"A2ABAPA\A!xAAAAAAAB!B.BABRB`BkB|BBB pB!xB@!xBC"C-CCCRCaCuCCCCCCCCCDD(D7DKDZDkD!DDDDDX!DDDE!E5ECEQE!xvEEE@!xEEEF!FF-F=FKFXFX!_FjFwFFF JFinitfini.ccall_gmon_startcrtstuff.c__CTOR_LIST____DTOR_LIST____JCR_LIST____do_global_dtors_auxcompleted.6085dtor_idx.6087frame_dummy__CTOR_END____FRAME_END____JCR_END____do_global_ctors_auxutil.c__pyx_f_6cpyamf_4util_19cBufferedByteStream_close__pyx_f_6cpyamf_4util_19cBufferedByteStream_tell__pyx_pf_6cpyamf_4util_18BufferedByteStream_flush__pyx_pf_6cpyamf_4util_18BufferedByteStream___len____pyx_pf_6cpyamf_4util_18cIndexedCollection___len____pyx_tp_traverse_6cpyamf_4util_cIndexedCollection__pyx_tp_clear_6cpyamf_4util_cIndexedCollection__pyx_getprop_6cpyamf_4util_17IndexedCollection_use_hash__pyx_getprop_6cpyamf_4util_17IndexedCollection_exceptions__pyx_getprop_6cpyamf_4util_10IndexedMap_use_hash__pyx_getprop_6cpyamf_4util_10IndexedMap_exceptions__Pyx_Raise__pyx_setprop_6cpyamf_4util_10IndexedMap_exceptions__pyx_setprop_6cpyamf_4util_10IndexedMap_use_hash__pyx_setprop_6cpyamf_4util_17IndexedCollection_exceptions__pyx_setprop_6cpyamf_4util_17IndexedCollection_use_hash__Pyx_AddTraceback__pyx_filename__pyx_clineno__pyx_m__pyx_empty_tuple__pyx_lineno__pyx_cfilenm__pyx_getprop_6cpyamf_4util_18BufferedByteStream_endian__pyx_f__pyx_pf_6cpyamf_4util_18BufferedByteStream_getvalue__pyx_vtabptr_6cpyamf_4util_cBufferedByteStream__pyx_pf_6cpyamf_4util_18BufferedByteStream___str____pyx_f_6cpyamf_4util_19cBufferedByteStream_has_available__pyx_builtin_IOError__pyx_pf_6cpyamf_4util_10IndexedMap_clear__pyx_vtabptr_6cpyamf_4util_cIndexedMap__pyx_pf_6cpyamf_4util_17IndexedCollection_clear__pyx_vtabptr_6cpyamf_4util_cIndexedCollection__pyx_pf_6cpyamf_4util_18BufferedByteStream_append__pyx_pf_6cpyamf_4util_18BufferedByteStream_write_utf8_string__pyx_pf_6cpyamf_4util_18BufferedByteStream_consume__pyx_pf_6cpyamf_4util_18BufferedByteStream_at_eof__pyx_pf_6cpyamf_4util_18BufferedByteStream_close__pyx_pf_6cpyamf_4util_18BufferedByteStream_write__pyx_f_6cpyamf_4util_19cBufferedByteStream_write_24bit_int__pyx_f_6cpyamf_4util_19cBufferedByteStream_write_24bit_uint__pyx_f_6cpyamf_4util_19cBufferedByteStream_write_long__pyx_f_6cpyamf_4util_19cBufferedByteStream_write_ulong__pyx_f_6cpyamf_4util_19cBufferedByteStream_write_short__pyx_f_6cpyamf_4util_19cBufferedByteStream_write_ushort__pyx_f_6cpyamf_4util_19cBufferedByteStream_write_char__pyx_f_6cpyamf_4util_19cBufferedByteStream_write_uchar__pyx_f_6cpyamf_4util_19cBufferedByteStream_read_24bit_int__pyx_f_6cpyamf_4util_19cBufferedByteStream_read_24bit_uint__pyx_f_6cpyamf_4util_19cBufferedByteStream_read_long__pyx_f_6cpyamf_4util_19cBufferedByteStream_read_ulong__pyx_f_6cpyamf_4util_19cBufferedByteStream_read_short__pyx_f_6cpyamf_4util_19cBufferedByteStream_read_ushort__pyx_f_6cpyamf_4util_19cBufferedByteStream_read_char__pyx_f_6cpyamf_4util_19cBufferedByteStream_read_uchar__pyx_f_6cpyamf_4util_19cBufferedByteStream_unpack_uint__pyx_v_6cpyamf_4util_SYSTEM_ENDIAN__pyx_f_6cpyamf_4util_19cBufferedByteStream_unpack_int__pyx_f_6cpyamf_4util_19cBufferedByteStream_peek__pyx_f_6cpyamf_4util_19cBufferedByteStream_getvalue__pyx_f_6cpyamf_4util_19cBufferedByteStream_remaining__pyx_f_6cpyamf_4util_19cBufferedByteStream_at_eof__pyx_pf_6cpyamf_4util_10IndexedMap_append__pyx_pf_6cpyamf_4util_10IndexedMap_getReferenceTo__pyx_pf_6cpyamf_4util_17IndexedCollection_append__pyx_pf_6cpyamf_4util_17IndexedCollection_getReferenceTo__pyx_pf_6cpyamf_4util_18BufferedByteStream_remaining__pyx_pf_6cpyamf_4util_18BufferedByteStream_tell__pyx_sq_item_6cpyamf_4util_cIndexedCollection__pyx_f_6cpyamf_4util_18cIndexedCollection_append__Pyx_ParseOptionalKeywords__pyx_pf_6cpyamf_4util_10IndexedMap_map__pyx_kp_obj__pyx_kp_mapped_obj__pyx_pyargnames.14738__pyx_pf_6cpyamf_4util_18cIndexedCollection___copy____pyx_ptype_6cpyamf_4util_cIndexedCollection__pyx_f_6cpyamf_4util_11cIndexedMap_getMappedByReference__pyx_kp_57__pyx_v_6cpyamf_4util_pyamf_ReferenceError__pyx_f_6cpyamf_4util_18cIndexedCollection_getReferenceTo__pyx_kp_55__pyx_f_6cpyamf_4util_18cIndexedCollection_getByReference__pyx_kp_54__pyx_f_6cpyamf_4util_19cBufferedByteStream_seek__pyx_kp_29__pyx_builtin_ValueError__pyx_f_6cpyamf_4util_19cBufferedByteStream_complain_if_closed__pyx_kp_28__pyx_pf_6cpyamf_4util_18BufferedByteStream_write_float__pyx_kp_53__pyx_builtin_TypeError__pyx_pf_6cpyamf_4util_18BufferedByteStream_read_float__pyx_pf_6cpyamf_4util_18BufferedByteStream_read_double__pyx_v_6cpyamf_4util_float_broken__pyx_v_6cpyamf_4util_system_nan__pyx_v_6cpyamf_4util_pyamf_NaN__pyx_v_6cpyamf_4util_system_neginf__pyx_v_6cpyamf_4util_pyamf_NegInf__pyx_v_6cpyamf_4util_system_posinf__pyx_v_6cpyamf_4util_pyamf_PosInf__pyx_f_6cpyamf_4util_19cBufferedByteStream_read__pyx_builtin_MemoryError__pyx_f_6cpyamf_4util_19cBufferedByteStream_write__pyx_f_6cpyamf_4util_swap_bytes__pyx_pf_6cpyamf_4util_18BufferedByteStream_read_24bit_int__pyx_pf_6cpyamf_4util_18BufferedByteStream_read_24bit_uint__pyx_pf_6cpyamf_4util_18BufferedByteStream_read_long__pyx_pf_6cpyamf_4util_18BufferedByteStream_read_short__pyx_pf_6cpyamf_4util_18BufferedByteStream_read_ushort__pyx_pf_6cpyamf_4util_18BufferedByteStream_read_char__pyx_pf_6cpyamf_4util_18BufferedByteStream_read_uchar__pyx_f_6cpyamf_4util_18cIndexedCollection__clear__pyx_f_6cpyamf_4util_19cBufferedByteStream_pack_uint__pyx_kp_31__pyx_builtin_OverflowError__pyx_f_6cpyamf_4util_19cBufferedByteStream_pack_int__pyx_kp_30__pyx_f_6cpyamf_4util_19cBufferedByteStream_consume__pyx_f_6cpyamf_4util_19cBufferedByteStream_truncate__Pyx_PyNumber_Int__Pyx_PyInt_AsLong__Pyx_PyInt_AsUnsignedLong__pyx_pf_6cpyamf_4util_18BufferedByteStream_read_ulong__pyx_pf_6cpyamf_4util_18BufferedByteStream___init____pyx_ptype_6cpyamf_4util_cBufferedByteStream__pyx_kp_write__pyx_kp_seek__pyx_int_0__pyx_kp_36__pyx_kp_getvalue__pyx_kp_37__pyx_kp_40__pyx_kp_38__pyx_kp_39__pyx_kp_tell__pyx_kp_read__pyx_kp_buf__pyx_pyargnames.10814__pyx_f_6cpyamf_4util_19cBufferedByteStream_append__pyx_kp_35__pyx_f_6cpyamf_4util_11cIndexedMap_clear__pyx_f_6cpyamf_4util_19cBufferedByteStream_read_double__pyx_f_6cpyamf_4util_18cIndexedCollection_clear__pyx_pf_6cpyamf_4util_18cIndexedCollection___iter____pyx_f_6cpyamf_4util_11cIndexedMap_map__pyx_kp_59__pyx_builtin_RuntimeError__pyx_f_6cpyamf_4util_11cIndexedMap_append__pyx_kp_58__pyx_tp_dealloc_6cpyamf_4util_cIndexedCollection__pyx_tp_dealloc_6cpyamf_4util_cIndexedMap__pyx_tp_dealloc_6cpyamf_4util_cBufferedByteStream__pyx_f_6cpyamf_4util_19cBufferedByteStream_read_utf8_string__pyx_kp_32__pyx_k_33__Pyx_SetVtable__pyx_f_6cpyamf_4util_18cIndexedCollection__ref__pyx_builtin_id__pyx_f_6cpyamf_4util_18cIndexedCollection__increase_size__pyx_f_6cpyamf_4util_19cBufferedByteStream__increase_buffer__pyx_f_6cpyamf_4util_19cBufferedByteStream_write_float__pyx_f_6cpyamf_4util_19cBufferedByteStream_read_float__pyx_f_6cpyamf_4util_19cBufferedByteStream_write_double__pyx_f_6cpyamf_4util_19cBufferedByteStream_write_utf8_string__pyx_kp_34__pyx_tp_traverse_6cpyamf_4util_cIndexedMap__pyx_tp_clear_6cpyamf_4util_cIndexedMap__pyx_pf_6cpyamf_4util_17IndexedCollection___init____pyx_k_13__pyx_k_14__pyx_kp_use_hash__pyx_kp_exceptions__pyx_pyargnames.13724__pyx_pf_6cpyamf_4util_10IndexedMap___init____pyx_k_15__pyx_k_16__pyx_pyargnames.14367__pyx_pf_6cpyamf_4util_18BufferedByteStream_read__pyx_int_neg_1__pyx_kp_size__pyx_pyargnames.11082__pyx_pf_6cpyamf_4util_18BufferedByteStream_write_double__pyx_kp_52__pyx_v_6cpyamf_4util_platform_nan__pyx_int_1__pyx_v_6cpyamf_4util_platform_neginf__pyx_v_6cpyamf_4util_platform_posinf__pyx_setprop_6cpyamf_4util_18BufferedByteStream_endian__pyx_kp_42__pyx_kp_46__pyx_kp_43__pyx_kp_44__pyx_kp_45__pyx_kp_41__pyx_pf_6cpyamf_4util_10IndexedMap_getByReference__pyx_pf_6cpyamf_4util_18cIndexedCollection___getitem____pyx_pf_6cpyamf_4util_10IndexedMap_getMappedByReference__pyx_pf_6cpyamf_4util_17IndexedCollection_getByReference__pyx_kp_56__pyx_pf_6cpyamf_4util_18BufferedByteStream_write_24bit_uint__pyx_filenames__pyx_int_4294967295L__pyx_int_2__pyx_string_tab__pyx_mdoc__pyx_methods__pyx_b__pyx_kp_MemoryError__pyx_kp_IOError__pyx_kp_ValueError__pyx_kp_OverflowError__pyx_kp_TypeError__pyx_kp_id__pyx_kp_NotImplementedError__pyx_kp_RuntimeError__pyx_builtin_NotImplementedError__pyx_skip_dispatch__pyx_vtable_6cpyamf_4util_cBufferedByteStream__pyx_kp___main____pyx_vtable_6cpyamf_4util_cIndexedCollection__pyx_vtable_6cpyamf_4util_cIndexedMap__pyx_vtable_6cpyamf_4util_BufferedByteStream__pyx_ptype_6cpyamf_4util_cIndexedMap__pyx_vtabptr_6cpyamf_4util_BufferedByteStream__pyx_vtable_6cpyamf_4util_IndexedCollection__pyx_ptype_6cpyamf_4util_BufferedByteStream__pyx_vtabptr_6cpyamf_4util_IndexedCollection__pyx_vtable_6cpyamf_4util_IndexedMap__pyx_ptype_6cpyamf_4util_IndexedCollection__pyx_vtabptr_6cpyamf_4util_IndexedMap__pyx_k_10__pyx_ptype_6cpyamf_4util_IndexedMap__pyx_v_6cpyamf_4util_complete_init__pyx_v_6cpyamf_4util_NaN__pyx_k_11__pyx_v_6cpyamf_4util_NegInf__pyx_k_12__pyx_v_6cpyamf_4util_PosInf__pyx_pf_6cpyamf_4util_18BufferedByteStream_write_ulong__pyx_kp_51__pyx_f_6cpyamf_4util_complete_import__pyx_kp_17__pyx_kp_ReferenceError__pyx_kp_util__pyx_kp_NaN__pyx_kp_NegInf__pyx_kp_PosInf__pyx_pf_6cpyamf_4util_19cBufferedByteStream___cinit____pyx_tp_new_6cpyamf_4util_cBufferedByteStream__pyx_tp_new_6cpyamf_4util_BufferedByteStream__pyx_pf_6cpyamf_4util_18BufferedByteStream_write_24bit_int__pyx_pf_6cpyamf_4util_18BufferedByteStream_write_long__pyx_pf_6cpyamf_4util_18BufferedByteStream_read_utf8_string__Pyx_PyInt_AsInt__pyx_pf_6cpyamf_4util_18BufferedByteStream_write_short__pyx_kp_50__pyx_pf_6cpyamf_4util_18BufferedByteStream_write_ushort__pyx_kp_49__pyx_pf_6cpyamf_4util_18BufferedByteStream___add____pyx_pf_6cpyamf_4util_18BufferedByteStream_write_char__pyx_kp_48__pyx_pf_6cpyamf_4util_18BufferedByteStream_write_uchar__pyx_kp_47__pyx_pf_6cpyamf_4util_18BufferedByteStream_seek__pyx_kp_pos__pyx_kp_mode__pyx_pyargnames.11400__pyx_pf_6cpyamf_4util_18BufferedByteStream_truncate__pyx_pyargnames.11584__pyx_pf_6cpyamf_4util_18BufferedByteStream_peek__pyx_pyargnames.11488__pyx_pf_6cpyamf_4util_11cIndexedMap___cinit____pyx_pyargnames.14085__pyx_pf_6cpyamf_4util_18cIndexedCollection___cinit____pyx_pyargnames.13065__pyx_tp_new_6cpyamf_4util_cIndexedCollection__pyx_tp_new_6cpyamf_4util_IndexedCollection__pyx_tp_new_6cpyamf_4util_cIndexedMap__pyx_tp_new_6cpyamf_4util_IndexedMap__pyx_pf_6cpyamf_4util_18cIndexedCollection___richcmp____pyx_tp_as_number_cBufferedByteStream__pyx_tp_as_sequence_cBufferedByteStream__pyx_tp_as_mapping_cBufferedByteStream__pyx_tp_as_buffer_cBufferedByteStream__pyx_methods_6cpyamf_4util_cBufferedByteStream__pyx_tp_as_number_cIndexedCollection__pyx_tp_as_sequence_cIndexedCollection__pyx_tp_as_mapping_cIndexedCollection__pyx_tp_as_buffer_cIndexedCollection__pyx_methods_6cpyamf_4util_cIndexedCollection__pyx_tp_as_number_cIndexedMap__pyx_tp_as_sequence_cIndexedMap__pyx_tp_as_mapping_cIndexedMap__pyx_tp_as_buffer_cIndexedMap__pyx_methods_6cpyamf_4util_cIndexedMap__pyx_tp_as_number_BufferedByteStream__pyx_tp_as_sequence_BufferedByteStream__pyx_tp_as_mapping_BufferedByteStream__pyx_tp_as_buffer_BufferedByteStream__pyx_methods_6cpyamf_4util_BufferedByteStream__pyx_getsets_6cpyamf_4util_BufferedByteStream__pyx_tp_as_number_IndexedCollection__pyx_tp_as_sequence_IndexedCollection__pyx_tp_as_mapping_IndexedCollection__pyx_tp_as_buffer_IndexedCollection__pyx_methods_6cpyamf_4util_IndexedCollection__pyx_getsets_6cpyamf_4util_IndexedCollection__pyx_tp_as_number_IndexedMap__pyx_tp_as_sequence_IndexedMap__pyx_tp_as_mapping_IndexedMap__pyx_tp_as_buffer_IndexedMap__pyx_methods_6cpyamf_4util_IndexedMap__pyx_getsets_6cpyamf_4util_IndexedMap__pyx_k___main____pyx_kp___cinit____pyx_k___cinit____pyx_kp___dealloc____pyx_k___dealloc____pyx_kp___init____pyx_k___init____pyx_k_read__pyx_k_write__pyx_kp_close__pyx_k_close__pyx_kp_flush__pyx_k_flush__pyx_k_tell__pyx_kp_remaining__pyx_k_remaining__pyx_kp___len____pyx_k___len____pyx_k_getvalue__pyx_kp_at_eof__pyx_k_at_eof__pyx_k_seek__pyx_kp_peek__pyx_k_peek__pyx_kp_truncate__pyx_k_truncate__pyx_kp_consume__pyx_k_consume__pyx_kp_read_uchar__pyx_k_read_uchar__pyx_kp_read_char__pyx_k_read_char__pyx_kp_read_ushort__pyx_k_read_ushort__pyx_kp_read_short__pyx_k_read_short__pyx_kp_read_ulong__pyx_k_read_ulong__pyx_kp_read_long__pyx_k_read_long__pyx_kp_3__pyx_k_3__pyx_kp_4__pyx_k_4__pyx_kp_write_uchar__pyx_k_write_uchar__pyx_kp_write_char__pyx_k_write_char__pyx_kp_write_ushort__pyx_k_write_ushort__pyx_kp_write_short__pyx_k_write_short__pyx_kp_write_ulong__pyx_k_write_ulong__pyx_kp_write_long__pyx_k_write_long__pyx_kp_5__pyx_k_5__pyx_kp_6__pyx_k_6__pyx_kp_7__pyx_k_7__pyx_kp_8__pyx_k_8__pyx_kp_read_double__pyx_k_read_double__pyx_kp_write_double__pyx_k_write_double__pyx_kp_read_float__pyx_k_read_float__pyx_kp_write_float__pyx_k_write_float__pyx_kp_append__pyx_k_append__pyx_kp___add____pyx_k___add____pyx_kp___str____pyx_k___str____pyx_kp___iter____pyx_k___iter____pyx_kp___richcmp____pyx_k___richcmp____pyx_kp___getitem____pyx_k___getitem____pyx_kp___copy____pyx_k___copy____pyx_kp_getByReference__pyx_k_getByReference__pyx_kp_getReferenceTo__pyx_k_getReferenceTo__pyx_kp_clear__pyx_k_clear__pyx_kp_9__pyx_k_9__pyx_kp_map__pyx_k_map__pyx_k_buf__pyx_kp_value__pyx_k_value__pyx_k_size__pyx_kp_x__pyx_k_x__pyx_k_pos__pyx_k_mode__pyx_k_obj__pyx_kp_val__pyx_k_val__pyx_kp_data__pyx_k_data__pyx_kp_self__pyx_k_self__pyx_kp_other__pyx_k_other__pyx_k_use_hash__pyx_k_exceptions__pyx_kp_op__pyx_k_op__pyx_kp_idx__pyx_k_idx__pyx_kp_ref__pyx_k_ref__pyx_k_mapped_obj__pyx_k_MemoryError__pyx_k_17__pyx_k_ReferenceError__pyx_k_util__pyx_k_NaN__pyx_k_NegInf__pyx_k_PosInf__pyx_k_IOError__pyx_k_ValueError__pyx_k_OverflowError__pyx_k_TypeError__pyx_k_35__pyx_k_36__pyx_k_37__pyx_k_38__pyx_k_39__pyx_k_id__pyx_k_NotImplementedError__pyx_k_RuntimeError__pyx_k_28__pyx_k_29__pyx_k_30__pyx_k_31__pyx_k_32__pyx_k_34__pyx_k_40__pyx_k_41__pyx_k_42__pyx_k_43__pyx_k_44__pyx_k_45__pyx_k_46__pyx_k_47__pyx_k_48__pyx_k_49__pyx_k_50__pyx_k_51__pyx_k_52__pyx_k_53__pyx_k_54__pyx_k_55__pyx_k_56__pyx_k_57__pyx_k_58__pyx_k_59__pyx_doc_6cpyamf_4util_18BufferedByteStream_read__pyx_doc_6cpyamf_4util_18BufferedByteStream_write__pyx_doc_6cpyamf_4util_18BufferedByteStream_close__pyx_doc_6cpyamf_4util_18BufferedByteStream_tell__pyx_doc_6cpyamf_4util_18BufferedByteStream_remaining__pyx_doc_6cpyamf_4util_18BufferedByteStream_getvalue__pyx_doc_6cpyamf_4util_18BufferedByteStream_at_eof__pyx_doc_6cpyamf_4util_18BufferedByteStream_seek__pyx_doc_6cpyamf_4util_18BufferedByteStream_peek__pyx_doc_6cpyamf_4util_18BufferedByteStream_truncate__pyx_doc_6cpyamf_4util_18BufferedByteStream_consume__pyx_doc_6cpyamf_4util_18BufferedByteStream_read_uchar__pyx_doc_6cpyamf_4util_18BufferedByteStream_read_char__pyx_doc_6cpyamf_4util_18BufferedByteStream_read_ushort__pyx_doc_6cpyamf_4util_18BufferedByteStream_read_short__pyx_doc_6cpyamf_4util_18BufferedByteStream_read_ulong__pyx_doc_6cpyamf_4util_18BufferedByteStream_read_long__pyx_doc_6cpyamf_4util_18BufferedByteStream_read_24bit_uint__pyx_doc_6cpyamf_4util_18BufferedByteStream_read_24bit_int__pyx_doc_6cpyamf_4util_18BufferedByteStream_write_uchar__pyx_doc_6cpyamf_4util_18BufferedByteStream_write_char__pyx_doc_6cpyamf_4util_18BufferedByteStream_write_ushort__pyx_doc_6cpyamf_4util_18BufferedByteStream_write_short__pyx_doc_6cpyamf_4util_18BufferedByteStream_write_ulong__pyx_doc_6cpyamf_4util_18BufferedByteStream_write_long__pyx_doc_6cpyamf_4util_18BufferedByteStream_write_24bit_uint__pyx_doc_6cpyamf_4util_18BufferedByteStream_write_24bit_int__pyx_doc_6cpyamf_4util_18BufferedByteStream_read_utf8_string__pyx_doc_6cpyamf_4util_18BufferedByteStream_write_utf8_string__pyx_doc_6cpyamf_4util_18BufferedByteStream_read_double__pyx_doc_6cpyamf_4util_18BufferedByteStream_write_double__pyx_doc_6cpyamf_4util_18BufferedByteStream_read_float__pyx_doc_6cpyamf_4util_18BufferedByteStream_write_float__pyx_doc_6cpyamf_4util_18BufferedByteStream_append_GLOBAL_OFFSET_TABLE___dso_handle__DTOR_END___DYNAMICPyDict_SetItemStringPyString_InternFromString_Py_ZeroStructPyString_AsStringPyFrame_NewPyClass_Type__pyx_type_6cpyamf_4util_cIndexedCollectionPyType_ReadyPyInstance_TypePyLong_FromUnsignedLongPyMem_FreePyExc_SystemError__gmon_start___Jv_RegisterClassesPyCObject_FromVoidPtr_PyString_Eq_finiPyList_TypePyObject_CallFunctionObjArgsPyObject_IsTruePyExc_TypeErrorPyMem_ReallocPyDict_Type__pyx_type_6cpyamf_4util_cBufferedByteStreamPyObject_HasAttrPyInt_TypePyString_FromStringAndSizePyDict_NextPyImport_AddModulePyUnicodeUCS2_DecodeUTF8PyLong_AsLongPyUnicodeUCS2_AsUTF8StringPyErr_FormatPyFloat_FromDouble_PyFloat_Unpack4PyNumber_LongPyCode_NewPyObject_GetAttrPyErr_Occurred_PyFloat_Unpack8initutil__pyx_type_6cpyamf_4util_IndexedCollection__pyx_type_6cpyamf_4util_IndexedMapPyFloat_Type__cxa_finalize@@GLIBC_2.2.5PyErr_SetObjectPyErr_WriteUnraisablePyUnicode_Type_Py_TrueStructPyString_FromStringPyString_FromFormatPyInt_FromLongPyLong_FromStringPyDict_SizePyModule_GetDictPyDict_GetItemPyErr_RestorePyInt_AsLongPyObject_RichComparePyObject_GetIterPyType_IsSubtype_PyFloat_Pack4memcpy@@GLIBC_2.2.5_PyFloat_Pack8PyTraceBack_Type__pyx_module_is_main_cpyamf__utilPyErr_FetchPyFloat_AsDoublePyObject_HashPyObject_GetAttrString__bss_startPyObject_IsInstancePyLong_TypePyObject_SetAttrString_Py_NoneStructPyExc_OverflowErrorPyList_AppendPyObject_Call__pyx_type_6cpyamf_4util_cIndexedMapPyTraceBack_Here_PyThreadState_Current__pyx_type_6cpyamf_4util_BufferedByteStreamPyExc_NameErrorPy_InitModule4PyString_AsStringAndSize_endPyTuple_NewPyExc_NotImplementedErrorPyErr_SetStringPyString_TypePyNumber_Int_edataPyList_NewPyMem_MallocPyDict_SetItemPyLong_AsUnsignedLong_initPyDict_NewPK:u3;HC<cpyamf/amf3.soELF>@@8@&#d<d< @@ @  0@0@ 0@ PtdX;X;X;44Qtd%6 ($ +5-&034,"./)2'  %1#*!/ A@ /14|CE쀇sqXjn t._l + ?g "2KJ[PB:"hu|8F % F _ 0C, F   80F __gmon_start___init_fini__cxa_finalize_Jv_RegisterClassesPyInt_TypePyType_IsSubtypePyLong_TypePyLong_AsLongPyNumber_IntPyExc_TypeErrorPyErr_FormatPyErr_OccurredPyErr_SetStringPyNumber_LongPyString_FromStringPyModule_GetDictPyString_FromStringAndSizePyCode_New_PyThreadState_CurrentPyFrame_NewPyTraceBack_HerePyString_FromFormatinitamf3PyTuple_NewPyString_InternFromStringPyUnicodeUCS2_DecodeUTF8Py_InitModule4PyImport_AddModulePyObject_SetAttrString__pyx_module_is_main_cpyamf__amf3PyObject_GetAttr_Py_ZeroStructPyExc_NameErrorPyErr_SetObjectPyObject_Call_Py_NoneStructPyClass_TypePyInstance_TypePyMem_MallocPyMem_FreePyExc_OverflowErrorPyInt_FromLongPyDict_SizePyDict_GetItemPyDict_NextPyString_Type_PyString_EqPyString_AsStringlibpthread.so.0libc.so.6_edata__bss_start_endGLIBC_2.2.5ui =(@ 9`C `C D I9D D C D 9D $D 0D E F E F E 9 E xF (E ID @E F HE RD `E F hE TD E F E [D E F E `D E F E kD E F E yD A A A A  A  A  B  B B 5B ! B #(B $0B '8B (@B ,`B hB pB xB B  B B B B B B B B B B B B B B B C C C C  C "(C %0C &8C )@C *HC +PC -XC .H%H5z/ %|/ @%z/ h%r/ h%j/ h%b/ h%Z/ h%R/ h%J/ h%B/ hp%:/ h`%2/ h P%*/ h @%"/ h 0%/ h %/ h % / h%/ h%. h%. h%. h%. h%. h%. h%. h%. hp%. h`%. hP%. h@%. h0%. h %. h%. h%. hHH, HtHÐU=1 HATSubH=, t H=?. H* L%* H0 L)HHXH9s DHBH0 AH0 H9r0 [A\fUH=* Ht"H[, HtH=* IAÐH\$Hl$HLd$Ll$H(HH-, H9u HSHH\$Hl$Ld$Ll$ H(H=uH{L-+ L9u HHl$H\$Ld$Ll$ H()LuH{H9t!HuH{L9t Lt2H8HŋHRHCHP(H@HCH@XHHHL%"HHtoH{H9tHZuH{L9yLAiHCH5"LLL@H* H81CtH5G HHHD$@AE;H5% HHbHcCH HL$@Ll$XLt$`L|$lHD$`HD$XD$lHL$L$LLLHyI$HHt$`H90Lu/fH91D"HH HuH~H+ H9HSL@HHH:H8G;FuHt$`fDHC HD$HHCHD$@SEHD$@Hl$HHD$ rID$H@XH| HJ LH HHS H}L9 LU H}H;|$ Ht$4 HEH5 HHL@H H816EEu HEHP(ZHuH H5xH8(3HA|H H Hu H DLxQH}H- H9HT$HoH,H` HC H  H: ALI|$H  H9HL$<L HHHH H5 H8 H H Hm H EEHEHP(HEHP(DID$LP(D3LH  HD$XH)HL$HHuIMH H5 H8FQHAH H M =H &L4H}HU H9HT$uHIHt$iuH}L9)LPH}H;|$ Ht$/HEH@XHHtrHL%H mHHt{H{L9t)LuH{H;|$tHt$H+IċIHCHP(:HftHL% HHfuH H5H8HdH H5 H8IEH`HCH5 LLL@H H81-uHCHP(뎋SHt$`H I9Ho Hh H8H9t$G;FHI9HH8H9uH- HO$HH5S H81H He q/ {H\ H7tPI$Ht$`H;?H HD$XHL$H)HH_u1Ht$`?H HH5H81VHH8(HKHHI HH5H81Ht$`4HD$HAHt$aH}L9t%LHuH}H;|$tHt$/tjEHHËEEHEHP(LLH}H  H9HL$HH'HEH@XHHHHHHH}L9SLrCH}H;|$4Ht$Q"HEH5HHL@H H81SEE#HEHP(Ht$H}L9LoH}H;|$`Ht$NHEH@XHHt}HHIMI|$L9t*LduI|$H;|$tHt$JLHA$A$ID$LP(zH@tHH7IpZHuH H5mH8(3HuH H5XH8HD$0DHtHxHG H5@H8붃EIID$H5HHL@H H81[A$A$PID$LP(@HtHH/HWRHHs H5aH8Ht$I|$L9t*LuI|$H;|$tHt$vA$LHHËEEHEHP(HtLH_HHH H5H8LLDH}H H9HD$3HIHEH@XHHzHL%HHH{L9)LZH{H;|$ Ht$9HCH5LLL@H H81;u HCHP(aHfDuH H5H80;HDItMxHo H5hH8Ht$|fH}L9t)LauH}H;|$tHt$HEHHIċ0HCHP(!HtHL%7HwZHH{ H5iH8$UHSHHP HtHC HHHuH[ÐHHlongan integer is required%s (%s:%d)__builtin____builtins____name__cpyamf.amf3cpyamf.amf3.encode_int%s() keywords must be stringsat leastat mostcpyamf.amf3.decode_intcpyamf.amf3._decode_intamf3.pyxcpyamf/amf3.c__%s__ returned non-%s (type %.200s)raise: exception must be an old-style class or instance%s() got multiple values for keyword argument '%s'%s() got an unexpected keyword argument '%s'%s() takes %s %d positional argument%s (%d given)value too large to convert to intcan't convert negative value to unsigned charvalue too large to convert to unsigned char;4hPhp(zRx JQ0$<eJ[d8CACD $hrBBA D(D@$Ja9   8Xo  I HB   o ooj o0@ &6FVfv&6FVfv`C C-extension for L{pyamf.amf3} Python module in L{PyAMF}. @since: 0.4 Encode C{int}. @raise OverflowError: Out of range. Decode C{int}. __main__nstreamsignread_ucharOverflowErrorOut of rangeI9C 9$0D F F 9xF ID F RD F TD F [D F `D F kD F yD GCC: (Debian 4.3.3-5) 4.3.3GCC: (Debian 4.3.3-8) 4.3.3GCC: (Debian 4.3.3-8) 4.3.3GCC: (Debian 4.3.3-8) 4.3.3GCC: (Debian 4.3.3-5) 4.3.3L 8,"<*8A)^initamf3)__pyx_module_is_main_cpyamf__amf3/home/aurel32/debian/co-packages/glibc/glibc-2.9/build-tree/amd64-libc/csu/crti.S/home/aurel32/debian/co-packages/glibc/glibc-2.9/csuGNU AS 2.19.1)m8$8afint ii1-o b# # # # +# #( #0 I #8 #@ #H =#P  #X "#` V$#h L&b#p *b#t ,p#x ]0F# 1T# M2# W6# ?{# H# I# J# K# L-# Nb# P# v # # Ob#v  o  b \f5 gb# g'#e xg' b# '# b# # Jb# b#$ d #(  #0  #8   #@  #H $ #P T#X  #` #h  / #p -  #x  $ #   #  # k# i# # #  # !P # $i# ({ #  ) # ,a# J -# '.# /'# U0Y# 1 # /2 # 3i# 4 # 5 # {6 # 7G # 8# 9Y# :Y# A;Y# <Y# 1=Y# !>d #5 h ~CIYYY-djpYYYYYYYA bY bYY#Yb.4YNYbbY_byYbYbYbbYxbYYYbYbC !b6YkAGbaYbaLrxbYYbYA bY0 (_# _# H_# l_# _# L_#( ?#0 j8#8 8#@ 8#H #P H8#X _#` _#h _#p _#x _# # 8# W8# 8# 8#  8# ' _# _# N_# b_# W_# # - _# ,_# _# d _# _# _# c_# a_# {_#) PŲ ư#  _# # # ## N#( y#0 g#8 _#@ 9 #H  ԰# O_# ֩# ׽  < # # # 6# R X d Ao u  Y~  b Y b  Y Yojc   b YYyr&C(: @ iP Y[ a Y{ YYb CC   Y 'YYB  Y'b   < v ,a "# ## $b# %# - f(# )b# *b# +b#doc,#g(. f #get #set $#doc # # BG5 a  b#  '# 2 i# .( #  $b#  $'# $b# %i# K &b# g '#$    b#  '# b#   # Y 5 j@   b#  '# Y# s Y#  Y#  Y#(  Y#0  Y#83 %(   b#  '# / # ! Y# Y#   Y$Y /5bOYY_isH # ! # Y# sY# CY# 0Y#( FY#0 Y#8 |b#@O_ts  3# z4# D 6X# ]7b# " 8b#  9b# <;(#( H <(#0 =Y#8 j >Y#@ r@Y#H ZAY#P  BY#X LDY#` EY#h FY#p v HY#x Jb# 1Kb# >MY# Ni#!O)39bXYXbY^C   b# '# b# oX# |# AY#( Y#0 Y#8 #@ H#H q Y#P JY#X Y#` Y#h #p b#x "b#| #b# %b# &#  'b# 8(b# )b# _*b# S+ #&R b Kp#s#ni# # s# Q#A Bb# Cb#p k  b#  '# | b# Fb# b# *b# Y# Y#( ? Y#0 ,Y#8 Y#@ :Y#H oY#P Y#X b#` Y#h    b#  b# $ b#y vk  ,^:a8)9Y^YYtbYYY Y `YxYmfresY btKU Yv YfYY3 b# !" bQ !""!#JaE! Fb@GHI KZLWL)bxY!valiYf fiKf;g8hi8jk?8lmV nb   & O d z   ii%xY$vali!valitmpY!"p!#z##%&8'j()S(<(r*^P"p+(z(#,J%sX-6J.6 KY.3LYQ.MY.oNY.{ O,.A PXu/bad00s-V Y1   $2 +`3*&4Tb*# +35*@""+p(gYYtbY !"""" !#-#9#E#Q5!Y#?-!Y&-YI.;i=KEY.Y V b.` Yg.Y.) 1S"1v D1 1I<2 "B6##*^0"p+p(z ( #)#2-"S"G";+@7^M*"""" +(-c (9 (EA (Q *" & +0(l #!#-(9#E(QJ#]#i7u7}7773737( ib cYd eY)fghkeyjYjYposkfl 4m  /bad _!"" i Y b;bi1?iV Y` Y?b     VT*? x*Y!val,i5ZY$8%-!ZY-ZYN-ZY .[Y.\Y .]Y^V.V _b.` `iT8aYP1P$1$1v%1 $ 9QP$$Z""""w"k"_)P$$(##2""+@(*"B6"##*^`"p+(z/(x#)1%5%#2 @$"& " +#2 #> (J (V #b (n (z !# # 7 '3 3 3 7 9&2  $" + ( :#* ,"B6 ###*^ "p+P (z.$(w$#)&&#* =" + ( k%*,"B6@$#+##*^"p+(z&(y'#6pq%.f(8)g%6$.vY)*?{"""u"i"]"Q+0(/*(+(;,(,#7m170371:00""8b% E Y%  % ;b 8F ;Y HF ;Y PF ;Y XF ;]b `F ;b 4F ; ;& (@ ;1 hF ;a pF z& N;j& C 8 GY @F & 8N& ID 8OY xF & 8P& RD 8 QY F -' 8R' TD 8SY F i' 8}TY' [D 8UY F ' 8;V' `D 8p WY F ' 8N X' kD 8YY F 8ZY F 8u [Y F I( 8 \9( yD o( A8_( C ( 8 Y( 0D ( 8t( D K( 8:(  E ) 8"-( E o Kb 0F '/home/aurel32/debian/co-packages/glibc/glibc-2.9/build-tree/amd64-libc/csu/crtn.S/home/aurel32/debian/co-packages/glibc/glibc-2.9/csuGNU AS 2.19.1U%% : ; I$ > $ > $ >   I : ;  : ;I8 : ; : ; I8 I !I/ &I : ; ' II : ;  : ; '  : ; : ; I8 : ;I : ; .: ;' : ;I: ;I4: ;I.: ;' I 4: ;I.: ;' : ;! "1#41$ %.1@&1' (41) *1UX Y+ U,.: ;' @-: ;I.4: ;I/ : ;0.? : ;' @1 : ;21UX Y3 141X Y5.: ;' I@6 U7 184: ;I 91X Y:1X Y;4: ; I <4: ; I? < =4: ;I? < >4: ;I?  U%h /home/aurel32/debian/co-packages/glibc/glibc-2.9/build-tree/amd64-libc/csucrti.S  Ku=/0K K 8$K cpyamf/usr/lib/gcc/x86_64-linux-gnu/4.3.3/include/usr/include/bits/usr/include/usr/local/include/python2.3amf3.cstddef.htypes.hstdio.hlibio.hobject.hmethodobject.hstructmember.hdescrobject.hintobject.hstringobject.htupleobject.hclassobject.hpystate.htraceback.hframeobject.hcompile.hboolobject.hlongobject.hpyerrors.h  Jq <wtW*~<$h  Z2&~m %8@g ֱ;=hF\8@/#,].fm<;ugGt~tqt>tT#%xdP0*~ =Jd}7=yJZwU=vptJw X|>%X{t{f>" <  .@zXw< <wJ <>>jX xKfKKKKK==w00(wJ+o3sJh  :&xf'Ytp]z\*%..~J%hy% +;u  u< u J~J%X7K=J|X|F~Xy tf|=  t.~JzqiJ;<-%}@t~<(ytvzt.~Jzh <w Jif .~JzqwX J tJsY;YJzw<!zXLF@#B"}( YWh  >&|fyXHx*~y%~dt{<zX vf0K>0  Z~2ȼ<|X&yf]z~#* Xn$}: .~Jt%h  >&~>0  ~4#f|XzX vXʇt'm#fK~J4~fK~Oh  >&|JzXʇt<2~tȠfKh /home/aurel32/debian/co-packages/glibc/glibc-2.9/build-tree/amd64-libc/csucrtn.S K 8Kx $JQ0,eJ[$0CACD ,rBBA D(D@,$Ja__pyx_mob_item_Py_TrueStructPyExc_OverflowErrorPyClassObjectf_builtinsobjobjprocnb_inplace_remaindernb_dividePyMethodDef__pyx_v_streamtp_richcomparenb_intPyFrameObjectPyInt_Typetp_dealloc_IO_save_endnb_nonzero__pyx_kp_signkwds2num_foundtp_as_sequencetp_reprsq_itemPy_ssize_t_IO_write_base__pyx_string_tab__pyx_v_buf_lockrecursion_depth/home/buildbot/slaves/pyamf/debian64-py23/buildnb_subtractnb_xornum_pos_argstp_bases__pyx_opt_args_6cpyamf_4amf3__decode_inttp_methods__Pyx_ErrRestore_IO_save_basetp_init__pyx_pf_6cpyamf_4amf3_encode_intgetwritebufferproc_chain_cur_column__Pyx_PyInt_AsLongco_argcounttp_weaklistoffsettp_is_gcnb_absolutetp_namef_blockstack_objectgettertp_mronb_floor_divideternaryfuncco_stacksizemp_ass_subscriptob_refcntis_unicode__Pyx_PyInt_AsInt__pyx_k_read_ucharnb_inplace_multiplynb_inplace_divide__pyx_methodsf_exc_value__pyx_L3__pyx_L4__pyx_L5__pyx_L6__pyx_L7__pyx_L8__pyx_L9cl_name_IO_markerf_iblocktp_iter__pyx_kwdsintintargfuncnb_inplace_orf_exc_tracebackhashfuncgilstate_counterallocfuncnb_divmodPyClass_Typenb_true_dividecurexc_typeprintfuncarg_passed_twice_IO_FILEco_lnotab__pyx_v_changedPyBufferProcsPyString_Type__pyx_arg_n__pyx_argscl_setattrtp_docinvalid_keyword_typeunsigned charb_levelco_varnames__pyx_v_bytescodec_search_cache__pyx_f_6cpyamf_4amf3__encode_intnb_inplace_true_dividenb_floattp_free__pyx_t_3__pyx_t_4sq_repeatmp_lengthf_localstp_basenb_inplace_powerf_globalsnb_remainderbf_getwritebufferPyMemberDef__pyx_filenamesob_ivalco_cellvarsco_nlocalsis_identifierinvalid_keywordf_back_IO_lock_tco_freevarsGNU C 4.3.3tp_hashcl_getattrf_lasti__pyx_pf_6cpyamf_4amf3_decode_int__pyx_L0__Pyx_RaiseArgtupleInvalidkw_argsco_code__Pyx_InitGlobals_IO_read_ptrvaluescodec_search_pathPyTypeObject_posstdincurexc_valueob_svalgetattrofuncdlopenflagsPy_tracefuncsq_ass_slice__pyx_optional_argstp_getattrosq_sliceco_name_markers__pyx_L5_argtuple_errorgetreadbufferprocco_firstlinenointintobjargprocreprfunctp_descr_setc_profilefuncf_exc_typetp_dict__pyx_linenonb_negative__pyx_L4_argument_unpacking_donenb_lshiftPyCodeObjectunaryfunctp_traversePyInterpreterStatenewfunccl_delattrtp_as_mappingnb_inplace_subtract__pyx_k_1tp_setattrexactnb_inplace_addpy_srcfiletraverseproc__pyx_k_OverflowErrornb_inplace_xorcl_dictpy_codeclosuretick_counterbf_getreadbuffernb_andtp_strin_weakreflist__pyx_v_icl_bases_flags2getiterfunctmp_tb_IO_read_basesq_concat__pyx_k_2f_nlocals_unused2PyNumberMethodssq_inplace_repeatob_sstatePyExc_NameError_typeobjectf_tracePyTryBlocktp_flagsf_tstate_old_offsetcodec_error_registryco_conststp_compare__Pyx_InitStringsPyIntObjectml_flagsbf_getsegcountcurexc_tracebacklong long inttstate_headnb_inplace_lshiftco_namesc_tracefuncPyLong_TypePyInstance_Type__pyx_kp_read_uchar__pyx_f_6cpyamf_4amf3__decode_intml_meth__Pyx_InitCachedBuiltins_IO_write_endc_profileobjob_sizePyObjectgetsegcountproctp_iternextnb_hextp_clear__pyx_cfilenmtp_callPyCFunctioninquiry_IO_buf_base__pyx_t_1__pyx_t_2c_traceobj__pyx_kp_2raise_error__pyx_L1_errorPyTraceBack_Typenum_expected__pad1__pad2__pad3__pad4__pad5descrsetfunc_sbufnb_positive__pyx_doc_6cpyamf_4amf3_decode_intuse_tracing_PyThreadState_Currentpy_frametp_members__Pyx_GetNamesetattrfunc__pyx_module_is_main_cpyamf__amf3__pyx_kp_nPyMappingMethods__Pyx_ParseOptionalKeywordscoercionob_shash_modef_restrictedf_linenof_nfreevarstp_setattrosq_inplace_concatin_dictkw_name__pyx_filenamenum_minnb_invert_Py_ZeroStructfunc_namegetcharbufferproc__pyx_k_signiternextfunclong doublepy_globals__pyx_empty_tupletmp_type__pyx_v_sizedescrgetfuncvisitproc__pyx_kp_streamnb_coerce__pyx_L10__pyx_L3_errorbf_getcharbuffer__pyx_v_b__pyx_v_n__pyx_v_omp_subscriptlong long unsigned intinterninterpinitproc__off_t__pyx_k_stream__pyx_mdoc__pyx_v_signtp_allocnb_rshift__pyx_k___main____pyx_pyargnamesnb_inplace_andfreefuncf_valuestacksq_contains__pyx_1tp_getsettp_weaklist_IO_backup_base_shortbufnb_longf_stacksizetp_as_bufferobjobjargprocsq_ass_item__pyx_f_next__off64_t__pyx_kp_OverflowErrorrichcmpfuncPyGetSetDef__pyx_n__pyx_r__pyx_skip_dispatchtp_printtp_getattr_IO_buf_endinitamf3PyThreadStatefirst_kw_argtp_cachetp_basicsizemore_or_lessbinaryfuncempty_stringf_codeshort intsetterPySequenceMethodstp_itemsize__pyx_v_count__pyx_builtin_OverflowError__pyx_v_result__Pyx_StringTabEntrynum_maxb_handler_vtable_offset__pyx_selfnb_inplace_rshiftasync_excnb_multiplytp_as_numbernb_inplace_floor_dividesetattrofuncgetattrfuncnb_or__pyx_init_filenamesnb_octmodulesml_doc__pyx_kp___main____pyx_doc_6cpyamf_4amf3_encode_intcpyamf/amf3.c_IO_read_end__pyx_clinenotp_delnb_addin_classf_ncellsdestructor_fileno__Pyx_PyInt_AsUnsignedCharco_filenametp_newsq_lengthob_type__Pyx_AddTraceback__Pyx_Raise__Pyx_RaiseDoubleKeywordsErrorshort unsigned intstdouttp_descr_getPyExc_TypeError_IO_write_ptr__pyx_v_real_valueco_flagspy_funcnamenb_powerf_stacktopf_localsplus__Pyx_PyNumber_Intsysdict_Py_NoneStructtp_subclassestmp_value__pyx_k_nml_namefunction_nametp_dictoffset__pyx_bthread_idww0U7SKtS SSS/KQQQQQQ/<VV/7SS SSPPP/A\\\\%w%ew,U,SSS47P^e^V]]e]nqP_e_P\e\VVeVSSeSpqwqtwtxwxw S(SBS PBIPwwww w(2wUT>V] V V V V  VU  V V T  Vs 2V Sa Sh v S S + S  S , S~ S  S SQ Q Q Q  P S+ d S, S0 s S;>PVs v P S V+ L VL R QR R V, U V V R V R V 0 S0 s VZ p T + T  T , T P P*P \ h \ \ \ s \ \%2\U` U? G U U US Sd S? U S S\ \h \? U \ \P\  P P Pw + w , w 0 w a Sa p Q S + Q S  Q , S U U , UV] V + V  V , V 0 V@kwk"w@UNaU58U@tTtSTSNqTquSuTSTES]4SJfS{MSMUTeS5jSS S TDSIS.S]SSShSSS'kSStSSS5 SU l Sy S@wQw~V&V5=Q=V]V%V w N~]w M~Mew e5~w  ~ Iw I]~~%w ~w ~w "~~&VNVMeVV IV%VVV&PP N~x|P|w,Pw,~PM~MUPUew,e5~ ~I]~~~~"~ UvUUUUXuxSDStSPPP SSES]4SJfS{MSeSS SIS.SSShSitSS5 SU l Sy S 6]s]_{]M]2]25P55]]]]]] "] SNHKSKs]sS4]47S7@^@JSJf^f{S*S*M]e}]}^SPw0P..CSCS^SS5S ]]..ESE]S^F]FaSa]S SNYS|SSw0!P!2w02>S !!!^! "S "" &V&.\Psy\yVP0rVr{\{MVe5VVVIV]VVSVS8V8FSFmVmSVV|\|V\V\>V>\* VU t Vy !V!!S!W"VW""S""V""S""V .\PE0\JM\e\5\\V \s]\\\\ \m\\\|\9\* \* U VU t \t y Vy \ !\!!\ "b"\""\""\ SE4SJfSMSeS SS.SSShS5 U SPU q Py ~ P S]4SJfSMSeS S.SSShS* 5 Sl S .\s\0{\\}\S\E\\\\8a\SY|S \! "\b""\qPPPP|PP !P""P""P .\s\J{\\}\.S\SE\\\ a\m\ YSS>S!!\W"b"\""\.\]\\\Me\@\\ s\\\\\PP%P N]5))T]]TTQQTTTTT%" N]5%" N]5%" S.\]uSu\ES]4SJfS{MSMe\eSQS)\)UQUl\lSSDSDs\sS.S]QSShSS\'S'k\kS\S\%iSi\S\S\5 SU l Sy S88O6G .@`@`@`BiBiBTBTs 2  ~ ~ 2 ~ 2  9 ~  1  S 0 S 0 R R  0 0  h   0    0 ] h U Z  F ]%IPh]%IUh]u%I7it7i7@?5aiHWy"I`h5P!"!I`w5qtZ`TWChPy2T s2T s2E s5 * U *  ~ U b  *  \;R3@!" !]`@!"!! !=8]`0 "" !2a8]`,0]`b"""W" !2YNa8+]`"""W" !2|Na8+]`""""H"W"/">""'"W!!6!M!!.! !2|FN,<$a8a@W+85%`%Q'`Y'`88.symtab.strtab.shstrtab.gnu.hash.dynsym.dynstr.gnu.version.gnu.version_r.rela.dyn.rela.plt.init.text.fini.rodata.eh_frame_hdr.eh_frame.ctors.dtors.jcr.data.rel.ro.dynamic.got.got.plt.data.bss.comment.debug_aranges.debug_pubnames.debug_info.debug_abbrev.debug_line.debug_frame.debug_str.debug_loc.debug_rangesXXto@% -  I5oj j lBo Q [ e`k#q88w288pX;X;4;;@ @@ @ @ @(@ (@0@ 0@A AxHB HB`C `C  F F FFGEGO+ s9Mv'~40?”/JX %\ X j       8 8X;;@ @  @ (@ 0@ A HB `C  F  !"  '@ 5@ C @ P f F u(F  @ `< @  8  ehF 4F HF XF 0`F =(@ K E \E lpF tC OD `PF F F 8F @F xF  rF % $GF [F kF yE C B0D ID F RD TD  [D `D *kD @yD JHB ``C m@ z0@   " 8(8C^j}"*>MYjy 0C0F  F &=M\F am} F  initfini.ccall_gmon_startcrtstuff.c__CTOR_LIST____DTOR_LIST____JCR_LIST____do_global_dtors_auxcompleted.6085dtor_idx.6087frame_dummy__CTOR_END____FRAME_END____JCR_END____do_global_ctors_auxamf3.c__Pyx_PyInt_AsLong__Pyx_AddTraceback__pyx_filename__pyx_clineno__pyx_m__pyx_empty_tuple__pyx_lineno__pyx_cfilenm__pyx_string_tab__pyx_filenames__pyx_f__pyx_mdoc__pyx_methods__pyx_b__pyx_kp_OverflowError__pyx_builtin_OverflowError__pyx_skip_dispatch__pyx_k_1__pyx_kp___main____pyx_pf_6cpyamf_4amf3_encode_int__pyx_kp_2__pyx_pf_6cpyamf_4amf3_decode_int__pyx_kp_read_uchar__pyx_kp_stream__pyx_kp_sign__pyx_pyargnames.8743__pyx_doc_6cpyamf_4amf3_encode_int__pyx_doc_6cpyamf_4amf3_decode_int__pyx_k___main____pyx_kp_n__pyx_k_n__pyx_k_stream__pyx_k_sign__pyx_k_read_uchar__pyx_k_OverflowError__pyx_k_2_GLOBAL_OFFSET_TABLE___dso_handle__DTOR_END___DYNAMICPyString_InternFromString_Py_ZeroStructPyString_AsStringPyFrame_NewPyClass_TypePyInstance_TypePyMem_Free__gmon_start___Jv_RegisterClasses_PyString_Eq_finiPyExc_TypeErrorPyInt_TypePyString_FromStringAndSizePyDict_NextPyImport_AddModulePyUnicodeUCS2_DecodeUTF8PyLong_AsLongPyErr_FormatPyNumber_LongPyCode_NewPyObject_GetAttrPyErr_Occurred__cxa_finalize@@GLIBC_2.2.5PyErr_SetObjectPyString_FromStringPyString_FromFormatPyInt_FromLongPyDict_SizePyModule_GetDictPyDict_GetIteminitamf3PyType_IsSubtype__pyx_module_is_main_cpyamf__amf3__bss_startPyLong_TypePyObject_SetAttrString_Py_NoneStructPyExc_OverflowErrorPyObject_CallPyTraceBack_Here_PyThreadState_CurrentPyExc_NameErrorPy_InitModule4_endPyTuple_NewPyErr_SetStringPyString_TypePyNumber_Int_edataPyMem_Malloc_initPK:u3;>v cpyamf/__init__.pyc; VJc@s dZdS(s7 Python C-extensions for L{PyAMF}. @since: 0.4 N(s__doc__(((s/build/bdist.linux-x86_64/egg/cpyamf/__init__.pys?sPK:u3;%cpyamf/util.pydef __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__,'util.so') __loader__ = None; del __bootstrap__, __loader__ imp.load_dynamic(__name__,__file__) __bootstrap__() PK:u3;Gcpyamf/amf3.pydef __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__,'amf3.so') __loader__ = None; del __bootstrap__, __loader__ imp.load_dynamic(__name__,__file__) __bootstrap__() PK:u3; ,,cpyamf/util.pyc; ߴJc@sdatdS(cCsMdk}dk}dk}|itdatabb|i ttdS(Nsutil.so( ssyss pkg_resourcessimpsresource_filenames__name__s__file__sNones __loader__s __bootstrap__s load_dynamic(s pkg_resourcesssyssimp((s+build/bdist.linux-x86_64/egg/cpyamf/util.pys __bootstrap__s  N(s __bootstrap__(((s+build/bdist.linux-x86_64/egg/cpyamf/util.pys?s PK:u3;i,,cpyamf/amf3.pyc; ߴJc@sdatdS(cCsMdk}dk}dk}|itdatabb|i ttdS(Nsamf3.so( ssyss pkg_resourcessimpsresource_filenames__name__s__file__sNones __loader__s __bootstrap__s load_dynamic(s pkg_resourcesssyssimp((s+build/bdist.linux-x86_64/egg/cpyamf/amf3.pys __bootstrap__s  N(s __bootstrap__(((s+build/bdist.linux-x86_64/egg/cpyamf/amf3.pys?s PK.; sC pyamf/sol.py# -*- coding: utf-8 -*- # # Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Local Shared Object implementation. Local Shared Object (LSO), sometimes known as Adobe Flash cookies, is a cookie-like data entity used by the Adobe Flash Player and Gnash. The players allow web content to read and write LSO data to the computer's local drive on a per-domain basis. @see: U{Local Shared Object on WikiPedia (external) } @see: U{Local Shared Object envelope (external) } @since: 0.1.0 """ import pyamf from pyamf import util #: Magic Number - 2 bytes HEADER_VERSION = '\x00\xbf' #: Marker - 10 bytes HEADER_SIGNATURE = 'TCSO\x00\x04\x00\x00\x00\x00' #: Padding - 4 bytes PADDING_BYTE = '\x00' def decode(stream, strict=True): """ Decodes a SOL stream. C{strict} mode ensures that the sol stream is as spec compatible as possible. @param strict: Ensure that the SOL stream is as spec compatible as possible. @type strict: C{bool} @return: A C{tuple} containing the C{root_name} and a C{dict} of name, value pairs. @rtype: C{tuple} @raise DecodeError: Unknown SOL version in header. @raise DecodeError: Inconsistent stream header length. @raise DecodeError: Invalid signature. @raise DecodeError: Invalid padding read. @raise DecodeError: Missing padding byte. """ if not isinstance(stream, util.BufferedByteStream): stream = util.BufferedByteStream(stream) # read the version version = stream.read(2) if version != HEADER_VERSION: raise pyamf.DecodeError('Unknown SOL version in header') # read the length length = stream.read_ulong() if strict and stream.remaining() != length: raise pyamf.DecodeError('Inconsistent stream header length') # read the signature signature = stream.read(10) if signature != HEADER_SIGNATURE: raise pyamf.DecodeError('Invalid signature') length = stream.read_ushort() root_name = stream.read_utf8_string(length) # read padding if stream.read(3) != PADDING_BYTE * 3: raise pyamf.DecodeError('Invalid padding read') decoder = pyamf.get_decoder(stream.read_uchar()) decoder.stream = stream values = {} while 1: if stream.at_eof(): break name = decoder.readString() value = decoder.readElement() # read the padding if stream.read(1) != PADDING_BYTE: raise pyamf.DecodeError('Missing padding byte') values[name] = value return (root_name, values) def encode(name, values, strict=True, encoding=pyamf.AMF0): """ Produces a SharedObject encoded stream based on the name and values. @param name: The root name of the SharedObject. @type name: C{basestring} @param values: A C{dict} of name value pairs to be encoded in the stream. @type values: C{dict} @param strict: Ensure that the SOL stream is as spec compatible as possible. @type strict: C{bool} @return: A SharedObject encoded stream. @rtype: L{BufferedByteStream} """ encoder = pyamf.get_encoder(encoding) encoder.stream = stream = util.BufferedByteStream() # write the header stream.write(HEADER_VERSION) if strict is True: length_pos = stream.tell() stream.write_ulong(0) # write the signature stream.write(HEADER_SIGNATURE) # write the root name if not isinstance(name, unicode): name = unicode(name) stream.write_ushort(len(name)) stream.write_utf8_string(name) # write the padding stream.write(PADDING_BYTE * 3) stream.write_uchar(encoding) for n, v in values.iteritems(): encoder.writeString(n, writeType=False) encoder.writeElement(v) # write the padding stream.write(PADDING_BYTE) if strict: stream.seek(length_pos) stream.write_ulong(stream.remaining() - 4) stream.seek(0) return stream def load(name_or_file): """ Loads a sol file and returns a L{SOL} object. @param name_or_file: Name of file, or file-object. @type name_or_file: C{str} or C{StringIO} @raise ValueError: Readable stream expected. """ f = name_or_file opened = False if isinstance(name_or_file, basestring): f = open(name_or_file, 'rb') opened = True elif not hasattr(f, 'read'): raise ValueError('Readable stream expected') name, values = decode(f.read()) s = SOL(name) for n, v in values.iteritems(): s[n] = v if opened is True: f.close() return s def save(sol, name_or_file, encoding=pyamf.AMF0): """ Writes a L{SOL} object to C{name_or_file}. @param sol: @type sol: @param name_or_file: Name of file, or file-object. @type name_or_file: C{str} or C{StringIO} @param encoding: AMF encoding type. @type encoding: C{int} @raise ValueError: Writable stream expected. """ f = name_or_file opened = False if isinstance(name_or_file, basestring): f = open(name_or_file, 'wb+') opened = True elif not hasattr(f, 'write'): raise ValueError('Writable stream expected') f.write(encode(sol.name, sol, encoding=encoding).getvalue()) if opened: f.close() class SOL(dict): """ Local Shared Object class, allows easy manipulation of the internals of a C{sol} file. """ def __init__(self, name): self.name = name def save(self, name_or_file, encoding=pyamf.AMF0): save(self, name_or_file, encoding) def __repr__(self): return '<%s %s %s at 0x%x>' % (self.__class__.__name__, self.name, dict.__repr__(self), id(self)) LSO = SOL PK p3;wVVpyamf/__init__.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ B{PyAMF} provides B{A}ction B{M}essage B{F}ormat (U{AMF}) support for Python that is compatible with the Adobe U{Flash Player}. @copyright: Copyright (c) 2007-2009 The PyAMF Project. All Rights Reserved. @contact: U{users@pyamf.org} @see: U{http://pyamf.org} @since: October 2007 @version: 0.5.1 @status: Production/Stable """ import types import inspect from pyamf import util from pyamf.adapters import register_adapters try: set except NameError: from sets import Set as set __all__ = [ 'register_class', 'register_class_loader', 'encode', 'decode', '__version__' ] #: PyAMF version number. __version__ = (0, 5, 1) #: Class mapping support. CLASS_CACHE = {} #: Class loaders. CLASS_LOADERS = [] #: Custom type map. TYPE_MAP = {} #: Maps error classes to string codes. ERROR_CLASS_MAP = {} #: Alias mapping support ALIAS_TYPES = {} #: Specifies that objects are serialized using AMF for ActionScript 1.0 #: and 2.0 that were introduced in the Adobe Flash Player 6. AMF0 = 0 #: Specifies that objects are serialized using AMF for ActionScript 3.0 #: that was introduced in the Adobe Flash Player 9. AMF3 = 3 #: Supported AMF encoding types. ENCODING_TYPES = (AMF0, AMF3) #: Default encoding DEFAULT_ENCODING = AMF0 class ClientTypes: """ Typecodes used to identify AMF clients and servers. @see: U{Adobe Flash Player on WikiPedia (external) } @see: U{Adobe Flash Media Server on WikiPedia (external) } """ #: Specifies a Adobe Flash Player 6.0 - 8.0 client. Flash6 = 0 #: Specifies a Adobe FlashCom / Flash Media Server client. FlashCom = 1 #: Specifies a Adobe Flash Player 9.0 client or newer. Flash9 = 3 #: List of AMF client typecodes. CLIENT_TYPES = [] for x in ClientTypes.__dict__: if not x.startswith('_'): CLIENT_TYPES.append(ClientTypes.__dict__[x]) del x class UndefinedType(object): def __repr__(self): return 'pyamf.Undefined' #: Represents the C{undefined} value in a Adobe Flash Player client. Undefined = UndefinedType() class BaseError(Exception): """ Base AMF Error. All AMF related errors should be subclassed from this class. """ class DecodeError(BaseError): """ Raised if there is an error in decoding an AMF data stream. """ class EOStream(BaseError): """ Raised if the data stream has come to a natural end. """ class ReferenceError(BaseError): """ Raised if an AMF data stream refers to a non-existent object or string reference. """ class EncodeError(BaseError): """ Raised if the element could not be encoded to the stream. @bug: See U{Docuverse blog (external) } for more info about the empty key string array bug. """ class ClassAliasError(BaseError): """ Generic error for anything class alias related. """ class UnknownClassAlias(ClassAliasError): """ Raised if the AMF stream specifies an Actionscript class that does not have a Python class alias. @see: L{register_class} """ class BaseContext(object): """ I hold the AMF context for en/decoding streams. @ivar objects: An indexed collection of referencable objects encountered during en/decoding. @type objects: L{util.IndexedCollection} @ivar class_aliases: A L{dict} of C{class} to L{ClassAlias} @ivar exceptions: If C{True} then reference errors will be propagated. @type exceptions: C{bool} """ def __init__(self, exceptions=True): self.objects = util.IndexedCollection(exceptions=False) self.clear() self.exceptions = exceptions def clear(self): """ Completely clears the context. """ self.objects.clear() self.class_aliases = {} def getObject(self, ref): """ Gets an object based on a reference. @raise ReferenceError: Unknown object reference, if L{exceptions} is C{True}, otherwise C{None} will be returned. """ o = self.objects.getByReference(ref) if o is None and self.exceptions: raise ReferenceError("Unknown object reference %r" % (ref,)) return o def getObjectReference(self, obj): """ Gets a reference for an object. @raise ReferenceError: Object not a valid reference, """ o = self.objects.getReferenceTo(obj) if o is None and self.exceptions: raise ReferenceError("Object %r not a valid reference" % (obj,)) return o def addObject(self, obj): """ Adds a reference to C{obj}. @type obj: C{mixed} @param obj: The object to add to the context. @rtype: C{int} @return: Reference to C{obj}. """ return self.objects.append(obj) def getClassAlias(self, klass): """ Gets a class alias based on the supplied C{klass}. """ try: return self.class_aliases[klass] except KeyError: pass try: self.class_aliases[klass] = get_class_alias(klass) except UnknownClassAlias: # no alias has been found yet .. check subclasses alias = util.get_class_alias(klass) self.class_aliases[klass] = alias(klass) return self.class_aliases[klass] def __copy__(self): raise NotImplementedError class ASObject(dict): """ This class represents a Flash Actionscript Object (typed or untyped). I supply a C{__builtin__.dict} interface to support C{get}/C{setattr} calls. @raise AttributeError: Unknown attribute. """ class __amf__: dynamic = True def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) def __getattr__(self, k): try: return self[k] except KeyError: raise AttributeError('Unknown attribute \'%s\'' % (k,)) def __setattr__(self, k, v): self[k] = v def __repr__(self): return dict.__repr__(self) def __hash__(self): return id(self) class MixedArray(dict): """ Used to be able to specify the C{mixedarray} type. """ class ClassAlias(object): """ Class alias. Provides class/instance meta data to the En/Decoder to allow fine grain control and some performance increases. """ def __init__(self, klass, alias=None, **kwargs): if not isinstance(klass, (type, types.ClassType)): raise TypeError('klass must be a class type, got %r' % type(klass)) self.checkClass(klass) self.klass = klass self.alias = alias self.static_attrs = kwargs.get('static_attrs', None) self.exclude_attrs = kwargs.get('exclude_attrs', None) self.readonly_attrs = kwargs.get('readonly_attrs', None) self.proxy_attrs = kwargs.get('proxy_attrs', None) self.amf3 = kwargs.get('amf3', None) self.external = kwargs.get('external', None) self.dynamic = kwargs.get('dynamic', None) self._compiled = False self.anonymous = False self.sealed = None if self.alias is None: self.anonymous = True # we don't set this to None because AMF3 untyped objects have a # class name of '' self.alias = '' else: if self.alias == '': raise ValueError('Cannot set class alias as \'\'') if not kwargs.get('defer', False): self.compile() def _checkExternal(self): if not hasattr(self.klass, '__readamf__'): raise AttributeError("An externalised class was specified, but" " no __readamf__ attribute was found for %r" % (self.klass,)) if not hasattr(self.klass, '__writeamf__'): raise AttributeError("An externalised class was specified, but" " no __writeamf__ attribute was found for %r" % (self.klass,)) if not isinstance(self.klass.__readamf__, types.UnboundMethodType): raise TypeError("%s.__readamf__ must be callable" % ( self.klass.__name__,)) if not isinstance(self.klass.__writeamf__, types.UnboundMethodType): raise TypeError("%s.__writeamf__ must be callable" % ( self.klass.__name__,)) def compile(self): """ This compiles the alias into a form that can be of most benefit to the en/decoder. """ if self._compiled: return self.decodable_properties = set() self.encodable_properties = set() self.inherited_dynamic = None self.inherited_sealed = None self.exclude_attrs = set(self.exclude_attrs or []) self.readonly_attrs = set(self.readonly_attrs or []) self.static_attrs = set(self.static_attrs or []) self.proxy_attrs = set(self.proxy_attrs or []) if self.external: self._checkExternal() self._finalise_compile() # this class is external so no more compiling is necessary return self.sealed = util.is_class_sealed(self.klass) if hasattr(self.klass, '__slots__'): self.decodable_properties.update(self.klass.__slots__) self.encodable_properties.update(self.klass.__slots__) for k, v in self.klass.__dict__.iteritems(): if not isinstance(v, property): continue if v.fget: self.encodable_properties.update([k]) if v.fset: self.decodable_properties.update([k]) else: self.readonly_attrs.update([k]) mro = inspect.getmro(self.klass)[1:] try: self._compile_base_class(mro[0]) except IndexError: pass self.getCustomProperties() self._finalise_compile() def _compile_base_class(self, klass): if klass is object: return try: alias = get_class_alias(klass) except UnknownClassAlias: alias = register_class(klass) alias.compile() if alias.exclude_attrs: self.exclude_attrs.update(alias.exclude_attrs) if alias.readonly_attrs: self.readonly_attrs.update(alias.readonly_attrs) if alias.static_attrs: self.static_attrs.update(alias.static_attrs) if alias.proxy_attrs: self.proxy_attrs.update(alias.proxy_attrs) if alias.encodable_properties: self.encodable_properties.update(alias.encodable_properties) if alias.decodable_properties: self.decodable_properties.update(alias.decodable_properties) if self.amf3 is None and alias.amf3: self.amf3 = alias.amf3 if self.dynamic is None and alias.dynamic is not None: self.inherited_dynamic = alias.dynamic if alias.sealed is not None: self.inherited_sealed = alias.sealed def _finalise_compile(self): if self.dynamic is None: self.dynamic = True if self.inherited_dynamic is not None: if self.inherited_dynamic is False and not self.sealed and self.inherited_sealed: self.dynamic = True else: self.dynamic = self.inherited_dynamic if self.sealed: self.dynamic = False if self.amf3 is None: self.amf3 = False if self.external is None: self.external = False if not self.static_attrs: self.static_attrs = None else: self.encodable_properties.update(self.static_attrs) self.decodable_properties.update(self.static_attrs) if self.static_attrs is not None: if self.exclude_attrs: self.static_attrs.difference_update(self.exclude_attrs) self.static_attrs = list(self.static_attrs) self.static_attrs.sort() if not self.exclude_attrs: self.exclude_attrs = None else: self.encodable_properties.difference_update(self.exclude_attrs) self.decodable_properties.difference_update(self.exclude_attrs) if self.exclude_attrs is not None: self.exclude_attrs = list(self.exclude_attrs) self.exclude_attrs.sort() if not self.readonly_attrs: self.readonly_attrs = None else: self.decodable_properties.difference_update(self.readonly_attrs) if self.readonly_attrs is not None: self.readonly_attrs = list(self.readonly_attrs) self.readonly_attrs.sort() if not self.proxy_attrs: self.proxy_attrs = None else: if not self.amf3: raise ClassAliasError('amf3 = True must be specified for ' 'classes with proxied attributes. Attribute = %r, ' 'Class = %r' % (self.proxy_attrs, self.klass,)) self.proxy_attrs = list(self.proxy_attrs) self.proxy_attrs.sort() if len(self.decodable_properties) == 0: self.decodable_properties = None else: self.decodable_properties = list(self.decodable_properties) self.decodable_properties.sort() if len(self.encodable_properties) == 0: self.encodable_properties = None else: self.encodable_properties = list(self.encodable_properties) self.encodable_properties.sort() self.non_static_encodable_properties = None if self.encodable_properties: self.non_static_encodable_properties = set(self.encodable_properties) if self.static_attrs: self.non_static_encodable_properties.difference_update(self.static_attrs) self.shortcut_encode = True if self.encodable_properties or self.static_attrs or self.exclude_attrs: self.shortcut_encode = False self._compiled = True def is_compiled(self): return self._compiled def __str__(self): return self.alias def __repr__(self): return '' % ( self.alias, self.klass, id(self)) def __eq__(self, other): if isinstance(other, basestring): return self.alias == other elif isinstance(other, self.__class__): return self.klass == other.klass elif isinstance(other, (type, types.ClassType)): return self.klass == other else: return False def __hash__(self): return id(self) def checkClass(self, klass): """ This function is used to check if the class being aliased fits certain criteria. The default is to check that the C{__init__} constructor does not pass in arguments. @since: 0.4 @raise TypeError: C{__init__} doesn't support additional arguments """ # Check that the constructor of the class doesn't require any additonal # arguments. if not (hasattr(klass, '__init__') and hasattr(klass.__init__, 'im_func')): return klass_func = klass.__init__.im_func # built-in classes don't have func_code if hasattr(klass_func, 'func_code') and ( klass_func.func_code.co_argcount - len(klass_func.func_defaults or []) > 1): args = list(klass_func.func_code.co_varnames) values = list(klass_func.func_defaults or []) if not values: sign = "%s.__init__(%s)" % (klass.__name__, ", ".join(args)) else: named_args = zip(args[len(args) - len(values):], values) sign = "%s.%s.__init__(%s, %s)" % ( klass.__module__, klass.__name__, ", ".join(args[:0-len(values)]), ", ".join(map(lambda x: "%s=%s" % x, named_args))) raise TypeError("__init__ doesn't support additional arguments: %s" % sign) def getEncodableAttributes(self, obj, codec=None): """ Returns a C{tuple} containing a dict of static and dynamic attributes for an object to encode. @param codec: An optional argument that will contain the en/decoder instance calling this function. @since: 0.5 """ if not self._compiled: self.compile() static_attrs = {} dynamic_attrs = {} if self.static_attrs: for attr in self.static_attrs: try: static_attrs[attr] = getattr(obj, attr) except AttributeError: static_attrs[attr] = Undefined if not self.dynamic: if self.non_static_encodable_properties: for attr in self.non_static_encodable_properties: dynamic_attrs[attr] = getattr(obj, attr) if not static_attrs: static_attrs = None if not dynamic_attrs: dynamic_attrs = None return static_attrs, dynamic_attrs dynamic_props = util.get_properties(obj) if not self.shortcut_encode: dynamic_props = set(dynamic_props) if self.encodable_properties: dynamic_props.update(self.encodable_properties) if self.static_attrs: dynamic_props.difference_update(self.static_attrs) if self.exclude_attrs: dynamic_props.difference_update(self.exclude_attrs) if self.klass is dict: for attr in dynamic_props: dynamic_attrs[attr] = obj[attr] else: for attr in dynamic_props: dynamic_attrs[attr] = getattr(obj, attr) if self.proxy_attrs is not None: if static_attrs: for k, v in static_attrs.copy().iteritems(): if k in self.proxy_attrs: static_attrs[k] = self.getProxiedAttribute(k, v) if dynamic_attrs: for k, v in dynamic_attrs.copy().iteritems(): if k in self.proxy_attrs: dynamic_attrs[k] = self.getProxiedAttribute(k, v) if not static_attrs: static_attrs = None if not dynamic_attrs: dynamic_attrs = None return static_attrs, dynamic_attrs def getDecodableAttributes(self, obj, attrs, codec=None): """ Returns a dictionary of attributes for C{obj} that has been filtered, based on the supplied C{attrs}. This allows for fine grain control over what will finally end up on the object or not .. @param obj: The reference object. @param attrs: The attrs dictionary that has been decoded. @param codec: An optional argument that will contain the codec instance calling this function. @return: A dictionary of attributes that can be applied to C{obj} @since: 0.5 """ if not self._compiled: self.compile() changed = False props = set(attrs.keys()) if self.static_attrs: missing_attrs = [] for p in self.static_attrs: if p not in props: missing_attrs.append(p) if missing_attrs: raise AttributeError('Static attributes %r expected ' 'when decoding %r' % (missing_attrs, self.klass)) if not self.dynamic: if not self.decodable_properties: props = set() else: props.intersection_update(self.decodable_properties) changed = True if self.readonly_attrs: props.difference_update(self.readonly_attrs) changed = True if self.exclude_attrs: props.difference_update(self.exclude_attrs) changed = True if self.proxy_attrs is not None: from pyamf import flex for k in self.proxy_attrs: try: v = attrs[k] except KeyError: continue attrs[k] = flex.unproxy_object(v) if not changed: return attrs a = {} [a.__setitem__(p, attrs[p]) for p in props] return a def getProxiedAttribute(self, attr, obj): """ Returns the proxied equivalent for C{obj}. @param attr: The attribute of the proxy request. Useful for class introspection. @type attr: C{str} @param obj: The object to proxy. @return: The proxied object or the original object if it cannot be proxied. """ # the default is to just check basic types from pyamf import flex if type(obj) is list: return flex.ArrayCollection(obj) elif type(obj) is dict: return flex.ObjectProxy(obj) return obj def applyAttributes(self, obj, attrs, codec=None): """ Applies the collection of attributes C{attrs} to aliased object C{obj}. Called when decoding reading aliased objects from an AMF byte stream. Override this to provide fine grain control of application of attributes to C{obj}. @param codec: An optional argument that will contain the en/decoder instance calling this function. """ attrs = self.getDecodableAttributes(obj, attrs, codec=codec) util.set_attrs(obj, attrs) def getCustomProperties(self): """ Overrride this to provide known static properties based on the aliased class. @since: 0.5 """ def createInstance(self, codec=None, *args, **kwargs): """ Creates an instance of the klass. @return: Instance of C{self.klass}. """ return self.klass(*args, **kwargs) class TypedObject(dict): """ This class is used when a strongly typed object is decoded but there is no registered class to apply it to. This object can only be used for 'simple' streams - i.e. not externalized data. If encountered, a L{DecodeError} will be raised. @ivar alias: The alias of the typed object. @type alias: C{unicode} @since: 0.4 """ def __init__(self, alias): dict.__init__(self) self.alias = alias def __readamf__(self, o): raise DecodeError('Unable to decode an externalised stream with ' 'class alias \'%s\'.\n\nThe class alias was found and because ' 'strict mode is False an attempt was made to decode the object ' 'automatically. To decode this stream, a registered class with ' 'the alias and a corresponding __readamf__ method will be ' 'required.' % (self.alias,)) def __writeamf__(self, o): raise EncodeError('Unable to encode an externalised stream with ' 'class alias \'%s\'.\n\nThe class alias was found and because ' 'strict mode is False an attempt was made to encode the object ' 'automatically. To encode this stream, a registered class with ' 'the alias and a corresponding __readamf__ method will be ' 'required.' % (self.alias,)) class TypedObjectClassAlias(ClassAlias): """ @since: 0.4 """ klass = TypedObject def __init__(self, klass, alias, *args, **kwargs): # klass attr is ignored ClassAlias.__init__(self, self.klass, alias) def createInstance(self, codec=None): return self.klass(self.alias) def checkClass(kls, klass): pass class ErrorAlias(ClassAlias): """ Adapts Python exception objects to Adobe Flash Player error objects. @since: 0.5 """ def getCustomProperties(self): self.exclude_attrs.update(['args']) def getEncodableAttributes(self, obj, **kwargs): sa, da = ClassAlias.getEncodableAttributes(self, obj, **kwargs) if not da: da = {} da['message'] = str(obj) da['name'] = obj.__class__.__name__ return sa, da class BaseDecoder(object): """ Base AMF decoder. @ivar context_class: The context for the decoding. @type context_class: An instance of C{BaseDecoder.context_class} @ivar type_map: @type type_map: C{list} @ivar stream: The underlying data stream. @type stream: L{BufferedByteStream} @ivar strict: Defines how strict the decoding should be. For the time being this relates to typed objects in the stream that do not have a registered alias. Introduced in 0.4. @type strict: C{bool} @ivar timezone_offset: The offset from UTC for any datetime objects being decoded. Default to C{None} means no offset. @type timezone_offset: L{datetime.timedelta} """ context_class = BaseContext type_map = {} def __init__(self, stream=None, context=None, strict=False, timezone_offset=None): if isinstance(stream, util.BufferedByteStream): self.stream = stream else: self.stream = util.BufferedByteStream(stream) if context is None: self.context = self.context_class() else: self.context = context self.context.exceptions = False self.strict = strict self.timezone_offset = timezone_offset def readElement(self): """ Reads an AMF3 element from the data stream. @raise DecodeError: The ActionScript type is unsupported. @raise EOStream: No more data left to decode. """ pos = self.stream.tell() try: t = self.stream.read(1) except IOError: raise EOStream try: func = getattr(self, self.type_map[t]) except KeyError: raise DecodeError("Unsupported ActionScript type %r" % (t,)) try: return func() except IOError: self.stream.seek(pos) raise def __iter__(self): try: while 1: yield self.readElement() except EOStream: raise StopIteration class CustomTypeFunc(object): """ Custom type mappings. """ def __init__(self, encoder, func): self.encoder = encoder self.func = func def __call__(self, data, *args, **kwargs): self.encoder.writeElement(self.func(data, encoder=self.encoder)) class BaseEncoder(object): """ Base AMF encoder. @ivar type_map: A list of types -> functions. The types is a list of possible instances or functions to call (that return a C{bool}) to determine the correct function to call to encode the data. @type type_map: C{list} @ivar context_class: Holds the class that will create context objects for the implementing C{Encoder}. @type context_class: C{type} or C{types.ClassType} @ivar stream: The underlying data stream. @type stream: L{BufferedByteStream} @ivar context: The context for the encoding. @type context: An instance of C{BaseEncoder.context_class} @ivar strict: Whether the encoder should operate in 'strict' mode. Nothing is really affected by this for the time being - its just here for flexibility. @type strict: C{bool}, default is False. @ivar timezone_offset: The offset from UTC for any datetime objects being encoded. Default to C{None} means no offset. @type timezone_offset: L{datetime.timedelta} """ context_class = BaseContext type_map = [] def __init__(self, stream=None, context=None, strict=False, timezone_offset=None): if isinstance(stream, util.BufferedByteStream): self.stream = stream else: self.stream = util.BufferedByteStream(stream) if context is None: self.context = self.context_class() else: self.context = context self.context.exceptions = False self._write_elem_func_cache = {} self.strict = strict self.timezone_offset = timezone_offset def writeFunc(self, obj, **kwargs): """ Not possible to encode functions. @raise EncodeError: Unable to encode function/methods. """ raise EncodeError("Unable to encode function/methods") def _getWriteElementFunc(self, data): """ Gets a function used to encode the data. @type data: C{mixed} @param data: Python data. @rtype: callable or C{None}. @return: The function used to encode data to the stream. """ for type_, func in TYPE_MAP.iteritems(): try: if isinstance(data, type_): return CustomTypeFunc(self, func) except TypeError: if callable(type_) and type_(data): return CustomTypeFunc(self, func) for tlist, method in self.type_map: for t in tlist: try: if isinstance(data, t): return getattr(self, method) except TypeError: if callable(t) and t(data): return getattr(self, method) return None def _writeElementFunc(self, data): """ Gets a function used to encode the data. @type data: C{mixed} @param data: Python data. @rtype: callable or C{None}. @return: The function used to encode data to the stream. """ try: key = data.__class__ except AttributeError: return self._getWriteElementFunc(data) try: return self._write_elem_func_cache[key] except KeyError: self._write_elem_func_cache[key] = self._getWriteElementFunc(data) return self._write_elem_func_cache[key] def writeElement(self, data): """ Writes the data. Overridden in subclass. @type data: C{mixed} @param data: The data to be encoded to the data stream. """ raise NotImplementedError def register_class(klass, alias=None): """ Registers a class to be used in the data streaming. @return: The registered L{ClassAlias}. """ meta = util.get_class_meta(klass) if alias is not None: meta['alias'] = alias alias_klass = util.get_class_alias(klass) x = alias_klass(klass, defer=True, **meta) if not x.anonymous: CLASS_CACHE[x.alias] = x CLASS_CACHE[klass] = x return x def unregister_class(alias): """ Deletes a class from the cache. If C{alias} is a class, the matching alias is found. @type alias: C{class} or C{str} @param alias: Alias for class to delete. @raise UnknownClassAlias: Unknown alias. """ try: x = CLASS_CACHE[alias] except KeyError: raise UnknownClassAlias('Unknown alias %r' % (alias,)) if not x.anonymous: del CLASS_CACHE[x.alias] del CLASS_CACHE[x.klass] return x def get_class_alias(klass): """ Finds the alias registered to the class. @type klass: C{object} or class object. @return: The class alias linked to C{klass}. @rtype: L{ClassAlias} @raise UnknownClassAlias: Class not found. """ if isinstance(klass, basestring): try: return CLASS_CACHE[klass] except KeyError: return load_class(klass) if not isinstance(klass, (type, types.ClassType)): if isinstance(klass, types.InstanceType): klass = klass.__class__ elif isinstance(klass, types.ObjectType): klass = type(klass) try: return CLASS_CACHE[klass] except KeyError: raise UnknownClassAlias('Unknown alias for %r' % (klass,)) def register_class_loader(loader): """ Registers a loader that is called to provide the C{Class} for a specific alias. The L{loader} is provided with one argument, the C{Class} alias. If the loader succeeds in finding a suitable class then it should return that class, otherwise it should return C{None}. @type loader: C{callable} @raise TypeError: The C{loader} is not callable. @raise ValueError: The C{loader} is already registered. """ if not callable(loader): raise TypeError("loader must be callable") if loader in CLASS_LOADERS: raise ValueError("loader has already been registered") CLASS_LOADERS.append(loader) def unregister_class_loader(loader): """ Unregisters a class loader. @type loader: C{callable} @param loader: The object to be unregistered @raise LookupError: The C{loader} was not registered. """ if loader not in CLASS_LOADERS: raise LookupError("loader not found") CLASS_LOADERS.remove(loader) def get_module(mod_name): """ Load a module based on C{mod_name}. @type mod_name: C{str} @param mod_name: The module name. @return: Module. @raise ImportError: Unable to import an empty module. """ if mod_name is '': raise ImportError("Unable to import empty module") mod = __import__(mod_name) components = mod_name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod def load_class(alias): """ Finds the class registered to the alias. The search is done in order: 1. Checks if the class name has been registered via L{register_class} or L{register_package}. 2. Checks all functions registered via L{register_class_loader}. 3. Attempts to load the class via standard module loading techniques. @type alias: C{str} @param alias: The class name. @raise UnknownClassAlias: The C{alias} was not found. @raise TypeError: Expecting class type or L{ClassAlias} from loader. @return: Class registered to the alias. """ alias = str(alias) # Try the CLASS_CACHE first try: return CLASS_CACHE[alias] except KeyError: pass # Check each CLASS_LOADERS in turn for loader in CLASS_LOADERS: klass = loader(alias) if klass is None: continue if isinstance(klass, (type, types.ClassType)): return register_class(klass, alias) elif isinstance(klass, ClassAlias): CLASS_CACHE[str(alias)] = klass CLASS_CACHE[klass.klass] = klass return klass else: raise TypeError("Expecting class type or ClassAlias from loader") # XXX nick: Are there security concerns for loading classes this way? mod_class = alias.split('.') if mod_class: module = '.'.join(mod_class[:-1]) klass = mod_class[-1] try: module = get_module(module) except (ImportError, AttributeError): # XXX What to do here? pass else: klass = getattr(module, klass) if isinstance(klass, (type, types.ClassType)): return register_class(klass, alias) elif isinstance(klass, ClassAlias): CLASS_CACHE[str(alias)] = klass CLASS_CACHE[klass.klass] = klass return klass.klass else: raise TypeError("Expecting class type or ClassAlias from loader") # All available methods for finding the class have been exhausted raise UnknownClassAlias("Unknown alias for %r" % (alias,)) def decode(*args, **kwargs): """ A generator function to decode a datastream. @kwarg stream: AMF data. @type stream: L{BufferedByteStream} @type encoding: C{int} @kwarg encoding: AMF encoding type. @type context: L{AMF0 Context} or L{AMF3 Context} @kwarg context: Context. @return: Each element in the stream. """ encoding = kwargs.pop('encoding', DEFAULT_ENCODING) decoder = _get_decoder_class(encoding)(*args, **kwargs) while 1: try: yield decoder.readElement() except EOStream: break def encode(*args, **kwargs): """ A helper function to encode an element. @type args: C{mixed} @keyword element: Python data. @type encoding: C{int} @keyword encoding: AMF encoding type. @type context: L{amf0.Context} or L{amf3.Context} @keyword context: Context. @rtype: C{StringIO} @return: File-like object. """ encoding = kwargs.pop('encoding', DEFAULT_ENCODING) encoder = _get_encoder_class(encoding)(**kwargs) stream = encoder.stream for el in args: encoder.writeElement(el) stream.seek(0) return stream def get_decoder(encoding, *args, **kwargs): """ Returns a subclassed instance of L{pyamf.BaseDecoder}, based on C{encoding} """ return _get_decoder_class(encoding)(*args, **kwargs) def _get_decoder_class(encoding): """ Get compatible decoder. @type encoding: C{int} @param encoding: AMF encoding version. @raise ValueError: AMF encoding version is unknown. @rtype: L{amf0.Decoder} or L{amf3.Decoder} @return: AMF0 or AMF3 decoder. """ if encoding == AMF0: from pyamf import amf0 return amf0.Decoder elif encoding == AMF3: from pyamf import amf3 return amf3.Decoder raise ValueError("Unknown encoding %s" % (encoding,)) def get_encoder(encoding, *args, **kwargs): """ Returns a subclassed instance of L{pyamf.BaseEncoder}, based on C{encoding} """ return _get_encoder_class(encoding)(*args, **kwargs) def _get_encoder_class(encoding): """ Get compatible encoder. @type encoding: C{int} @param encoding: AMF encoding version. @raise ValueError: AMF encoding version is unknown. @rtype: L{amf0.Encoder} or L{amf3.Encoder} @return: AMF0 or AMF3 encoder. """ if encoding == AMF0: from pyamf import amf0 return amf0.Encoder elif encoding == AMF3: from pyamf import amf3 return amf3.Encoder raise ValueError("Unknown encoding %s" % (encoding,)) def get_context(encoding, **kwargs): return _get_context_class(encoding)(**kwargs) def _get_context_class(encoding): """ Gets a compatible context class. @type encoding: C{int} @param encoding: AMF encoding version. @raise ValueError: AMF encoding version is unknown. @rtype: L{amf0.Context} or L{amf3.Context} @return: AMF0 or AMF3 context class. """ if encoding == AMF0: from pyamf import amf0 return amf0.Context elif encoding == AMF3: from pyamf import amf3 return amf3.Context raise ValueError("Unknown encoding %s" % (encoding,)) def blaze_loader(alias): """ Loader for BlazeDS framework compatibility classes, specifically implementing C{ISmallMessage}. @see: U{BlazeDS (external)} @since: 0.5 """ if alias not in ['DSC', 'DSK']: return import pyamf.flex.messaging return CLASS_CACHE[alias] def flex_loader(alias): """ Loader for L{Flex} framework compatibility classes. @raise UnknownClassAlias: Trying to load unknown Flex compatibility class. """ if not alias.startswith('flex.'): return try: if alias.startswith('flex.messaging.messages'): import pyamf.flex.messaging elif alias.startswith('flex.messaging.io'): import pyamf.flex elif alias.startswith('flex.data.messages'): import pyamf.flex.data return CLASS_CACHE[alias] except KeyError: raise UnknownClassAlias(alias) def add_type(type_, func=None): """ Adds a custom type to L{TYPE_MAP}. A custom type allows fine grain control of what to encode to an AMF data stream. @raise TypeError: Unable to add as a custom type (expected a class or callable). @raise KeyError: Type already exists. """ def _check_type(type_): if not (isinstance(type_, (type, types.ClassType)) or callable(type_)): raise TypeError(r'Unable to add '%r' as a custom type (expected a ' 'class or callable)' % (type_,)) if isinstance(type_, list): type_ = tuple(type_) if type_ in TYPE_MAP: raise KeyError('Type %r already exists' % (type_,)) if isinstance(type_, types.TupleType): for x in type_: _check_type(x) else: _check_type(type_) TYPE_MAP[type_] = func def get_type(type_): """ Gets the declaration for the corresponding custom type. @raise KeyError: Unknown type. """ if isinstance(type_, list): type_ = tuple(type_) for (k, v) in TYPE_MAP.iteritems(): if k == type_: return v raise KeyError("Unknown type %r" % (type_,)) def remove_type(type_): """ Removes the custom type declaration. @return: Custom type declaration. """ declaration = get_type(type_) del TYPE_MAP[type_] return declaration def add_error_class(klass, code): """ Maps an exception class to a string code. Used to map remoting C{onStatus} objects to an exception class so that an exception can be built to represent that error:: class AuthenticationError(Exception): pass An example: C{add_error_class(AuthenticationError, 'Auth.Failed')} @type code: C{str} @raise TypeError: C{klass} must be a C{class} type. @raise TypeError: Error classes must subclass the C{__builtin__.Exception} class. @raise ValueError: Code is already registered. """ if not isinstance(code, basestring): code = str(code) if not isinstance(klass, (type, types.ClassType)): raise TypeError("klass must be a class type") mro = inspect.getmro(klass) if not Exception in mro: raise TypeError('Error classes must subclass the __builtin__.Exception class') if code in ERROR_CLASS_MAP.keys(): raise ValueError('Code %s is already registered' % (code,)) ERROR_CLASS_MAP[code] = klass def remove_error_class(klass): """ Removes a class from C{ERROR_CLASS_MAP}. @raise ValueError: Code is not registered. @raise ValueError: Class is not registered. @raise TypeError: Invalid type, expected C{class} or C{string}. """ if isinstance(klass, basestring): if not klass in ERROR_CLASS_MAP.keys(): raise ValueError('Code %s is not registered' % (klass,)) elif isinstance(klass, (type, types.ClassType)): classes = ERROR_CLASS_MAP.values() if not klass in classes: raise ValueError('Class %s is not registered' % (klass,)) klass = ERROR_CLASS_MAP.keys()[classes.index(klass)] else: raise TypeError("Invalid type, expected class or string") del ERROR_CLASS_MAP[klass] def register_alias_type(klass, *args): """ This function allows you to map subclasses of L{ClassAlias} to classes listed in C{args}. When an object is read/written from/to the AMF stream, a paired L{ClassAlias} instance is created (or reused), based on the Python class of that object. L{ClassAlias} provides important metadata for the class and can also control how the equivalent Python object is created, how the attributes are applied etc. Use this function if you need to do something non-standard. @see: L{pyamf.adapters._google_appengine_ext_db.DataStoreClassAlias} for a good example. @since: 0.4 @raise RuntimeError: Type is already registered. @raise TypeError: C{klass} must be a class. @raise ValueError: New aliases must subclass L{pyamf.ClassAlias}. @raise ValueError: At least one type must be supplied. """ def check_type_registered(arg): # FIXME: Create a reverse index of registered types and do a quicker lookup for k, v in ALIAS_TYPES.iteritems(): for kl in v: if arg is kl: raise RuntimeError('%r is already registered under %r' % (arg, k)) if not isinstance(klass, (type, types.ClassType)): raise TypeError('klass must be class') if not issubclass(klass, ClassAlias): raise ValueError('New aliases must subclass pyamf.ClassAlias') if len(args) == 0: raise ValueError('At least one type must be supplied') if len(args) == 1 and callable(args[0]): c = args[0] check_type_registered(c) else: for arg in args: if not isinstance(arg, (type, types.ClassType)): raise TypeError('%r must be class' % (arg,)) check_type_registered(arg) ALIAS_TYPES[klass] = args def register_package(module=None, package=None, separator='.', ignore=[], strict=True): """ This is a helper function that takes the concept of Actionscript packages and registers all the classes in the supplied Python module under that package. It auto-aliased all classes in C{module} based on C{package}. e.g. C{mymodule.py}:: class User(object): pass class Permission(object): pass >>> import mymodule >>> pyamf.register_package(mymodule, 'com.example.app') Now all instances of C{mymodule.User} will appear in Actionscript under the alias 'com.example.app.User'. Same goes for C{mymodule.Permission} - the Actionscript alias is 'com.example.app.Permission'. The reverse is also true, any objects with the correct aliases will now be instances of the relevant Python class. This function respects the C{__all__} attribute of the module but you can have further control of what not to auto alias by populating the C{ignore} argument. This function provides the ability to register the module it is being called in, an example: >>> class Foo: ... pass ... >>> class Bar: ... pass ... >>> import pyamf >>> pyamf.register_package('foo') You can also supply a list of classes to register. An example, taking the above classes: >>> import pyamf >>> pyamf.register_package([Foo, Bar], 'foo') @param module: The Python module that will contain all the classes to auto alias. @type module: C{module} or C{dict} @param package: The base package name. e.g. 'com.example.app'. If this is C{None} then the value is inferred from module.__name__. @type package: C{str} or C{unicode} or C{None} @param separator: The separator used to append to C{package} to form the complete alias. @type separator: C{str} @param ignore: To give fine grain control over what gets aliased and what doesn't, supply a list of classes that you B{do not} want to be aliased. @type ignore: C{iterable} @param strict: If this value is C{True} then only classes that originate from C{module} will be registered, all others will be left in peace. @type strict: C{bool} @return: A collection of all the classes that were registered and their respective L{ClassAlias} objects. @since: 0.5 """ if isinstance(module, basestring): if module == '': raise TypeError('Cannot get list of classes from %r' % (module,)) package = module module = None if module is None: import inspect prev_frame = inspect.stack()[1][0] module = prev_frame.f_locals if type(module) is dict: has = lambda x: x in module.keys() get = module.__getitem__ elif type(module) is list: has = lambda x: x in module get = module.__getitem__ strict = False else: has = lambda x: hasattr(module, x) get = lambda x: getattr(module, x) if package is None: if has('__name__'): package = get('__name__') else: raise TypeError('Cannot get list of classes from %r' % (module,)) if has('__all__'): keys = get('__all__') elif hasattr(module, '__dict__'): keys = module.__dict__.keys() elif hasattr(module, 'keys'): keys = module.keys() elif isinstance(module, list): keys = range(len(module)) else: raise TypeError('Cannot get list of classes from %r' % (module,)) def check_attr(attr): if not isinstance(attr, (types.ClassType, types.TypeType)): return False if attr.__name__ in ignore: return False try: if strict and attr.__module__ != get('__name__'): return False except AttributeError: return False return True # gotta love python classes = filter(check_attr, [get(x) for x in keys]) registered = {} for klass in classes: alias = '%s%s%s' % (package, separator, klass.__name__) registered[klass] = register_class(klass, alias) return registered # init module here register_class(ASObject) register_class_loader(flex_loader) register_class_loader(blaze_loader) register_alias_type(TypedObjectClassAlias, TypedObject) register_alias_type(ErrorAlias, Exception) register_adapters() PK.;kWnhh pyamf/amf0.py# -*- coding: utf-8 -*- # # Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ AMF0 implementation. C{AMF0} supports the basic data types used for the NetConnection, NetStream, LocalConnection, SharedObjects and other classes in the Adobe Flash Player. @see: U{Official AMF0 Specification in English (external) } @see: U{Official AMF0 Specification in Japanese (external) } @see: U{AMF documentation on OSFlash (external) } @since: 0.1 """ import datetime import types import copy import pyamf from pyamf import util #: Represented as 9 bytes: 1 byte for C{0×00} and 8 bytes a double #: representing the value of the number. TYPE_NUMBER = '\x00' #: Represented as 2 bytes: 1 byte for C{0×01} and a second, C{0×00} #: for C{False}, C{0×01} for C{True}. TYPE_BOOL = '\x01' #: Represented as 3 bytes + len(String): 1 byte C{0×02}, then a UTF8 string, #: including the top two bytes representing string length as a C{int}. TYPE_STRING = '\x02' #: Represented as 1 byte, C{0×03}, then pairs of UTF8 string, the key, and #: an AMF element, ended by three bytes, C{0×00} C{0×00} C{0×09}. TYPE_OBJECT = '\x03' #: MovieClip does not seem to be supported by Remoting. #: It may be used by other AMF clients such as SharedObjects. TYPE_MOVIECLIP = '\x04' #: 1 single byte, C{0×05} indicates null. TYPE_NULL = '\x05' #: 1 single byte, C{0×06} indicates null. TYPE_UNDEFINED = '\x06' #: When an ActionScript object refers to itself, such C{this.self = this}, #: or when objects are repeated within the same scope (for example, as the #: two parameters of the same function called), a code of C{0×07} and an #: C{int}, the reference number, are written. TYPE_REFERENCE = '\x07' #: A MixedArray is indicated by code C{0×08}, then a Long representing the #: highest numeric index in the array, or 0 if there are none or they are #: all negative. After that follow the elements in key : value pairs. TYPE_MIXEDARRAY = '\x08' #: @see: L{TYPE_OBJECT} TYPE_OBJECTTERM = '\x09' #: An array is indicated by C{0x0A}, then a Long for array length, then the #: array elements themselves. Arrays are always sparse; values for #: inexistant keys are set to null (C{0×06}) to maintain sparsity. TYPE_ARRAY = '\x0A' #: Date is represented as C{00x0B}, then a double, then an C{int}. The double #: represents the number of milliseconds since 01/01/1970. The C{int} represents #: the timezone offset in minutes between GMT. Note for the latter than values #: greater than 720 (12 hours) are represented as M{2^16} - the value. Thus GMT+1 #: is 60 while GMT-5 is 65236. TYPE_DATE = '\x0B' #: LongString is reserved for strings larger then M{2^16} characters long. It #: is represented as C{00x0C} then a LongUTF. TYPE_LONGSTRING = '\x0C' #: Trying to send values which don’t make sense, such as prototypes, functions, #: built-in objects, etc. will be indicated by a single C{00x0D} byte. TYPE_UNSUPPORTED = '\x0D' #: Remoting Server -> Client only. #: @see: L{RecordSet} #: @see: U{RecordSet structure on OSFlash (external) #: } TYPE_RECORDSET = '\x0E' #: The XML element is indicated by C{00x0F} and followed by a LongUTF containing #: the string representation of the XML object. The receiving gateway may which #: to wrap this string inside a language-specific standard XML object, or simply #: pass as a string. TYPE_XML = '\x0F' #: A typed object is indicated by C{0×10}, then a UTF string indicating class #: name, and then the same structure as a normal C{0×03} Object. The receiving #: gateway may use a mapping scheme, or send back as a vanilla object or #: associative array. TYPE_TYPEDOBJECT = '\x10' #: An AMF message sent from an AVM+ client such as the Flash Player 9 may break #: out into L{AMF3} mode. In this case the next byte will be the #: AMF3 type code and the data will be in AMF3 format until the decoded object #: reaches it’s logical conclusion (for example, an object has no more keys). TYPE_AMF3 = '\x11' class Context(pyamf.BaseContext): """ I hold the AMF0 context for en/decoding streams. AMF0 object references start at index 1. @ivar amf3_objs: A list of objects that have been decoded in L{AMF3}. @type amf3_objs: L{util.IndexedCollection} """ def __init__(self, **kwargs): self.amf3_objs = [] pyamf.BaseContext.__init__(self, **kwargs) def clear(self): """ Clears the context. """ pyamf.BaseContext.clear(self) self.amf3_objs = [] if hasattr(self, 'amf3_context'): self.amf3_context.clear() def hasAMF3ObjectReference(self, obj): """ Gets a reference for an object. @raise ReferenceError: Unknown AMF3 object reference. """ return obj in self.amf3_objs o = self.amf3_objs.getReferenceTo(obj) if o is None and self.exceptions: raise pyamf.ReferenceError( 'Unknown AMF3 reference for (%r)' % (obj,)) return o def addAMF3Object(self, obj): """ Adds an AMF3 reference to C{obj}. @type obj: C{mixed} @param obj: The object to add to the context. @rtype: C{int} @return: Reference to C{obj}. """ return self.amf3_objs.append(obj) def __copy__(self): cpy = self.__class__(exceptions=self.exceptions) cpy.amf3_objs = copy.copy(self.amf3_objs) return cpy class Decoder(pyamf.BaseDecoder): """ Decodes an AMF0 stream. """ context_class = Context # XXX nick: Do we need to support TYPE_MOVIECLIP here? type_map = { TYPE_NUMBER: 'readNumber', TYPE_BOOL: 'readBoolean', TYPE_STRING: 'readString', TYPE_OBJECT: 'readObject', TYPE_NULL: 'readNull', TYPE_UNDEFINED: 'readUndefined', TYPE_REFERENCE: 'readReference', TYPE_MIXEDARRAY: 'readMixedArray', TYPE_ARRAY: 'readList', TYPE_DATE: 'readDate', TYPE_LONGSTRING: 'readLongString', # TODO: do we need a special value here? TYPE_UNSUPPORTED:'readNull', TYPE_XML: 'readXML', TYPE_TYPEDOBJECT:'readTypedObject', TYPE_AMF3: 'readAMF3' } def readNumber(self): """ Reads a ActionScript C{Number} value. In ActionScript 1 and 2 the C{NumberASTypes} type represents all numbers, both floats and integers. @rtype: C{int} or C{float} """ return _check_for_int(self.stream.read_double()) def readBoolean(self): """ Reads a ActionScript C{Boolean} value. @rtype: C{bool} @return: Boolean. """ return bool(self.stream.read_uchar()) def readNull(self): """ Reads a ActionScript C{null} value. @return: C{None} @rtype: C{None} """ return None def readUndefined(self): """ Reads an ActionScript C{undefined} value. @return: L{Undefined} """ return pyamf.Undefined def readMixedArray(self): """ Read mixed array. @rtype: C{dict} @return: C{dict} read from the stream """ len = self.stream.read_ulong() obj = pyamf.MixedArray() self.context.addObject(obj) self._readObject(obj) ikeys = [] for key in obj.keys(): try: ikey = int(key) ikeys.append((key, ikey)) obj[ikey] = obj[key] del obj[key] except ValueError: # XXX: do we want to ignore this? pass ikeys.sort() return obj def readList(self): """ Read a C{list} from the data stream. @rtype: C{list} @return: C{list} """ obj = [] self.context.addObject(obj) len = self.stream.read_ulong() for i in xrange(len): obj.append(self.readElement()) return obj def readTypedObject(self): """ Reads an ActionScript object from the stream and attempts to 'cast' it. @see: L{load_class} """ classname = self.readString() alias = None try: alias = pyamf.get_class_alias(classname) ret = alias.createInstance(codec=self) except pyamf.UnknownClassAlias: if self.strict: raise ret = pyamf.TypedObject(classname) self.context.addObject(ret) self._readObject(ret, alias) return ret def readAMF3(self): """ Read AMF3 elements from the data stream. @rtype: C{mixed} @return: The AMF3 element read from the stream """ if not hasattr(self.context, 'amf3_context'): self.context.amf3_context = pyamf.get_context(pyamf.AMF3, exceptions=False) if not hasattr(self.context, 'amf3_decoder'): self.context.amf3_decoder = pyamf.get_decoder( pyamf.AMF3, self.stream, self.context.amf3_context) decoder = self.context.amf3_decoder element = decoder.readElement() self.context.addAMF3Object(element) return element def readString(self): """ Reads a string from the data stream. @rtype: C{str} @return: string """ len = self.stream.read_ushort() return self.stream.read_utf8_string(len) def _readObject(self, obj, alias=None): obj_attrs = dict() key = self.readString().encode('utf8') while self.stream.peek() != TYPE_OBJECTTERM: obj_attrs[key] = self.readElement() key = self.readString().encode('utf8') # discard the end marker (TYPE_OBJECTTERM) self.stream.read(1) if alias: alias.applyAttributes(obj, obj_attrs, codec=self) else: util.set_attrs(obj, obj_attrs) def readObject(self): """ Reads an object from the data stream. @rtype: L{ASObject} """ obj = pyamf.ASObject() self.context.addObject(obj) self._readObject(obj) return obj def readReference(self): """ Reads a reference from the data stream. @raise pyamf.ReferenceError: Unknown reference. """ idx = self.stream.read_ushort() o = self.context.getObject(idx) if o is None: raise pyamf.ReferenceError('Unknown reference %d' % (idx,)) return o def readDate(self): """ Reads a UTC date from the data stream. Client and servers are responsible for applying their own timezones. Date: C{0x0B T7 T6} .. C{T0 Z1 Z2 T7} to C{T0} form a 64 bit Big Endian number that specifies the number of nanoseconds that have passed since 1/1/1970 0:00 to the specified time. This format is UTC 1970. C{Z1} and C{Z0} for a 16 bit Big Endian number indicating the indicated time's timezone in minutes. """ ms = self.stream.read_double() / 1000.0 tz = self.stream.read_short() # Timezones are ignored d = util.get_datetime(ms) if self.timezone_offset: d = d + self.timezone_offset self.context.addObject(d) return d def readLongString(self): """ Read UTF8 string. """ len = self.stream.read_ulong() return self.stream.read_utf8_string(len) def readXML(self): """ Read XML. """ data = self.readLongString() xml = util.ET.fromstring(data) self.context.addObject(xml) return xml class Encoder(pyamf.BaseEncoder): """ Encodes an AMF0 stream. @ivar use_amf3: A flag to determine whether this encoder knows about AMF3. @type use_amf3: C{bool} """ context_class = Context type_map = [ ((types.BuiltinFunctionType, types.BuiltinMethodType, types.FunctionType, types.GeneratorType, types.ModuleType, types.LambdaType, types.MethodType), "writeFunc"), ((types.NoneType,), "writeNull"), ((bool,), "writeBoolean"), ((int,long,float), "writeNumber"), ((types.StringTypes,), "writeString"), ((pyamf.ASObject,), "writeObject"), ((pyamf.MixedArray,), "writeMixedArray"), ((types.ListType, types.TupleType,), "writeArray"), ((datetime.date, datetime.datetime, datetime.time), "writeDate"), ((util.is_ET_element,), "writeXML"), ((lambda x: x is pyamf.Undefined,), "writeUndefined"), ((types.ClassType, types.TypeType), "writeClass"), ((types.InstanceType,types.ObjectType,), "writeObject"), ] def __init__(self, *args, **kwargs): self.use_amf3 = kwargs.pop('use_amf3', False) pyamf.BaseEncoder.__init__(self, *args, **kwargs) def writeType(self, t): """ Writes the type to the stream. @type t: C{str} @param t: ActionScript type. @raise pyamf.EncodeError: AMF0 type is not recognized. """ self.stream.write(t) def writeUndefined(self, data): """ Writes the L{undefined} data type to the stream. @param data: The C{undefined} data to be encoded to the AMF0 data stream. @type data: C{undefined} data """ self.writeType(TYPE_UNDEFINED) def writeClass(self, *args, **kwargs): """ Classes cannot be serialised. """ raise pyamf.EncodeError("Class objects cannot be serialised") def writeFunc(self, *args, **kwargs): """ Functions cannot be serialised. """ raise pyamf.EncodeError("Callables cannot be serialised") def writeUnsupported(self, data): """ Writes L{unsupported} data type to the stream. @param data: The C{unsupported} data to be encoded to the AMF0 data stream. @type data: C{unsupported} data """ self.writeType(TYPE_UNSUPPORTED) def _writeElementFunc(self, data): """ Gets a function based on the type of data. @see: L{pyamf.BaseEncoder._writeElementFunc} """ # There is a very specific use case that we must check for. # In the context there is an array of amf3_objs that contain # references to objects that are to be encoded in amf3. if self.use_amf3 and self.context.hasAMF3ObjectReference(data): return self.writeAMF3 return pyamf.BaseEncoder._writeElementFunc(self, data) def writeElement(self, data): """ Writes the data. @type data: C{mixed} @param data: The data to be encoded to the AMF0 data stream. @raise EncodeError: Cannot find encoder func. """ func = self._writeElementFunc(data) if func is None: raise pyamf.EncodeError("Cannot find encoder func for %r" % (data,)) func(data) def writeNull(self, n): """ Write null type to data stream. @type n: C{None} @param n: Is ignored. """ self.writeType(TYPE_NULL) def writeArray(self, a): """ Write array to the stream. @type a: L{BufferedByteStream} @param a: The array data to be encoded to the AMF0 data stream. """ alias = self.context.getClassAlias(a.__class__) if alias.external: # a is a subclassed list with a registered alias - push to the # correct method self.writeObject(a) return if self.writeReference(a) is not None: return self.context.addObject(a) self.writeType(TYPE_ARRAY) self.stream.write_ulong(len(a)) for data in a: self.writeElement(data) def writeNumber(self, n): """ Write number to the data stream. @type n: L{BufferedByteStream} @param n: The number data to be encoded to the AMF0 data stream. """ self.writeType(TYPE_NUMBER) self.stream.write_double(float(n)) def writeBoolean(self, b): """ Write boolean to the data stream. @type b: L{BufferedByteStream} @param b: The boolean data to be encoded to the AMF0 data stream. """ self.writeType(TYPE_BOOL) if b: self.stream.write_uchar(1) else: self.stream.write_uchar(0) def writeString(self, s, writeType=True): """ Write string to the data stream. @type s: L{BufferedByteStream} @param s: The string data to be encoded to the AMF0 data stream. @type writeType: C{bool} @param writeType: Write data type. """ t = type(s) if t is str: pass elif isinstance(s, unicode): s = s.encode('utf8') elif not isinstance(s, basestring): s = unicode(s).encode('utf8') l = len(s) if writeType: if l > 0xffff: self.writeType(TYPE_LONGSTRING) else: self.writeType(TYPE_STRING) if l > 0xffff: self.stream.write_ulong(l) else: self.stream.write_ushort(l) self.stream.write(s) def writeReference(self, o): """ Write reference to the data stream. @type o: L{BufferedByteStream} @param o: The reference data to be encoded to the AMF0 data stream. """ idx = self.context.getObjectReference(o) if idx is None: return None self.writeType(TYPE_REFERENCE) self.stream.write_ushort(idx) return idx def _writeDict(self, o): """ Write C{dict} to the data stream. @type o: C{iterable} @param o: The C{dict} data to be encoded to the AMF0 data stream. """ for key, val in o.iteritems(): self.writeString(key, False) self.writeElement(val) def writeMixedArray(self, o): """ Write mixed array to the data stream. @type o: L{BufferedByteStream} @param o: The mixed array data to be encoded to the AMF0 data stream. """ if self.writeReference(o) is not None: return self.context.addObject(o) self.writeType(TYPE_MIXEDARRAY) # TODO: optimise this # work out the highest integer index try: # list comprehensions to save the day max_index = max([y[0] for y in o.items() if isinstance(y[0], (int, long))]) if max_index < 0: max_index = 0 except ValueError: max_index = 0 self.stream.write_ulong(max_index) self._writeDict(o) self._writeEndObject() def _writeEndObject(self): self.stream.write('\x00\x00') self.writeType(TYPE_OBJECTTERM) def writeObject(self, o): """ Write object to the stream. @type o: L{BufferedByteStream} @param o: The object data to be encoded to the AMF0 data stream. """ if self.use_amf3: self.writeAMF3(o) return if self.writeReference(o) is not None: return self.context.addObject(o) alias = self.context.getClassAlias(o.__class__) alias.compile() if alias.amf3: self.writeAMF3(o) return if alias.anonymous: self.writeType(TYPE_OBJECT) else: self.writeType(TYPE_TYPEDOBJECT) self.writeString(alias.alias, False) sa, da = alias.getEncodableAttributes(o, codec=self) if sa: for key in alias.static_attrs: self.writeString(key, False) self.writeElement(sa[key]) if da: for key, value in da.iteritems(): self.writeString(key, False) self.writeElement(value) self._writeEndObject() def writeDate(self, d): """ Writes a date to the data stream. @type d: Instance of C{datetime.datetime} @param d: The date to be encoded to the AMF0 data stream. """ if isinstance(d, datetime.time): raise pyamf.EncodeError('A datetime.time instance was found but ' 'AMF0 has no way to encode time objects. Please use ' 'datetime.datetime instead (got:%r)' % (d,)) # According to the Red5 implementation of AMF0, dates references are # created, but not used. if self.timezone_offset is not None: d -= self.timezone_offset secs = util.get_timestamp(d) tz = 0 self.writeType(TYPE_DATE) self.stream.write_double(secs * 1000.0) self.stream.write_short(tz) def writeXML(self, e): """ Write XML to the data stream. @type e: L{BufferedByteStream} @param e: The XML data to be encoded to the AMF0 data stream. """ if self.use_amf3 is True: self.writeAMF3(e) return self.writeType(TYPE_XML) data = util.ET.tostring(e, 'utf-8') self.stream.write_ulong(len(data)) self.stream.write(data) def writeAMF3(self, data): """ Writes an element to the datastream in L{AMF3} format. @type data: C{mixed} @param data: The data to be encoded to the AMF0 data stream. """ if not hasattr(self.context, 'amf3_context'): self.context.amf3_context = pyamf.get_context(pyamf.AMF3, exceptions=False) if not hasattr(self.context, 'amf3_encoder'): self.context.amf3_encoder = pyamf.get_encoder( pyamf.AMF3, self.stream, self.context.amf3_context) self.context.addAMF3Object(data) encoder = self.context.amf3_encoder self.writeType(TYPE_AMF3) encoder.writeElement(data) def decode(*args, **kwargs): """ A helper function to decode an AMF0 datastream. """ decoder = Decoder(*args, **kwargs) while 1: try: yield decoder.readElement() except pyamf.EOStream: break def encode(*args, **kwargs): """ A helper function to encode an element into the AMF0 format. @type element: C{mixed} @keyword element: The element to encode @type context: L{Context} @keyword context: AMF0 C{Context} to use for the encoding. This holds previously referenced objects etc. @rtype: C{StringIO} @return: The encoded stream. """ encoder = Encoder(**kwargs) for element in args: encoder.writeElement(element) return encoder.stream class RecordSet(object): """ I represent the C{RecordSet} class used in Adobe Flash Remoting to hold (amongst other things) SQL records. @ivar columns: The columns to send. @type columns: List of strings. @ivar items: The C{RecordSet} data. @type items: List of lists, the order of the data corresponds to the order of the columns. @ivar service: Service linked to the C{RecordSet}. @type service: @ivar id: The id of the C{RecordSet}. @type id: C{str} @see: U{RecordSet on OSFlash (external) } """ class __amf__: alias = 'RecordSet' static = ('serverInfo',) dynamic = False def __init__(self, columns=[], items=[], service=None, id=None): self.columns = columns self.items = items self.service = service self.id = id def _get_server_info(self): ret = pyamf.ASObject(totalCount=len(self.items), cursor=1, version=1, initialData=self.items, columnNames=self.columns) if self.service is not None: ret.update({'serviceName': str(self.service['name'])}) if self.id is not None: ret.update({'id':str(self.id)}) return ret def _set_server_info(self, val): self.columns = val['columnNames'] self.items = val['initialData'] try: # TODO nick: find relevant service and link in here. self.service = dict(name=val['serviceName']) except KeyError: self.service = None try: self.id = val['id'] except KeyError: self.id = None serverInfo = property(_get_server_info, _set_server_info) def __repr__(self): ret = '<%s.%s object' % (self.__module__, self.__class__.__name__) if self.id is not None: ret += ' id=%s' % self.id if self.service is not None: ret += ' service=%s' % self.service ret += ' at 0x%x>' % id(self) return ret pyamf.register_class(RecordSet) def _check_for_int(x): """ This is a compatibility function that takes a C{float} and converts it to an C{int} if the values are equal. """ try: y = int(x) except (OverflowError, ValueError): pass else: # There is no way in AMF0 to distinguish between integers and floats if x == x and y == x: return y return x # check for some Python 2.3 problems with floats try: float('nan') except ValueError: pass else: if float('nan') == 0: def check_nan(func): def f2(x): if str(x).lower().find('nan') >= 0: return x return f2.func(x) f2.func = func return f2 _check_for_int = check_nan(_check_for_int) PK.;z pyamf/amf3.py# -*- coding: utf-8 -*- # # Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ AMF3 implementation. C{AMF3} is the default serialization for U{ActionScript} 3.0 and provides various advantages over L{AMF0}, which is used for ActionScript 1.0 and 2.0. It adds support for sending C{int} and C{uint} objects as integers and supports data types that are available only in ActionScript 3.0, such as L{ByteArray} and L{ArrayCollection}. @see: U{Official AMF3 Specification in English (external) } @see: U{Official AMF3 Specification in Japanese (external) } @see: U{AMF3 documentation on OSFlash (external) } @since: 0.1 """ import types import datetime import zlib import pyamf from pyamf import util from pyamf.flex import ObjectProxy, ArrayCollection #: If True encode/decode lists/tuples to L{ArrayCollections} #: and dicts to L{ObjectProxy} use_proxies_default = False try: set() except NameError: from sets import Set as set #: The undefined type is represented by the undefined type marker. No further #: information is encoded for this value. TYPE_UNDEFINED = '\x00' #: The null type is represented by the null type marker. No further #: information is encoded for this value. TYPE_NULL = '\x01' #: The false type is represented by the false type marker and is used to #: encode a Boolean value of C{false}. No further information is encoded for #: this value. TYPE_BOOL_FALSE = '\x02' #: The true type is represented by the true type marker and is used to encode #: a Boolean value of C{true}. No further information is encoded for this #: value. TYPE_BOOL_TRUE = '\x03' #: In AMF 3 integers are serialized using a variable length signed 29-bit #: integer. #: @see: U{Parsing Integers on OSFlash (external) #: } TYPE_INTEGER = '\x04' #: This type is used to encode an ActionScript Number or an ActionScript #: C{int} of value greater than or equal to 2^28 or an ActionScript uint of #: value greater than or equal to 2^29. The encoded value is is always an 8 #: byte IEEE-754 double precision floating point value in network byte order #: (sign bit in low memory). The AMF 3 number type is encoded in the same #: manner as the AMF 0 L{Number} type. TYPE_NUMBER = '\x05' #: ActionScript String values are represented using a single string type in #: AMF 3 - the concept of string and long string types from AMF 0 is not used. #: Strings can be sent as a reference to a previously occurring String by #: using an index to the implicit string reference table. Strings are encoding #: using UTF-8 - however the header may either describe a string literal or a #: string reference. TYPE_STRING = '\x06' #: ActionScript 3.0 introduced a new XML type however the legacy C{XMLDocument} #: type from ActionScript 1.0 and 2.0.is retained in the language as #: C{flash.xml.XMLDocument}. Similar to AMF 0, the structure of an #: C{XMLDocument} needs to be flattened into a string representation for #: serialization. As with other strings in AMF, the content is encoded in #: UTF-8. XMLDocuments can be sent as a reference to a previously occurring #: C{XMLDocument} instance by using an index to the implicit object reference #: table. #: @see: U{OSFlash documentation (external) #: } TYPE_XML = '\x07' #: In AMF 3 an ActionScript Date is serialized simply as the number of #: milliseconds elapsed since the epoch of midnight, 1st Jan 1970 in the #: UTC time zone. Local time zone information is not sent. TYPE_DATE = '\x08' #: ActionScript Arrays are described based on the nature of their indices, #: i.e. their type and how they are positioned in the Array. TYPE_ARRAY = '\x09' #: A single AMF 3 type handles ActionScript Objects and custom user classes. TYPE_OBJECT = '\x0A' #: ActionScript 3.0 introduces a new top-level XML class that supports #: U{E4X} syntax. #: For serialization purposes the XML type needs to be flattened into a #: string representation. As with other strings in AMF, the content is #: encoded using UTF-8. TYPE_XMLSTRING = '\x0B' #: ActionScript 3.0 introduces the L{ByteArray} type to hold an Array #: of bytes. AMF 3 serializes this type using a variable length encoding #: 29-bit integer for the byte-length prefix followed by the raw bytes #: of the L{ByteArray}. #: @see: U{Parsing ByteArrays on OSFlash (external) #: } TYPE_BYTEARRAY = '\x0C' #: Reference bit. REFERENCE_BIT = 0x01 #: The maximum that can be represented by an signed 29 bit integer. MAX_29B_INT = 0x0FFFFFFF #: The minimum that can be represented by an signed 29 bit integer. MIN_29B_INT = -0x10000000 ENCODED_INT_CACHE = {} class ObjectEncoding: """ AMF object encodings. """ #: Property list encoding. #: The remaining integer-data represents the number of class members that #: exist. The property names are read as string-data. The values are then #: read as AMF3-data. STATIC = 0x00 #: Externalizable object. #: What follows is the value of the "inner" object, including type code. #: This value appears for objects that implement IExternalizable, such as #: L{ArrayCollection} and L{ObjectProxy}. EXTERNAL = 0x01 #: Name-value encoding. #: The property names and values are encoded as string-data followed by #: AMF3-data until there is an empty string property name. If there is a #: class-def reference there are no property names and the number of values #: is equal to the number of properties in the class-def. DYNAMIC = 0x02 #: Proxy object. PROXY = 0x03 class DataOutput(object): """ I am a C{StringIO} type object containing byte data from the AMF stream. ActionScript 3.0 introduced the C{flash.utils.ByteArray} class to support the manipulation of raw data in the form of an Array of bytes. I provide a set of methods for writing binary data with ActionScript 3.0. This class is the I/O counterpart to the L{DataInput} class, which reads binary data. @see: U{IDataOutput on Livedocs (external) } """ def __init__(self, encoder): """ @param encoder: Encoder containing the stream. @type encoder: L{amf3.Encoder} """ self.encoder = encoder self.stream = encoder.stream def writeBoolean(self, value): """ Writes a Boolean value. @type value: C{bool} @param value: A C{Boolean} value determining which byte is written. If the parameter is C{True}, C{1} is written; if C{False}, C{0} is written. @raise ValueError: Non-boolean value found. """ if isinstance(value, bool): if value is True: self.stream.write_uchar(1) else: self.stream.write_uchar(0) else: raise ValueError("Non-boolean value found") def writeByte(self, value): """ Writes a byte. @type value: C{int} """ self.stream.write_char(value) def writeUnsignedByte(self, value): """ Writes an unsigned byte. @type value: C{int} @since: 0.5 """ return self.stream.write_uchar(value) def writeDouble(self, value): """ Writes an IEEE 754 double-precision (64-bit) floating point number. @type value: C{number} """ self.stream.write_double(value) def writeFloat(self, value): """ Writes an IEEE 754 single-precision (32-bit) floating point number. @type value: C{float} """ self.stream.write_float(value) def writeInt(self, value): """ Writes a 32-bit signed integer. @type value: C{int} """ self.stream.write_long(value) def writeMultiByte(self, value, charset): """ Writes a multibyte string to the datastream using the specified character set. @type value: C{str} @param value: The string value to be written. @type charset: C{str} @param charset: The string denoting the character set to use. Possible character set strings include C{shift-jis}, C{cn-gb}, C{iso-8859-1} and others. @see: U{Supported character sets on Livedocs (external) } """ self.stream.write(unicode(value).encode(charset)) def writeObject(self, value, use_references=True, use_proxies=None): """ Writes an object to data stream in AMF serialized format. @param value: The object to be serialized. @type use_references: C{bool} @param use_references: """ self.encoder.writeElement(value, use_references, use_proxies) def writeShort(self, value): """ Writes a 16-bit integer. @type value: C{int} @param value: A byte value as an integer. """ self.stream.write_short(value) def writeUnsignedShort(self, value): """ Writes a 16-bit unsigned integer. @type value: C{int} @param value: A byte value as an integer. @since: 0.5 """ self.stream.write_ushort(value) def writeUnsignedInt(self, value): """ Writes a 32-bit unsigned integer. @type value: C{int} @param value: A byte value as an unsigned integer. """ self.stream.write_ulong(value) def writeUTF(self, value): """ Writes a UTF-8 string to the data stream. The length of the UTF-8 string in bytes is written first, as a 16-bit integer, followed by the bytes representing the characters of the string. @type value: C{str} @param value: The string value to be written. """ if not isinstance(value, unicode): value = unicode(value, 'utf8') buf = util.BufferedByteStream() buf.write_utf8_string(value) bytes = buf.getvalue() self.stream.write_ushort(len(bytes)) self.stream.write(bytes) def writeUTFBytes(self, value): """ Writes a UTF-8 string. Similar to L{writeUTF}, but does not prefix the string with a 16-bit length word. @type value: C{str} @param value: The string value to be written. """ val = None if isinstance(value, unicode): val = value else: val = unicode(value, 'utf8') self.stream.write_utf8_string(val) class DataInput(object): """ I provide a set of methods for reading binary data with ActionScript 3.0. This class is the I/O counterpart to the L{DataOutput} class, which writes binary data. @see: U{IDataInput on Livedocs (external) } """ def __init__(self, decoder): """ @param decoder: AMF3 decoder containing the stream. @type decoder: L{amf3.Decoder} """ assert isinstance(decoder, Decoder) self.decoder = decoder self.stream = decoder.stream def readBoolean(self): """ Read C{Boolean}. @raise ValueError: Error reading Boolean. @rtype: C{bool} @return: A Boolean value, C{True} if the byte is nonzero, C{False} otherwise. """ byte = self.stream.read(1) if byte == '\x00': return False elif byte == '\x01': return True else: raise ValueError("Error reading boolean") def readByte(self): """ Reads a signed byte. @rtype: C{int} @return: The returned value is in the range -128 to 127. """ return self.stream.read_char() def readDouble(self): """ Reads an IEEE 754 double-precision floating point number from the data stream. @rtype: C{number} @return: An IEEE 754 double-precision floating point number. """ return self.stream.read_double() def readFloat(self): """ Reads an IEEE 754 single-precision floating point number from the data stream. @rtype: C{number} @return: An IEEE 754 single-precision floating point number. """ return self.stream.read_float() def readInt(self): """ Reads a signed 32-bit integer from the data stream. @rtype: C{int} @return: The returned value is in the range -2147483648 to 2147483647. """ return self.stream.read_long() def readMultiByte(self, length, charset): """ Reads a multibyte string of specified length from the data stream using the specified character set. @type length: C{int} @param length: The number of bytes from the data stream to read. @type charset: C{str} @param charset: The string denoting the character set to use. @rtype: C{str} @return: UTF-8 encoded string. """ #FIXME nick: how to work out the code point byte size (on the fly)? bytes = self.stream.read(length) return unicode(bytes, charset) def readObject(self): """ Reads an object from the data stream. @return: The deserialized object. """ return self.decoder.readElement() def readShort(self): """ Reads a signed 16-bit integer from the data stream. @rtype: C{uint} @return: The returned value is in the range -32768 to 32767. """ return self.stream.read_short() def readUnsignedByte(self): """ Reads an unsigned byte from the data stream. @rtype: C{uint} @return: The returned value is in the range 0 to 255. """ return self.stream.read_uchar() def readUnsignedInt(self): """ Reads an unsigned 32-bit integer from the data stream. @rtype: C{uint} @return: The returned value is in the range 0 to 4294967295. """ return self.stream.read_ulong() def readUnsignedShort(self): """ Reads an unsigned 16-bit integer from the data stream. @rtype: C{uint} @return: The returned value is in the range 0 to 65535. """ return self.stream.read_ushort() def readUTF(self): """ Reads a UTF-8 string from the data stream. The string is assumed to be prefixed with an unsigned short indicating the length in bytes. @rtype: C{str} @return: A UTF-8 string produced by the byte representation of characters. """ length = self.stream.read_ushort() return self.stream.read_utf8_string(length) def readUTFBytes(self, length): """ Reads a sequence of C{length} UTF-8 bytes from the data stream and returns a string. @type length: C{int} @param length: The number of bytes from the data stream to read. @rtype: C{str} @return: A UTF-8 string produced by the byte representation of characters of specified C{length}. """ return self.readMultiByte(length, 'utf-8') class ByteArray(util.BufferedByteStream, DataInput, DataOutput): """ I am a C{StringIO} type object containing byte data from the AMF stream. ActionScript 3.0 introduced the C{flash.utils.ByteArray} class to support the manipulation of raw data in the form of an Array of bytes. Supports C{zlib} compression. Possible uses of the C{ByteArray} class: - Creating a custom protocol to connect to a client. - Writing your own AMF/Remoting packet. - Optimizing the size of your data by using custom data types. @see: U{ByteArray on Livedocs (external) } """ class __amf__: amf3 = True def __init__(self, *args, **kwargs): self.context = kwargs.pop('context', Context()) util.BufferedByteStream.__init__(self, *args, **kwargs) DataInput.__init__(self, Decoder(self, self.context)) DataOutput.__init__(self, Encoder(self, self.context)) self.compressed = False def __cmp__(self, other): if isinstance(other, ByteArray): return cmp(self.getvalue(), other.getvalue()) return cmp(self.getvalue(), other) def __str__(self): buf = self.getvalue() if self.compressed: buf = zlib.compress(buf) #FIXME nick: hacked buf = buf[0] + '\xda' + buf[2:] return buf def compress(self): """ Forces compression of the underlying stream. """ self.compressed = True class ClassDefinition(object): """ """ def __init__(self, alias): self.alias = alias self.reference = None alias.compile() self.attr_len = 0 if alias.static_attrs: self.attr_len = len(alias.static_attrs) self.encoding = ObjectEncoding.DYNAMIC if alias.external: self.encoding = ObjectEncoding.EXTERNAL elif not alias.dynamic: if alias.static_attrs == alias.encodable_properties: self.encoding = ObjectEncoding.STATIC def __repr__(self): return '<%s.ClassDefinition reference=%r encoding=%r alias=%r at 0x%x>' % ( self.__class__.__module__, self.reference, self.encoding, self.alias, id(self)) class Context(pyamf.BaseContext): """ I hold the AMF3 context for en/decoding streams. @ivar strings: A list of string references. @type strings: C{list} @ivar classes: A list of L{ClassDefinition}. @type classes: C{list} @ivar legacy_xml: A list of legacy encoded XML documents. @type legacy_xml: C{list} """ def __init__(self, exceptions=True): self.strings = util.IndexedCollection(use_hash=True, exceptions=False) self.classes = {} self.class_ref = {} self.legacy_xml = util.IndexedCollection(exceptions=False) self.object_aliases = util.IndexedMap(exceptions=False) # Maps one object to another self.class_idx = 0 pyamf.BaseContext.__init__(self, exceptions=exceptions) def clear(self): """ Clears the context. """ pyamf.BaseContext.clear(self) self.strings.clear() self.classes = {} self.class_ref = {} self.legacy_xml.clear() self.object_aliases.clear() self.class_idx = 0 def setObjectAlias(self, obj, alias): """ Maps an object to an aliased object. @since: 0.4 """ self.object_aliases.map(obj, alias) def getObjectAlias(self, obj): """ Get an alias of an object. @since: 0.4 @raise pyamf.ReferenceError: Unknown object alias. @raise pyamf.ReferenceError: Unknown mapped alias. """ ref = self.object_aliases.getReferenceTo(obj) if ref is None: if self.exceptions is False: return None raise pyamf.ReferenceError('Unknown object alias for %r' % (obj,)) mapped = self.object_aliases.getMappedByReference(ref) if mapped is None: if self.exceptions is False: return None raise pyamf.ReferenceError('Unknown mapped alias for %r' % (obj,)) return mapped def getString(self, ref): """ Gets a string based on a reference C{ref}. @param ref: The reference index. @type ref: C{str} @raise pyamf.ReferenceError: The referenced string could not be found. @rtype: C{str} @return: The referenced string. """ i = self.strings.getByReference(ref) if i is None and self.exceptions: raise pyamf.ReferenceError("String reference %r not found" % (ref,)) return i def getStringReference(self, s): """ Return string reference. @type s: C{str} @param s: The referenced string. @raise pyamf.ReferenceError: The string reference could not be found. @return: The reference index to the string. @rtype: C{int} """ i = self.strings.getReferenceTo(s) if i is None and self.exceptions: raise pyamf.ReferenceError("Reference for string %r not found" % (s,)) return i def addString(self, s): """ Creates a reference to C{s}. If the reference already exists, that reference is returned. @type s: C{str} @param s: The string to be referenced. @rtype: C{int} @return: The reference index. @raise TypeError: The parameter C{s} is not of C{basestring} type. @raise pyamf.ReferenceError: Trying to store a reference to an empty string. """ if not isinstance(s, basestring): raise TypeError if len(s) == 0: if not self.exceptions: return None # do not store empty string references raise pyamf.ReferenceError("Cannot store a reference to an empty string") return self.strings.append(s) def getClassByReference(self, ref): """ Return class reference. @raise pyamf.ReferenceError: The class reference could not be found. @return: Class reference. """ try: return self.class_ref[ref] except KeyError: if not self.exceptions: return None raise pyamf.ReferenceError("Class reference %r not found" % ( ref,)) def getClass(self, klass): """ Return class reference. @raise pyamf.ReferenceError: The class reference could not be found. @return: Class reference. """ try: return self.classes[klass] except KeyError: if not self.exceptions: return None raise pyamf.ReferenceError("Class alias for %r not found" % ( klass,)) def addClass(self, alias, klass): """ Creates a reference to C{class_def}. @param alias: C{ClassDefinition} instance. """ ref = self.class_idx self.class_ref[ref] = alias cd = self.classes[klass] = alias cd.reference = ref self.class_idx += 1 return ref def getLegacyXML(self, ref): """ Return the legacy XML reference. This is the C{flash.xml.XMLDocument} class in ActionScript 3.0 and the top-level C{XML} class in ActionScript 1.0 and 2.0. @type ref: C{int} @param ref: The reference index. @raise pyamf.ReferenceError: The legacy XML reference could not be found. @return: Instance of L{ET} """ i = self.legacy_xml.getByReference(ref) if i is None: if not self.exceptions: return None raise pyamf.ReferenceError("Legacy XML reference %r not found" % (ref,)) return i def getLegacyXMLReference(self, doc): """ Return legacy XML reference. @type doc: L{ET} @param doc: The XML document to reference. @raise pyamf.ReferenceError: The reference could not be found. @return: The reference to C{doc}. @rtype: C{int} """ i = self.legacy_xml.getReferenceTo(doc) if i is None: if not self.exceptions: return None raise pyamf.ReferenceError("Reference for document %r not found" % (doc,)) return i def addLegacyXML(self, doc): """ Creates a reference to C{doc}. If C{doc} is already referenced that index will be returned. Otherwise a new index will be created. @type doc: L{ET} @param doc: The XML document to reference. @rtype: C{int} @return: The reference to C{doc}. """ return self.legacy_xml.append(doc) def __copy__(self): return self.__class__(exceptions=self.exceptions) class Decoder(pyamf.BaseDecoder): """ Decodes an AMF3 data stream. """ context_class = Context type_map = { TYPE_UNDEFINED: 'readUndefined', TYPE_NULL: 'readNull', TYPE_BOOL_FALSE: 'readBoolFalse', TYPE_BOOL_TRUE: 'readBoolTrue', TYPE_INTEGER: 'readSignedInteger', TYPE_NUMBER: 'readNumber', TYPE_STRING: 'readString', TYPE_XML: 'readXML', TYPE_DATE: 'readDate', TYPE_ARRAY: 'readArray', TYPE_OBJECT: 'readObject', TYPE_XMLSTRING: 'readXMLString', TYPE_BYTEARRAY: 'readByteArray', } def __init__(self, *args, **kwargs): self.use_proxies = kwargs.pop('use_proxies', use_proxies_default) pyamf.BaseDecoder.__init__(self, *args, **kwargs) def readUndefined(self): """ Read undefined. """ return pyamf.Undefined def readNull(self): """ Read null. @return: C{None} @rtype: C{None} """ return None def readBoolFalse(self): """ Returns C{False}. @return: C{False} @rtype: C{bool} """ return False def readBoolTrue(self): """ Returns C{True}. @return: C{True} @rtype: C{bool} """ return True def readNumber(self): """ Read number. """ return self.stream.read_double() def readUnsignedInteger(self): """ Reads and returns an unsigned integer from the stream. """ return self.readInteger(False) def readSignedInteger(self): """ Reads and returns a signed integer from the stream. """ return self.readInteger(True) def readInteger(self, signed=False): """ Reads and returns an integer from the stream. @type signed: C{bool} @see: U{Parsing integers on OSFlash } for the AMF3 integer data format. """ return decode_int(self.stream, signed) def readString(self, use_references=True): """ Reads and returns a string from the stream. @type use_references: C{bool} """ def readLength(): x = self.readUnsignedInteger() return (x >> 1, x & REFERENCE_BIT == 0) length, is_reference = readLength() if use_references and is_reference: return self.context.getString(length) if length == 0: return u'' result = self.stream.read_utf8_string(length) if len(result) != 0 and use_references: self.context.addString(result) return result def readDate(self): """ Read date from the stream. The timezone is ignored as the date is always in UTC. """ ref = self.readUnsignedInteger() if ref & REFERENCE_BIT == 0: return self.context.getObject(ref >> 1) ms = self.stream.read_double() result = util.get_datetime(ms / 1000.0) if self.timezone_offset is not None: result += self.timezone_offset self.context.addObject(result) return result def readArray(self): """ Reads an array from the stream. @warning: There is a very specific problem with AMF3 where the first three bytes of an encoded empty C{dict} will mirror that of an encoded C{{'': 1, '2': 2}} @see: U{Docuverse blog (external) } """ size = self.readUnsignedInteger() if size & REFERENCE_BIT == 0: return self.context.getObject(size >> 1) size >>= 1 key = self.readString().encode('utf8') if key == '': # integer indexes only -> python list result = [] self.context.addObject(result) for i in xrange(size): result.append(self.readElement()) return result result = pyamf.MixedArray() self.context.addObject(result) while key != "": result[key] = self.readElement() key = self.readString().encode('utf8') for i in xrange(size): el = self.readElement() result[i] = el return result def _getClassDefinition(self, ref): """ Reads class definition from the stream. """ is_ref = ref & REFERENCE_BIT == 0 ref >>= 1 if is_ref: class_def = self.context.getClassByReference(ref) return class_def, class_def.alias name = self.readString() alias = None if name == '': name = pyamf.ASObject try: alias = pyamf.get_class_alias(name) except pyamf.UnknownClassAlias: if self.strict: raise alias = pyamf.TypedObjectClassAlias(pyamf.TypedObject, name) class_def = ClassDefinition(alias) class_def.encoding = ref & 0x03 class_def.attr_len = ref >> 2 class_def.static_properties = [] if class_def.attr_len > 0: for i in xrange(class_def.attr_len): key = self.readString().encode('utf8') class_def.static_properties.append(key) self.context.addClass(class_def, alias.klass) return class_def, alias def readObject(self, use_proxies=None): """ Reads an object from the stream. @raise pyamf.EncodeError: Decoding an object in amf3 tagged as amf0 only is not allowed. @raise pyamf.DecodeError: Unknown object encoding. """ if use_proxies is None: use_proxies = self.use_proxies def readStatic(class_def, obj): for attr in class_def.static_properties: obj[attr] = self.readElement() def readDynamic(class_def, obj): attr = self.readString().encode('utf8') while attr != '': obj[attr] = self.readElement() attr = self.readString().encode('utf8') ref = self.readUnsignedInteger() if ref & REFERENCE_BIT == 0: obj = self.context.getObject(ref >> 1) if use_proxies is True: obj = self.readProxyObject(obj) return obj ref >>= 1 class_def, alias = self._getClassDefinition(ref) obj = alias.createInstance(codec=self) obj_attrs = dict() self.context.addObject(obj) if class_def.encoding in (ObjectEncoding.EXTERNAL, ObjectEncoding.PROXY): obj.__readamf__(DataInput(self)) elif class_def.encoding == ObjectEncoding.DYNAMIC: readStatic(class_def, obj_attrs) readDynamic(class_def, obj_attrs) elif class_def.encoding == ObjectEncoding.STATIC: readStatic(class_def, obj_attrs) else: raise pyamf.DecodeError("Unknown object encoding") alias.applyAttributes(obj, obj_attrs, codec=self) if use_proxies is True: obj = self.readProxyObject(obj) return obj def readProxyObject(self, proxy): """ Return the source object of a proxied object. @since: 0.4 """ if isinstance(proxy, ArrayCollection): return list(proxy) elif isinstance(proxy, ObjectProxy): return proxy._amf_object return proxy def _readXML(self, legacy=False): """ Reads an object from the stream. @type legacy: C{bool} @param legacy: The read XML is in 'legacy' format. """ ref = self.readUnsignedInteger() if ref & REFERENCE_BIT == 0: return self.context.getObject(ref >> 1) xmlstring = self.stream.read(ref >> 1) x = util.ET.fromstring(xmlstring) self.context.addObject(x) if legacy is True: self.context.addLegacyXML(x) return x def readXMLString(self): """ Reads a string from the data stream and converts it into an XML Tree. @return: The XML Document. @rtype: L{ET} """ return self._readXML() def readXML(self): """ Read a legacy XML Document from the stream. @return: The XML Document. @rtype: L{ET} """ return self._readXML(True) def readByteArray(self): """ Reads a string of data from the stream. Detects if the L{ByteArray} was compressed using C{zlib}. @see: L{ByteArray} @note: This is not supported in ActionScript 1.0 and 2.0. """ ref = self.readUnsignedInteger() if ref & REFERENCE_BIT == 0: return self.context.getObject(ref >> 1) buffer = self.stream.read(ref >> 1) try: buffer = zlib.decompress(buffer) compressed = True except zlib.error: compressed = False obj = ByteArray(buffer, context=self.context) obj.compressed = compressed self.context.addObject(obj) return obj class Encoder(pyamf.BaseEncoder): """ Encodes an AMF3 data stream. """ context_class = Context type_map = [ ((types.BuiltinFunctionType, types.BuiltinMethodType, types.FunctionType, types.GeneratorType, types.ModuleType, types.LambdaType, types.MethodType), "writeFunc"), ((bool,), "writeBoolean"), ((types.NoneType,), "writeNull"), ((int,long), "writeInteger"), ((float,), "writeNumber"), (types.StringTypes, "writeString"), ((ByteArray,), "writeByteArray"), ((datetime.date, datetime.datetime, datetime.time), "writeDate"), ((util.is_ET_element,), "writeXML"), ((pyamf.UndefinedType,), "writeUndefined"), ((types.ClassType, types.TypeType), "writeClass"), ((types.InstanceType, types.ObjectType,), "writeInstance"), ] def __init__(self, *args, **kwargs): self.use_proxies = kwargs.pop('use_proxies', use_proxies_default) self.string_references = kwargs.pop('string_references', True) pyamf.BaseEncoder.__init__(self, *args, **kwargs) def writeElement(self, data, use_references=True, use_proxies=None): """ Writes the data. @param data: The data to be encoded to the AMF3 data stream. @type data: C{mixed} @param use_references: Default is C{True}. @type use_references: C{bool} @raise EncodeError: Cannot find encoder func for C{data}. """ func = self._writeElementFunc(data) if func is None: raise pyamf.EncodeError("Unknown type %r" % (data,)) func(data, use_references=use_references, use_proxies=use_proxies) def writeClass(self, *args, **kwargs): """ Classes cannot be serialised. """ raise pyamf.EncodeError("Class objects cannot be serialised") def writeUndefined(self, *args, **kwargs): """ Writes an C{pyamf.Undefined} value to the stream. """ self.stream.write(TYPE_UNDEFINED) def writeNull(self, *args, **kwargs): """ Writes a C{null} value to the stream. """ self.stream.write(TYPE_NULL) def writeBoolean(self, n, **kwargs): """ Writes a Boolean to the stream. """ t = TYPE_BOOL_TRUE if not n: t = TYPE_BOOL_FALSE self.stream.write(t) def _writeInteger(self, n): """ AMF3 integers are encoded. @param n: The integer data to be encoded to the AMF3 data stream. @type n: integer data @see: U{Parsing Integers on OSFlash } for more info. """ try: self.stream.write(ENCODED_INT_CACHE[n]) except KeyError: ENCODED_INT_CACHE[n] = encode_int(n) self.stream.write(ENCODED_INT_CACHE[n]) def writeInteger(self, n, **kwargs): """ Writes an integer to the stream. @type n: integer data @param n: The integer data to be encoded to the AMF3 data stream. @type use_references: C{bool} @kwarg use_references: Default is C{True}. """ if n < MIN_29B_INT or n > MAX_29B_INT: self.writeNumber(float(n)) return self.stream.write(TYPE_INTEGER) self.stream.write(encode_int(n)) def writeNumber(self, n, **kwargs): """ Writes a float to the stream. @type n: C{float} """ self.stream.write(TYPE_NUMBER) self.stream.write_double(n) def _writeString(self, n, **kwargs): """ Writes a raw string to the stream. @type n: C{str} or C{unicode} @param n: The string data to be encoded to the AMF3 data stream. """ if n == '': self.stream.write_uchar(REFERENCE_BIT) return t = type(n) if t is str: bytes = n elif t is unicode: bytes = n.encode('utf8') else: bytes = unicode(n).encode('utf8') n = bytes if self.string_references: ref = self.context.getStringReference(n) if ref is not None: self._writeInteger(ref << 1) return self.context.addString(n) self._writeInteger((len(bytes) << 1) | REFERENCE_BIT) self.stream.write(bytes) def writeString(self, n, writeType=True, **kwargs): """ Writes a string to the stream. If C{n} is not a unicode string, an attempt will be made to convert it. @type n: C{basestring} @param n: The string data to be encoded to the AMF3 data stream. """ if writeType: self.stream.write(TYPE_STRING) self._writeString(n, **kwargs) def writeDate(self, n, use_references=True, **kwargs): """ Writes a C{datetime} instance to the stream. @type n: L{datetime} @param n: The C{Date} data to be encoded to the AMF3 data stream. @type use_references: C{bool} @param use_references: Default is C{True}. """ if isinstance(n, datetime.time): raise pyamf.EncodeError('A datetime.time instance was found but ' 'AMF3 has no way to encode time objects. Please use ' 'datetime.datetime instead (got:%r)' % (n,)) self.stream.write(TYPE_DATE) if use_references is True: ref = self.context.getObjectReference(n) if ref is not None: self._writeInteger(ref << 1) return self.context.addObject(n) self.stream.write_uchar(REFERENCE_BIT) if self.timezone_offset is not None: n -= self.timezone_offset ms = util.get_timestamp(n) self.stream.write_double(ms * 1000.0) def writeList(self, n, use_references=True, use_proxies=None): """ Writes a C{tuple}, C{set} or C{list} to the stream. @type n: One of C{__builtin__.tuple}, C{__builtin__.set} or C{__builtin__.list} @param n: The C{list} data to be encoded to the AMF3 data stream. @type use_references: C{bool} @param use_references: Default is C{True}. """ # Encode lists as ArrayCollections if use_proxies is None: use_proxies = self.use_proxies if use_proxies: ref_obj = self.context.getObjectAlias(n) if ref_obj is None: proxy = ArrayCollection(n) self.context.setObjectAlias(n, proxy) ref_obj = proxy self.writeObject(ref_obj, use_references, use_proxies=False) return self.stream.write(TYPE_ARRAY) if use_references: ref = self.context.getObjectReference(n) if ref is not None: self._writeInteger(ref << 1) return self.context.addObject(n) self._writeInteger((len(n) << 1) | REFERENCE_BIT) self.stream.write_uchar(0x01) [self.writeElement(x) for x in n] def writeDict(self, n, use_references=True, use_proxies=None): """ Writes a C{dict} to the stream. @type n: C{__builtin__.dict} @param n: The C{dict} data to be encoded to the AMF3 data stream. @type use_references: C{bool} @param use_references: Default is C{True}. @raise ValueError: Non C{int}/C{str} key value found in the C{dict} @raise EncodeError: C{dict} contains empty string keys. """ # Design bug in AMF3 that cannot read/write empty key strings # http://www.docuverse.com/blog/donpark/2007/05/14/flash-9-amf3-bug # for more info if '' in n: raise pyamf.EncodeError("dicts cannot contain empty string keys") if use_proxies is None: use_proxies = self.use_proxies if use_proxies is True: ref_obj = self.context.getObjectAlias(n) if ref_obj is None: proxy = ObjectProxy(pyamf.ASObject(n)) self.context.setObjectAlias(n, proxy) ref_obj = proxy self.writeObject(ref_obj, use_references, use_proxies=False) return self.stream.write(TYPE_ARRAY) if use_references: ref = self.context.getObjectReference(n) if ref is not None: self._writeInteger(ref << 1) return self.context.addObject(n) # The AMF3 spec demands that all str based indicies be listed first keys = n.keys() int_keys = [] str_keys = [] for x in keys: if isinstance(x, (int, long)): int_keys.append(x) elif isinstance(x, (str, unicode)): str_keys.append(x) else: raise ValueError("Non int/str key value found in dict") # Make sure the integer keys are within range l = len(int_keys) for x in int_keys: if l < x <= 0: # treat as a string key str_keys.append(x) del int_keys[int_keys.index(x)] int_keys.sort() # If integer keys don't start at 0, they will be treated as strings if len(int_keys) > 0 and int_keys[0] != 0: for x in int_keys: str_keys.append(str(x)) del int_keys[int_keys.index(x)] self._writeInteger(len(int_keys) << 1 | REFERENCE_BIT) for x in str_keys: self._writeString(x) self.writeElement(n[x]) self.stream.write_uchar(0x01) for k in int_keys: self.writeElement(n[k]) def writeInstance(self, obj, **kwargs): """ Read class definition. @param obj: The class instance to be encoded. """ kls = obj.__class__ if kls is pyamf.MixedArray: f = self._write_elem_func_cache[kls] = self.writeDict elif kls in (list, set, tuple): f = self._write_elem_func_cache[kls] = self.writeList else: f = self._write_elem_func_cache[kls] = self.writeObject f(obj, **kwargs) def writeObject(self, obj, use_references=True, use_proxies=None): """ Writes an object to the stream. @param obj: The object data to be encoded to the AMF3 data stream. @type obj: object data @param use_references: Default is C{True}. @type use_references: C{bool} @raise EncodeError: Encoding an object in amf3 tagged as amf0 only. """ if use_proxies is None: use_proxies = self.use_proxies if use_proxies is True and obj.__class__ is dict: ref_obj = self.context.getObjectAlias(obj) if ref_obj is None: proxy = ObjectProxy(obj) self.context.setObjectAlias(obj, proxy) ref_obj = proxy self.writeObject(ref_obj, use_references, use_proxies=False) return self.stream.write(TYPE_OBJECT) if use_references: ref = self.context.getObjectReference(obj) if ref is not None: self._writeInteger(ref << 1) return self.context.addObject(obj) # object is not referenced, serialise it kls = obj.__class__ definition = self.context.getClass(kls) alias = None class_ref = False # if the class definition is a reference if definition: class_ref = True alias = definition.alias if alias.anonymous and definition.reference is not None: class_ref = True else: try: alias = pyamf.get_class_alias(kls) except pyamf.UnknownClassAlias: alias_klass = util.get_class_alias(kls) meta = util.get_class_meta(kls) alias = alias_klass(kls, defer=True, **meta) definition = ClassDefinition(alias) self.context.addClass(definition, alias.klass) if class_ref: self.stream.write(definition.reference) else: ref = 0 if definition.encoding != ObjectEncoding.EXTERNAL: ref += definition.attr_len << 4 final_reference = encode_int(ref | definition.encoding << 2 | REFERENCE_BIT << 1 | REFERENCE_BIT) self.stream.write(final_reference) definition.reference = encode_int( definition.reference << 2 | REFERENCE_BIT) if alias.anonymous: self.stream.write_uchar(0x01) else: self._writeString(alias.alias) # work out what the final reference for the class will be. # this is okay because the next time an object of the same # class is encoded, class_ref will be True and never get here # again. if alias.external: obj.__writeamf__(DataOutput(self)) return sa, da = alias.getEncodableAttributes(obj, codec=self) if sa: if not class_ref: [self._writeString(attr) for attr in alias.static_attrs] [self.writeElement(sa[attr]) for attr in alias.static_attrs] if definition.encoding == ObjectEncoding.STATIC: return if definition.encoding == ObjectEncoding.DYNAMIC: if da: for attr, value in da.iteritems(): self._writeString(attr) self.writeElement(value) self.stream.write_uchar(0x01) def writeByteArray(self, n, use_references=True, **kwargs): """ Writes a L{ByteArray} to the data stream. @param n: The L{ByteArray} data to be encoded to the AMF3 data stream. @type n: L{ByteArray} @param use_references: Default is C{True}. @type use_references: C{bool} """ self.stream.write(TYPE_BYTEARRAY) if use_references: ref = self.context.getObjectReference(n) if ref is not None: self._writeInteger(ref << 1) return self.context.addObject(n) buf = str(n) l = len(buf) self._writeInteger(l << 1 | REFERENCE_BIT) self.stream.write(buf) def writeXML(self, n, use_references=True, use_proxies=None): """ Writes a XML string to the data stream. @type n: L{ET} @param n: The XML Document to be encoded to the AMF3 data stream. @type use_references: C{bool} @param use_references: Default is C{True}. """ i = self.context.getLegacyXMLReference(n) if i is None: is_legacy = True else: is_legacy = False if is_legacy is True: self.stream.write(TYPE_XMLSTRING) else: self.stream.write(TYPE_XML) if use_references: ref = self.context.getObjectReference(n) if ref is not None: self._writeInteger(ref << 1) return self.context.addObject(n) self._writeString(util.ET.tostring(n, 'utf-8')) def decode(stream, context=None, strict=False): """ A helper function to decode an AMF3 datastream. @type stream: L{BufferedByteStream} @param stream: AMF3 data. @type context: L{Context} @param context: Context. """ decoder = Decoder(stream, context, strict) while 1: try: yield decoder.readElement() except pyamf.EOStream: break def encode(*args, **kwargs): """ A helper function to encode an element into AMF3 format. @type args: List of args to encode. @keyword context: Any initial context to use. @type context: L{Context} @return: C{StringIO} type object containing the encoded AMF3 data. @rtype: L{BufferedByteStream} """ context = kwargs.get('context', None) buf = util.BufferedByteStream() encoder = Encoder(buf, context) for element in args: encoder.writeElement(element) return buf def encode_int(n): """ Encodes an int as a variable length signed 29-bit integer as defined by the spec. @param n: The integer to be encoded @return: The encoded string @rtype: C{str} @raise OverflowError: Out of range. """ if n < MIN_29B_INT or n > MAX_29B_INT: raise OverflowError("Out of range") if n < 0: n += 0x20000000 bytes = '' real_value = None if n > 0x1fffff: real_value = n n >>= 1 bytes += chr(0x80 | ((n >> 21) & 0xff)) if n > 0x3fff: bytes += chr(0x80 | ((n >> 14) & 0xff)) if n > 0x7f: bytes += chr(0x80 | ((n >> 7) & 0xff)) if real_value is not None: n = real_value if n > 0x1fffff: bytes += chr(n & 0xff) else: bytes += chr(n & 0x7f) return bytes def decode_int(stream, signed=False): """ Decode C{int}. """ n = result = 0 b = stream.read_uchar() while b & 0x80 != 0 and n < 3: result <<= 7 result |= b & 0x7f b = stream.read_uchar() n += 1 if n < 3: result <<= 7 result |= b else: result <<= 8 result |= b if result & 0x10000000 != 0: if signed: result -= 0x20000000 else: result <<= 1 result += 1 return result try: from cpyamf.amf3 import encode_int, decode_int except ImportError: pass pyamf.register_class(ByteArray) for x in range(0, 20): ENCODED_INT_CACHE[x] = encode_int(x) del x PK:u3;clܧ pyamf/sol.pyc; Jc@sdZdkZdklZdZdZdZedZeeidZ dZ eid Z d e fd YZ e ZdS( s Local Shared Object implementation. Local Shared Object (LSO), sometimes known as Adobe Flash cookies, is a cookie-like data entity used by the Adobe Flash Player and Gnash. The players allow web content to read and write LSO data to the computer's local drive on a per-domain basis. @see: U{Local Shared Object on WikiPedia (external) } @see: U{Local Shared Object envelope (external) } @since: 0.1.0 N(sutilss TCSOsc Cst|ti oti|}n|id}|tjotidn|i }|o|i |jotidn|id} | tjotidn|i}|i|}|idtdjotidnti|i}||_h}xinoa|ioPn|i}|i}|idtjotid n|||} iis writeTypeiN( spyamfs get_encodersencodingsencodersutilsBufferedByteStreamsstreamswritesHEADER_VERSIONsstrictsTruestells length_poss write_ulongsHEADER_SIGNATUREs isinstancesnamesunicodes write_ushortslenswrite_utf8_strings PADDING_BYTEs write_ucharsvaluess iteritemssnsvs writeStringsFalses writeElementsseeks remaining( snamesvaluessstrictsencodingsstreamsencodersns length_possv((s)build/bdist.linux-x86_64/egg/pyamf/sol.pysencodecs0           cCs|}t}t|tot|d}t}n"t|d ot dnt |i \}}t|}x$|iD]\}}|||(sselfs __class__s__name__snamesdicts__repr__sid(sself((s)build/bdist.linux-x86_64/egg/pyamf/sol.pys__repr__s(s__name__s __module__s__doc__s__init__spyamfsAMF0ssaves__repr__(((s)build/bdist.linux-x86_64/egg/pyamf/sol.pysSOLs  (s__doc__spyamfsutilsHEADER_VERSIONsHEADER_SIGNATUREs PADDING_BYTEsTruesdecodesAMF0sencodesloadssavesdictsSOLsLSO( s PADDING_BYTEsdecodesLSOspyamfsHEADER_SIGNATUREsSOLsloadsutilsencodesHEADER_VERSIONssave((s)build/bdist.linux-x86_64/egg/pyamf/sol.pys?s   B6 PK:u3;Ԍ]pyamf/__init__.pyc; մJc@sdZdkZdkZdklZdklZyeWn ej odk l ZnXddddd gZ d d d fZ hZ gZhZhZhZd Zd ZeefZeZdfdYZgZx:eiD]/Zeid oeieieqqW[defdYZeZdefdYZ de fdYZ!de fdYZ"de fdYZ#de fdYZ$de fdYZ%de%fd YZ&d!efd"YZ'd#e(fd$YZ)d%e(fd&YZ*d'efd(YZ+d)e(fd*YZ,d+e+fd,YZ-d-e+fd.YZ.d/efd0YZ/d1efd2YZ0d3efd4YZ1e2d5Z3d6Z4d7Z5d8Z6d9Z7d:Z8d;Z9d<Z:d=Z;d>Z<d?Z=d@Z>dAZ?dBZ@dCZAdDZBdEZCe2dFZDdGZEdHZFdIZGdJZHdKZIe2e2dLgeJdMZKe3e)e6eCe6eBeIe-e,eIe.eedS(Ns B{PyAMF} provides B{A}ction B{M}essage B{F}ormat (U{AMF}) support for Python that is compatible with the Adobe U{Flash Player}. @copyright: Copyright (c) 2007-2009 The PyAMF Project. All Rights Reserved. @contact: U{users@pyamf.org} @see: U{http://pyamf.org} @since: October 2007 @version: 0.5.1 @status: Production/Stable N(sutil(sregister_adapters(sSetsregister_classsregister_class_loadersencodesdecodes __version__iiiis ClientTypescBs tZdZdZdZdZRS(s  Typecodes used to identify AMF clients and servers. @see: U{Adobe Flash Player on WikiPedia (external) } @see: U{Adobe Flash Media Server on WikiPedia (external) } iii(s__name__s __module__s__doc__sFlash6sFlashComsFlash9(((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys ClientTypesCs s_s UndefinedTypecBstZdZRS(NcCsdSdS(Nspyamf.Undefined((sself((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys__repr___s(s__name__s __module__s__repr__(((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys UndefinedType]ss BaseErrorcBstZdZRS(s[ Base AMF Error. All AMF related errors should be subclassed from this class. (s__name__s __module__s__doc__(((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys BaseErrorfs s DecodeErrorcBstZdZRS(sE Raised if there is an error in decoding an AMF data stream. (s__name__s __module__s__doc__(((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys DecodeErrorns sEOStreamcBstZdZRS(s> Raised if the data stream has come to a natural end. (s__name__s __module__s__doc__(((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pysEOStreamts sReferenceErrorcBstZdZRS(s_ Raised if an AMF data stream refers to a non-existent object or string reference. (s__name__s __module__s__doc__(((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pysReferenceErrorzs s EncodeErrorcBstZdZRS(s Raised if the element could not be encoded to the stream. @bug: See U{Docuverse blog (external) } for more info about the empty key string array bug. (s__name__s __module__s__doc__(((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys EncodeErrors sClassAliasErrorcBstZdZRS(s9 Generic error for anything class alias related. (s__name__s __module__s__doc__(((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pysClassAliasErrors sUnknownClassAliascBstZdZRS(s Raised if the AMF stream specifies an Actionscript class that does not have a Python class alias. @see: L{register_class} (s__name__s __module__s__doc__(((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pysUnknownClassAliass s BaseContextcBsPtZdZedZdZdZdZdZdZ dZ RS(sy I hold the AMF context for en/decoding streams. @ivar objects: An indexed collection of referencable objects encountered during en/decoding. @type objects: L{util.IndexedCollection} @ivar class_aliases: A L{dict} of C{class} to L{ClassAlias} @ivar exceptions: If C{True} then reference errors will be propagated. @type exceptions: C{bool} cCs,tidt|_|i||_dS(Ns exceptions(sutilsIndexedCollectionsFalsesselfsobjectssclears exceptions(sselfs exceptions((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys__init__s cCs|iih|_dS(s0 Completely clears the context. N(sselfsobjectssclears class_aliases(sself((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pysclears cCsH|ii|}|tjo|iotd|fn|SdS(s Gets an object based on a reference. @raise ReferenceError: Unknown object reference, if L{exceptions} is C{True}, otherwise C{None} will be returned. sUnknown object reference %rN(sselfsobjectssgetByReferencesrefsosNones exceptionssReferenceError(sselfsrefso((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys getObjects cCsH|ii|}|tjo|iotd|fn|SdS(so Gets a reference for an object. @raise ReferenceError: Object not a valid reference, sObject %r not a valid referenceN(sselfsobjectssgetReferenceTosobjsosNones exceptionssReferenceError(sselfsobjso((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pysgetObjectReferences cCs|ii|SdS(s Adds a reference to C{obj}. @type obj: C{mixed} @param obj: The object to add to the context. @rtype: C{int} @return: Reference to C{obj}. N(sselfsobjectssappendsobj(sselfsobj((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys addObjectscCsy|i|SWntj onXyt||i|(sselfsaliassklasssid(sself((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys__repr__ scCszt|to|i|jSnVt||io|i|ijSn/t|tti fo|i|jSnt SdS(N( s isinstancesothers basestringsselfsaliass __class__sklassstypestypess ClassTypesFalse(sselfsother((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys__eq__ scCst|SdS(N(sidsself(sself((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys__hash__scCsBt|dot|id odSn|ii}t|do$|iit|ipgdjot |ii }t |ipg}| o d|i di|f}nlt|t|t||}d|i|i di|d t| ditd |f}td |ndS( s' This function is used to check if the class being aliased fits certain criteria. The default is to check that the C{__init__} constructor does not pass in arguments. @since: 0.4 @raise TypeError: C{__init__} doesn't support additional arguments s__init__sim_funcNs func_codeis%s.__init__(%s)s, s%s.%s.__init__(%s, %s)icCsd|S(Ns%s=%s(sx(sx((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys7ss1__init__ doesn't support additional arguments: %s(shasattrsklasss__init__sim_funcs klass_funcs func_codes co_argcountslens func_defaultsslists co_varnamessargssvaluess__name__sjoinssignszips named_argss __module__smaps TypeError(sselfsklasss named_argssargsssignsvaluess klass_func((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys checkClasss$ 7 #Hc Cs|i o|inh}h}|ioOxL|iD]=}yt||||} @ivar strict: Defines how strict the decoding should be. For the time being this relates to typed objects in the stream that do not have a registered alias. Introduced in 0.4. @type strict: C{bool} @ivar timezone_offset: The offset from UTC for any datetime objects being decoded. Default to C{None} means no offset. @type timezone_offset: L{datetime.timedelta} cCs}t|tio ||_nti||_|tjo|i|_n ||_t|i_ ||_ ||_ dS(N( s isinstancesstreamsutilsBufferedByteStreamsselfscontextsNones context_classsFalses exceptionssstrictstimezone_offset(sselfsstreamscontextsstrictstimezone_offset((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys__init__as     cCs|ii}y|iid}Wntj o tnXyt||i |}Wn&t j ot d|fnXy |SWn&tj o|ii |nXdS(s Reads an AMF3 element from the data stream. @raise DecodeError: The ActionScript type is unsupported. @raise EOStream: No more data left to decode. is Unsupported ActionScript type %rN(sselfsstreamstellspossreadstsIOErrorsEOStreamsgetattrstype_mapsfuncsKeyErrors DecodeErrorsseek(sselfsposstsfunc((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys readElementqs  ccs=yxno|iVq WWntj o tnXdS(Ni(sselfs readElementsEOStreams StopIteration(sself((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys__iter__s ( s__name__s __module__s__doc__s BaseContexts context_classstype_mapsNonesFalses__init__s readElements__iter__(((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys BaseDecoderKs  sCustomTypeFunccBs tZdZdZdZRS(s Custom type mappings. cCs||_||_dS(N(sencodersselfsfunc(sselfsencodersfunc((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys__init__s cOs&|ii|i|d|idS(Nsencoder(sselfsencoders writeElementsfuncsdata(sselfsdatasargsskwargs((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys__call__s(s__name__s __module__s__doc__s__init__s__call__(((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pysCustomTypeFuncs  s BaseEncodercBsStZdZeZgZeeeedZdZ dZ dZ dZ RS(s- Base AMF encoder. @ivar type_map: A list of types -> functions. The types is a list of possible instances or functions to call (that return a C{bool}) to determine the correct function to call to encode the data. @type type_map: C{list} @ivar context_class: Holds the class that will create context objects for the implementing C{Encoder}. @type context_class: C{type} or C{types.ClassType} @ivar stream: The underlying data stream. @type stream: L{BufferedByteStream} @ivar context: The context for the encoding. @type context: An instance of C{BaseEncoder.context_class} @ivar strict: Whether the encoder should operate in 'strict' mode. Nothing is really affected by this for the time being - its just here for flexibility. @type strict: C{bool}, default is False. @ivar timezone_offset: The offset from UTC for any datetime objects being encoded. Default to C{None} means no offset. @type timezone_offset: L{datetime.timedelta} cCst|tio ||_nti||_|tjo|i|_n ||_t|i_ h|_ ||_ ||_ dS(N( s isinstancesstreamsutilsBufferedByteStreamsselfscontextsNones context_classsFalses exceptionss_write_elem_func_cachesstrictstimezone_offset(sselfsstreamscontextsstrictstimezone_offset((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys__init__s      cKstddS(ss Not possible to encode functions. @raise EncodeError: Unable to encode function/methods. s!Unable to encode function/methodsN(s EncodeError(sselfsobjskwargs((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys writeFuncscCsxtiD]r\}}y%t||ot||SnWq tj o2t |o ||ot||Sqq Xq Wx|i D]\}}xt|D]l}y%t||ot||SnWqtj o2t |o ||ot||Sq qXqWqWtSdS(s Gets a function used to encode the data. @type data: C{mixed} @param data: Python data. @rtype: callable or C{None}. @return: The function used to encode data to the stream. N(sTYPE_MAPs iteritemsstype_sfuncs isinstancesdatasCustomTypeFuncsselfs TypeErrorscallablestype_mapstlistsmethodstsgetattrsNone(sselfsdatastype_stsfuncstlistsmethod((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys_getWriteElementFuncs(  cCszy |i}Wn tj o|i|SnXy|i|SWn)tj o|i||i|} @type encoding: C{int} @kwarg encoding: AMF encoding type. @type context: L{AMF0 Context} or L{AMF3 Context} @kwarg context: Context. @return: Each element in the stream. sencodingiN( skwargsspopsDEFAULT_ENCODINGsencodings_get_decoder_classsargssdecoders readElementsEOStream(sargsskwargssencodingsdecoder((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pysdecodes cOs`|idt}t||}|i}x|D]}|i |q4W|i d|SdS(sl A helper function to encode an element. @type args: C{mixed} @keyword element: Python data. @type encoding: C{int} @keyword encoding: AMF encoding type. @type context: L{amf0.Context} or L{amf3.Context} @keyword context: Context. @rtype: C{StringIO} @return: File-like object. sencodingiN( skwargsspopsDEFAULT_ENCODINGsencodings_get_encoder_classsencodersstreamsargssels writeElementsseek(sargsskwargsselsstreamsencodingsencoder((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pysencodes  cOst|||SdS(sU Returns a subclassed instance of L{pyamf.BaseDecoder}, based on C{encoding} N(s_get_decoder_classsencodingsargsskwargs(sencodingsargsskwargs((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys get_decoder scCsa|tjodkl}|iSn&|tjodkl}|iSntd|fdS(s Get compatible decoder. @type encoding: C{int} @param encoding: AMF encoding version. @raise ValueError: AMF encoding version is unknown. @rtype: L{amf0.Decoder} or L{amf3.Decoder} @return: AMF0 or AMF3 decoder. (samf0(samf3sUnknown encoding %sN(sencodingsAMF0spyamfsamf0sDecodersAMF3samf3s ValueError(sencodingsamf0samf3((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys_get_decoder_classs       cOst|||SdS(sU Returns a subclassed instance of L{pyamf.BaseEncoder}, based on C{encoding} N(s_get_encoder_classsencodingsargsskwargs(sencodingsargsskwargs((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys get_encoder*scCsa|tjodkl}|iSn&|tjodkl}|iSntd|fdS(s Get compatible encoder. @type encoding: C{int} @param encoding: AMF encoding version. @raise ValueError: AMF encoding version is unknown. @rtype: L{amf0.Encoder} or L{amf3.Encoder} @return: AMF0 or AMF3 encoder. (samf0(samf3sUnknown encoding %sN(sencodingsAMF0spyamfsamf0sEncodersAMF3samf3s ValueError(sencodingsamf0samf3((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys_get_encoder_class1s       cKst||SdS(N(s_get_context_classsencodingskwargs(sencodingskwargs((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys get_contextIscCsa|tjodkl}|iSn&|tjodkl}|iSntd|fdS(s. Gets a compatible context class. @type encoding: C{int} @param encoding: AMF encoding version. @raise ValueError: AMF encoding version is unknown. @rtype: L{amf0.Context} or L{amf3.Context} @return: AMF0 or AMF3 context class. (samf0(samf3sUnknown encoding %sN(sencodingsAMF0spyamfsamf0sContextsAMF3samf3s ValueError(sencodingsamf0samf3((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys_get_context_classMs       cCs0|ddgjodSndk}t|SdS(s Loader for BlazeDS framework compatibility classes, specifically implementing C{ISmallMessage}. @see: U{BlazeDS (external)} @since: 0.5 sDSCsDSKN(saliasspyamf.flex.messagingspyamfs CLASS_CACHE(saliasspyamf((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys blaze_loaderes  cCs|id odSnyc|ido dk}n;|ido dk}n|ido dk}nt|SWntj ot|nXdS(s Loader for L{Flex} framework compatibility classes. @raise UnknownClassAlias: Trying to load unknown Flex compatibility class. sflex.Nsflex.messaging.messagessflex.messaging.iosflex.data.messages( saliass startswithspyamf.flex.messagingspyamfs pyamf.flexspyamf.flex.datas CLASS_CACHEsKeyErrorsUnknownClassAlias(saliasspyamf((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys flex_loaderus    cCsd}t|tot|}n|tjotd|fnt|tiox&|D]}||qgWn |||t|>> import mymodule >>> pyamf.register_package(mymodule, 'com.example.app') Now all instances of C{mymodule.User} will appear in Actionscript under the alias 'com.example.app.User'. Same goes for C{mymodule.Permission} - the Actionscript alias is 'com.example.app.Permission'. The reverse is also true, any objects with the correct aliases will now be instances of the relevant Python class. This function respects the C{__all__} attribute of the module but you can have further control of what not to auto alias by populating the C{ignore} argument. This function provides the ability to register the module it is being called in, an example: >>> class Foo: ... pass ... >>> class Bar: ... pass ... >>> import pyamf >>> pyamf.register_package('foo') You can also supply a list of classes to register. An example, taking the above classes: >>> import pyamf >>> pyamf.register_package([Foo, Bar], 'foo') @param module: The Python module that will contain all the classes to auto alias. @type module: C{module} or C{dict} @param package: The base package name. e.g. 'com.example.app'. If this is C{None} then the value is inferred from module.__name__. @type package: C{str} or C{unicode} or C{None} @param separator: The separator used to append to C{package} to form the complete alias. @type separator: C{str} @param ignore: To give fine grain control over what gets aliased and what doesn't, supply a list of classes that you B{do not} want to be aliased. @type ignore: C{iterable} @param strict: If this value is C{True} then only classes that originate from C{module} will be registered, all others will be left in peace. @type strict: C{bool} @return: A collection of all the classes that were registered and their respective L{ClassAlias} objects. @since: 0.5 ss"Cannot get list of classes from %rNiics|ijS(N(sxsmoduleskeys(sx(smodule(s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys~scs |jS(N(sxsmodule(sx(smodule(s.build/bdist.linux-x86_64/egg/pyamf/__init__.pysscs t|S(N(shasattrsmodulesx(sx(smodule(s.build/bdist.linux-x86_64/egg/pyamf/__init__.pysscs t|S(N(sgetattrsmodulesx(sx(smodule(s.build/bdist.linux-x86_64/egg/pyamf/__init__.pysss__name__s__all__s__dict__skeyscst|titif otSn|ijotSny)o|i djotSnWnt j o tSnXt SdS(Ns__name__( s isinstancesattrstypess ClassTypesTypeTypesFalses__name__signoresstricts __module__sgetsAttributeErrorsTrue(sattr(sgetsignoresstrict(s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys check_attrs  s%s%s%s(#s isinstancesmodules basestrings TypeErrorspackagesNonesinspectsstacks prev_framesf_localsstypesdictshass __getitem__sgetslistsFalsesstrictskeysshasattrs__dict__srangeslens check_attrsfiltersappends_[1]sxsclassess registeredsklasss separators__name__saliassregister_class(smodulespackages separatorsignoresstricts check_attrshassklasssgetskeyss registeredsinspectsaliassclassess_[1]s prev_framesx((smodulesignoresstrictsgets.build/bdist.linux-x86_64/egg/pyamf/__init__.pysregister_package1sP>               6(Ls__doc__stypessinspectspyamfsutilspyamf.adapterssregister_adaptersssets NameErrorssetssSets__all__s __version__s CLASS_CACHEs CLASS_LOADERSsTYPE_MAPsERROR_CLASS_MAPs ALIAS_TYPESsAMF0sAMF3sENCODING_TYPESsDEFAULT_ENCODINGs ClientTypess CLIENT_TYPESs__dict__sxs startswithsappendsobjects UndefinedTypes Undefineds Exceptions BaseErrors DecodeErrorsEOStreamsReferenceErrors EncodeErrorsClassAliasErrorsUnknownClassAliass BaseContextsdictsASObjects MixedArrays ClassAliass TypedObjectsTypedObjectClassAliass ErrorAliass BaseDecodersCustomTypeFuncs BaseEncodersNonesregister_classsunregister_classsget_class_aliassregister_class_loadersunregister_class_loaders get_modules load_classsdecodesencodes get_decoders_get_decoder_classs get_encoders_get_encoder_classs get_contexts_get_context_classs blaze_loaders flex_loadersadd_typesget_types remove_typesadd_error_classsremove_error_classsregister_alias_typesTruesregister_package(>ssets BaseDecoders UndefinedTypes_get_encoder_classs EncodeErrors get_contexts get_decodersUnknownClassAliass DecodeErrorsregister_classs CLASS_CACHEsremove_error_classsdecodesAMF0s_get_context_classs__all__sEOStreamsadd_error_classsadd_typesCustomTypeFuncsunregister_classs blaze_loadersTYPE_MAPs BaseEncodersClassAliasErrorsencodesAMF3s __version__s ClientTypess Undefineds get_encodersinspectsERROR_CLASS_MAPsutils BaseErrorsASObjects ClassAliass ALIAS_TYPESsTypedObjectClassAliass BaseContexts ErrorAliassReferenceErrorstypess_get_decoder_classsregister_adapterss MixedArraysregister_class_loaders TypedObjects CLASS_LOADERSsDEFAULT_ENCODINGs load_classsget_class_aliass get_modules flex_loadersget_types remove_types CLIENT_TYPESsxsregister_alias_typesENCODING_TYPESsunregister_class_loadersregister_package((s.build/bdist.linux-x86_64/egg/pyamf/__init__.pys?s          V #H n       F             "  4     PK:u3;zI>U|U|pyamf/amf0.pyc; Jc@sdZdkZdkZdkZdkZdklZdZdZdZdZ dZ dZ d Z d Z d Zd Zd ZdZdZdZdZdZdZdZdeifdYZdeifdYZdeifdYZdZdZde fdYZ!ei"e!dZ#ye$d Wne%j on.Xe$d d!jod"Z&e&e#Z#ndS(#s: AMF0 implementation. C{AMF0} supports the basic data types used for the NetConnection, NetStream, LocalConnection, SharedObjects and other classes in the Adobe Flash Player. @see: U{Official AMF0 Specification in English (external) } @see: U{Official AMF0 Specification in Japanese (external) } @see: U{AMF documentation on OSFlash (external) } @since: 0.1 N(sutilssssssssss s s s s sssssContextcBs;tZdZdZdZdZdZdZRS(s I hold the AMF0 context for en/decoding streams. AMF0 object references start at index 1. @ivar amf3_objs: A list of objects that have been decoded in L{AMF3}. @type amf3_objs: L{util.IndexedCollection} cKs g|_tii||dS(N(sselfs amf3_objsspyamfs BaseContexts__init__skwargs(sselfskwargs((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys__init__ms cCs>tii|g|_t|do|iindS(s% Clears the context. s amf3_contextN(spyamfs BaseContextsclearsselfs amf3_objsshasattrs amf3_context(sself((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pysclearrs  cCsX||ijS|ii|}|tjo|iotid|fn|SdS(sp Gets a reference for an object. @raise ReferenceError: Unknown AMF3 object reference. sUnknown AMF3 reference for (%r)N( sobjsselfs amf3_objssgetReferenceTososNones exceptionsspyamfsReferenceError(sselfsobjso((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pyshasAMF3ObjectReference}s  cCs|ii|SdS(s Adds an AMF3 reference to C{obj}. @type obj: C{mixed} @param obj: The object to add to the context. @rtype: C{int} @return: Reference to C{obj}. N(sselfs amf3_objssappendsobj(sselfsobj((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys addAMF3ObjectscCs2|id|i}ti|i|_|SdS(Ns exceptions(sselfs __class__s exceptionsscpyscopys amf3_objs(sselfscpy((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys__copy__s(s__name__s __module__s__doc__s__init__sclearshasAMF3ObjectReferences addAMF3Objects__copy__(((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pysContextbs    sDecodercBs+tZdZeZhed<ed<ed<ed<e d<e d<e d<e d<e d <ed <ed <ed<ed <ed <ed} N(spyamfs Undefined(sself((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys readUndefinedscCs|ii}ti}|ii||i |g}xb|i D]T}y8t |}|i||f||||<||=WqKtj oqKXqKW|i|SdS(sj Read mixed array. @rtype: C{dict} @return: C{dict} read from the stream N(sselfsstreams read_ulongslenspyamfs MixedArraysobjscontexts addObjects _readObjectsikeysskeysskeysintsikeysappends ValueErrorssort(sselfsikeysikeysslenskeysobj((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pysreadMixedArrays"       cCsWg}|ii||ii}x't|D]}|i |i q2W|SdS(sh Read a C{list} from the data stream. @rtype: C{list} @return: C{list} N( sobjsselfscontexts addObjectsstreams read_ulongslensxrangesisappends readElement(sselfsisobjslen((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pysreadLists cCs|i}t}y%ti|}|id|}Wn6ti j o'|i onti |}nX|i i ||i|||SdS(s Reads an ActionScript object from the stream and attempts to 'cast' it. @see: L{load_class} scodecN(sselfs readStrings classnamesNonesaliasspyamfsget_class_aliasscreateInstancesretsUnknownClassAliassstricts TypedObjectscontexts addObjects _readObject(sselfsrets classnamesalias((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pysreadTypedObject s  cCst|id o"titidt|i_nt|id o+titi|i |ii|i_ n|ii }|i }|ii||SdS(s Read AMF3 elements from the data stream. @rtype: C{mixed} @return: The AMF3 element read from the stream s amf3_contexts exceptionss amf3_decoderN(shasattrsselfscontextspyamfs get_contextsAMF3sFalses amf3_contexts get_decodersstreams amf3_decodersdecoders readElementselements addAMF3Object(sselfselementsdecoder((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pysreadAMF3"s"+  cCs#|ii}|ii|SdS(sf Reads a string from the data stream. @rtype: C{str} @return: string N(sselfsstreams read_ushortslensread_utf8_string(sselfslen((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys readString6scCst}|iid}x@|iitjo)|i ||<|iid}q!W|ii d|o|i ||d|nti||dS(Nsutf8iscodec(sdicts obj_attrssselfs readStringsencodeskeysstreamspeeksTYPE_OBJECTTERMs readElementsreadsaliassapplyAttributessobjsutils set_attrs(sselfsobjsaliass obj_attrsskey((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys _readObject@s cCs1ti}|ii||i||SdS(sd Reads an object from the data stream. @rtype: L{ASObject} N(spyamfsASObjectsobjsselfscontexts addObjects _readObject(sselfsobj((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys readObjectQs   cCsP|ii}|ii|}|tjoti d|fn|SdS(sr Reads a reference from the data stream. @raise pyamf.ReferenceError: Unknown reference. sUnknown reference %dN( sselfsstreams read_ushortsidxscontexts getObjectsosNonespyamfsReferenceError(sselfsosidx((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys readReference^s  cCsd|iid}|ii}ti|}|i o||i }n|i i ||SdS(s Reads a UTC date from the data stream. Client and servers are responsible for applying their own timezones. Date: C{0x0B T7 T6} .. C{T0 Z1 Z2 T7} to C{T0} form a 64 bit Big Endian number that specifies the number of nanoseconds that have passed since 1/1/1970 0:00 to the specified time. This format is UTC 1970. C{Z1} and C{Z0} for a 16 bit Big Endian number indicating the indicated time's timezone in minutes. f1000.0N( sselfsstreams read_doublesmss read_shortstzsutils get_datetimesdstimezone_offsetscontexts addObject(sselfstzsdsms((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pysreadDatems  cCs#|ii}|ii|SdS(s# Read UTF8 string. N(sselfsstreams read_ulongslensread_utf8_string(sselfslen((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pysreadLongStringscCs6|i}tii|}|ii||SdS(s Read XML. N( sselfsreadLongStringsdatasutilsETs fromstringsxmlscontexts addObject(sselfsxmlsdata((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pysreadXMLs  (%s__name__s __module__s__doc__sContexts context_classs TYPE_NUMBERs TYPE_BOOLs TYPE_STRINGs TYPE_OBJECTs TYPE_NULLsTYPE_UNDEFINEDsTYPE_REFERENCEsTYPE_MIXEDARRAYs TYPE_ARRAYs TYPE_DATEsTYPE_LONGSTRINGsTYPE_UNSUPPORTEDsTYPE_XMLsTYPE_TYPEDOBJECTs TYPE_AMF3stype_maps readNumbers readBooleansreadNulls readUndefinedsreadMixedArraysreadListsreadTypedObjectsreadAMF3s readStringsNones _readObjects readObjects readReferencesreadDatesreadLongStringsreadXML(((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pysDecoders$          sEncodercBstZdZeZeieieiei ei ei ei fdfei fdfefdfeeefdfeifdfeifdfeifdfeieifdfeieieifd feifd fd fd feieifd feiei fdfg Z!dZ"dZ#dZ$dZ%dZ&dZ'dZ(dZ)dZ*dZ+dZ,dZ-e.dZ/dZ0dZ1dZ2dZ3dZ4d Z5d!Z6d"Z7RS(#s Encodes an AMF0 stream. @ivar use_amf3: A flag to determine whether this encoder knows about AMF3. @type use_amf3: C{bool} s writeFuncs writeNulls writeBooleans writeNumbers writeStrings writeObjectswriteMixedArrays writeArrays writeDateswriteXMLcCs |tijS(N(sxspyamfs Undefined(sx((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pyssswriteUndefineds writeClasscOs/|idt|_tii|||dS(Nsuse_amf3( skwargsspopsFalsesselfsuse_amf3spyamfs BaseEncoders__init__sargs(sselfsargsskwargs((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys__init__scCs|ii|dS(s Writes the type to the stream. @type t: C{str} @param t: ActionScript type. @raise pyamf.EncodeError: AMF0 type is not recognized. N(sselfsstreamswritest(sselfst((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys writeTypescCs|itdS(s Writes the L{undefined} data type to the stream. @param data: The C{undefined} data to be encoded to the AMF0 data stream. @type data: C{undefined} data N(sselfs writeTypesTYPE_UNDEFINED(sselfsdata((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pyswriteUndefinedscOstiddS(s/ Classes cannot be serialised. s"Class objects cannot be serialisedN(spyamfs EncodeError(sselfsargsskwargs((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys writeClassscOstiddS(s1 Functions cannot be serialised. sCallables cannot be serialisedN(spyamfs EncodeError(sselfsargsskwargs((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys writeFuncscCs|itdS(s Writes L{unsupported} data type to the stream. @param data: The C{unsupported} data to be encoded to the AMF0 data stream. @type data: C{unsupported} data N(sselfs writeTypesTYPE_UNSUPPORTED(sselfsdata((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pyswriteUnsupportedscCs?|io|ii|o |iSntii||SdS(sr Gets a function based on the type of data. @see: L{pyamf.BaseEncoder._writeElementFunc} N( sselfsuse_amf3scontextshasAMF3ObjectReferencesdatas writeAMF3spyamfs BaseEncoders_writeElementFunc(sselfsdata((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys_writeElementFuncs cCsD|i|}|tjotid|fn||dS(s Writes the data. @type data: C{mixed} @param data: The data to be encoded to the AMF0 data stream. @raise EncodeError: Cannot find encoder func. sCannot find encoder func for %rN(sselfs_writeElementFuncsdatasfuncsNonespyamfs EncodeError(sselfsdatasfunc((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys writeElements  cCs|itdS(sl Write null type to data stream. @type n: C{None} @param n: Is ignored. N(sselfs writeTypes TYPE_NULL(sselfsn((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys writeNullscCs|ii|i}|io|i|dSn|i|t j odSn|ii ||i t |i it|x|D]}|i|qWdS(s Write array to the stream. @type a: L{BufferedByteStream} @param a: The array data to be encoded to the AMF0 data stream. N(sselfscontexts getClassAliassas __class__saliassexternals writeObjectswriteReferencesNones addObjects writeTypes TYPE_ARRAYsstreams write_ulongslensdatas writeElement(sselfsasaliassdata((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys writeArray s   cCs'|it|iit|dS(s Write number to the data stream. @type n: L{BufferedByteStream} @param n: The number data to be encoded to the AMF0 data stream. N(sselfs writeTypes TYPE_NUMBERsstreams write_doublesfloatsn(sselfsn((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys writeNumber(s cCs<|it|o|iidn|iiddS(s Write boolean to the data stream. @type b: L{BufferedByteStream} @param b: The boolean data to be encoded to the AMF0 data stream. iiN(sselfs writeTypes TYPE_BOOLsbsstreams write_uchar(sselfsb((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys writeBoolean2s  cCst|}|tjonNt|to|id}n+t|t ot|id}nt|}|o/|djo|i t q|i t n|djo|ii|n|ii||ii|dS(s Write string to the data stream. @type s: L{BufferedByteStream} @param s: The string data to be encoded to the AMF0 data stream. @type writeType: C{bool} @param writeType: Write data type. sutf8iN(stypessstsstrs isinstancesunicodesencodes basestringslensls writeTypesselfsTYPE_LONGSTRINGs TYPE_STRINGsstreams write_ulongs write_ushortswrite(sselfsss writeTypeslst((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys writeString@s"     cCsL|ii|}|tjotSn|it|ii ||SdS(s Write reference to the data stream. @type o: L{BufferedByteStream} @param o: The reference data to be encoded to the AMF0 data stream. N( sselfscontextsgetObjectReferencesosidxsNones writeTypesTYPE_REFERENCEsstreams write_ushort(sselfsosidx((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pyswriteReferenceas  cCs>x7|iD])\}}|i|t|i|q WdS(s Write C{dict} to the data stream. @type o: C{iterable} @param o: The C{dict} data to be encoded to the AMF0 data stream. N(sos iteritemsskeysvalsselfs writeStringsFalses writeElement(sselfsosvalskey((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys _writeDictss  cCs|i|tj odSn|ii||ityptgi }|i D]2}t |dttfo||dqUqU~}|djo d}nWntj o d}nX|ii||i||idS(s Write mixed array to the data stream. @type o: L{BufferedByteStream} @param o: The mixed array data to be encoded to the AMF0 data stream. Ni(sselfswriteReferencesosNonescontexts addObjects writeTypesTYPE_MIXEDARRAYsmaxsappends_[1]sitemssys isinstancesintslongs max_indexs ValueErrorsstreams write_ulongs _writeDicts_writeEndObject(sselfsos_[1]sys max_index((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pyswriteMixedArrays U   cCs!|iid|itdS(Ns(sselfsstreamswrites writeTypesTYPE_OBJECTTERM(sself((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys_writeEndObjectscCst|io|i|dSn|i|tj odSn|ii||ii|i }|i |i o|i|dSn|i o|itn!|it|i|i t|i|d|\}}|o9x6|iD]'}|i|t|i||qWn|o>x;|iD])\}}|i|t|i|q5Wn|idS(s Write object to the stream. @type o: L{BufferedByteStream} @param o: The object data to be encoded to the AMF0 data stream. Nscodec(sselfsuse_amf3s writeAMF3soswriteReferencesNonescontexts addObjects getClassAliass __class__saliasscompilesamf3s anonymouss writeTypes TYPE_OBJECTsTYPE_TYPEDOBJECTs writeStringsFalsesgetEncodableAttributesssasdas static_attrsskeys writeElements iteritemssvalues_writeEndObject(sselfsosdasaliassvalueskeyssa((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys writeObjects8         cCst|tiotid|fn|itj o||i8}nt i |}d}|i t|ii|d|ii|dS(s Writes a date to the data stream. @type d: Instance of C{datetime.datetime} @param d: The date to be encoded to the AMF0 data stream. s|A datetime.time instance was found but AMF0 has no way to encode time objects. Please use datetime.datetime instead (got:%r)if1000.0N(s isinstancesdsdatetimestimespyamfs EncodeErrorsselfstimezone_offsetsNonesutils get_timestampssecsstzs writeTypes TYPE_DATEsstreams write_doubles write_short(sselfsdstzssecs((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys writeDates cCsq|itjo|i|dSn|ittii |d}|i i t ||i i|dS(s Write XML to the data stream. @type e: L{BufferedByteStream} @param e: The XML data to be encoded to the AMF0 data stream. Nsutf-8(sselfsuse_amf3sTrues writeAMF3ses writeTypesTYPE_XMLsutilsETstostringsdatasstreams write_ulongslenswrite(sselfsesdata((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pyswriteXMLs  cCst|id o"titidt|i_nt|id o+titi|i |ii|i_ n|ii ||ii }|it|i|dS(s Writes an element to the datastream in L{AMF3} format. @type data: C{mixed} @param data: The data to be encoded to the AMF0 data stream. s amf3_contexts exceptionss amf3_encoderN(shasattrsselfscontextspyamfs get_contextsAMF3sFalses amf3_contexts get_encodersstreams amf3_encoders addAMF3Objectsdatasencoders writeTypes TYPE_AMF3s writeElement(sselfsdatasencoder((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys writeAMF3s"+  (8s__name__s __module__s__doc__sContexts context_classstypessBuiltinFunctionTypesBuiltinMethodTypes FunctionTypes GeneratorTypes ModuleTypes LambdaTypes MethodTypesNoneTypesboolsintslongsfloats StringTypesspyamfsASObjects MixedArraysListTypes TupleTypesdatetimesdatestimesutils is_ET_elements ClassTypesTypeTypes InstanceTypes ObjectTypestype_maps__init__s writeTypeswriteUndefineds writeClasss writeFuncswriteUnsupporteds_writeElementFuncs writeElements writeNulls writeArrays writeNumbers writeBooleansTrues writeStringswriteReferences _writeDictswriteMixedArrays_writeEndObjects writeObjects writeDateswriteXMLs writeAMF3(((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pysEncoders2          !    -  cosJt||}x4no,y|iVWqtij oPqXqWdS(s9 A helper function to decode an AMF0 datastream. iN(sDecodersargsskwargssdecoders readElementspyamfsEOStream(sargsskwargssdecoder((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pysdecodescOs5t|}x|D]}|i|qW|iSdS(so A helper function to encode an element into the AMF0 format. @type element: C{mixed} @keyword element: The element to encode @type context: L{Context} @keyword context: AMF0 C{Context} to use for the encoding. This holds previously referenced objects etc. @rtype: C{StringIO} @return: The encoded stream. N(sEncoderskwargssencodersargsselements writeElementsstream(sargsskwargssencoderselement((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pysencodes  s RecordSetcBs`tZdZdfdYZggeedZdZdZeeeZ dZ RS(sA I represent the C{RecordSet} class used in Adobe Flash Remoting to hold (amongst other things) SQL records. @ivar columns: The columns to send. @type columns: List of strings. @ivar items: The C{RecordSet} data. @type items: List of lists, the order of the data corresponds to the order of the columns. @ivar service: Service linked to the C{RecordSet}. @type service: @ivar id: The id of the C{RecordSet}. @type id: C{str} @see: U{RecordSet on OSFlash (external) } s__amf__cBstZdZdfZeZRS(Ns RecordSets serverInfo(s__name__s __module__saliassstaticsFalsesdynamic(((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys__amf__Bs cCs(||_||_||_||_dS(N(scolumnssselfsitemssservicesid(sselfscolumnssitemssservicesid((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys__init__Gs   c Cstidt|iddddd|id|i}|itj o'|i hdt |id<n|i tj o#|i hd t |i <n|SdS( Ns totalCountscursorisversions initialDatas columnNamess serviceNamesnamesid( spyamfsASObjectslensselfsitemsscolumnssretsservicesNonesupdatesstrsid(sselfsret((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys_get_server_infoMs!'#cCs|d|_|d|_ytd|d|_Wntj ot|_nXy|d|_Wntj ot|_nXdS(Ns columnNamess initialDatasnames serviceNamesid( svalsselfscolumnssitemssdictsservicesKeyErrorsNonesid(sselfsval((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys_set_server_infoYs  cCsd|i|iif}|itj o|d|i7}n|itj o|d|i7}n|dt|7}|SdS(Ns <%s.%s objects id=%ss service=%ss at 0x%x>(sselfs __module__s __class__s__name__sretsidsNonesservice(sselfsret((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys__repr__js( s__name__s __module__s__doc__s__amf__sNones__init__s_get_server_infos_set_server_infospropertys serverInfos__repr__(((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys RecordSet/s  cCsVyt|}Wnttfj on$X||jo ||jo|Sn|SdS(sz This is a compatibility function that takes a C{float} and converts it to an C{int} if the values are equal. N(sintsxsys OverflowErrors ValueError(sxsy((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys_check_for_intzssnanicsd|_SdS(Ncs;t|iiddjo|Sni|SdS(Nsnani(sstrsxslowersfindsf2sfunc(sx(sf2(s*build/bdist.linux-x86_64/egg/pyamf/amf0.pysf2s"(sf2sfunc(sfuncsf2((sf2s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys check_nans  ('s__doc__sdatetimestypesscopyspyamfsutils TYPE_NUMBERs TYPE_BOOLs TYPE_STRINGs TYPE_OBJECTsTYPE_MOVIECLIPs TYPE_NULLsTYPE_UNDEFINEDsTYPE_REFERENCEsTYPE_MIXEDARRAYsTYPE_OBJECTTERMs TYPE_ARRAYs TYPE_DATEsTYPE_LONGSTRINGsTYPE_UNSUPPORTEDsTYPE_RECORDSETsTYPE_XMLsTYPE_TYPEDOBJECTs TYPE_AMF3s BaseContextsContexts BaseDecodersDecoders BaseEncodersEncodersdecodesencodesobjects RecordSetsregister_classs_check_for_intsfloats ValueErrors check_nan(sTYPE_UNSUPPORTEDs TYPE_STRINGspyamfsdatetimes TYPE_NULLs TYPE_DATEsTYPE_LONGSTRINGsdecodesTYPE_MIXEDARRAYsEncodersTYPE_TYPEDOBJECTsTYPE_RECORDSETsDecodersencodes TYPE_NUMBERs check_nans RecordSetsTYPE_UNDEFINEDsTYPE_REFERENCEs TYPE_AMF3sContextscopysTYPE_MOVIECLIPstypess_check_for_intsutils TYPE_OBJECTs TYPE_BOOLsTYPE_XMLsTYPE_OBJECTTERMs TYPE_ARRAY((s*build/bdist.linux-x86_64/egg/pyamf/amf0.pys?sN     <v H   PK:u3;7pppyamf/amf3.pyc; Jc@s<dZdkZdkZdkZdkZdklZdklZlZe Z y e Wn e j odk lZ nXdZdZdZdZd Zd Zd Zd Zd ZdZdZdZdZdZdZd ZhZdfdYZ de!fdYZ"de!fdYZ#dei$e#e"fdYZ%de!fdYZ&dei'fd YZ(d!ei)fd"YZ*d#ei+fd$YZ,e-e d%Z.d&Z/d'Z0e d(Z1yd)k2l0Z0l1Z1Wne3j onXei4e%x'e5d*d+D]Z6e0e6ee6} 3.0 and provides various advantages over L{AMF0}, which is used for ActionScript 1.0 and 2.0. It adds support for sending C{int} and C{uint} objects as integers and supports data types that are available only in ActionScript 3.0, such as L{ByteArray} and L{ArrayCollection}. @see: U{Official AMF3 Specification in English (external) } @see: U{Official AMF3 Specification in Japanese (external) } @see: U{AMF3 documentation on OSFlash (external) } @since: 0.1 N(sutil(s ObjectProxysArrayCollection(sSetssssssssss s s s iiisObjectEncodingcBs&tZdZdZdZdZdZRS(s AMF object encodings. iiii(s__name__s __module__s__doc__sSTATICsEXTERNALsDYNAMICsPROXY(((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pysObjectEncoding{s s DataOutputcBstZdZdZdZdZdZdZdZdZ dZ e e d Z d Zd Zd Zd ZdZRS(s I am a C{StringIO} type object containing byte data from the AMF stream. ActionScript 3.0 introduced the C{flash.utils.ByteArray} class to support the manipulation of raw data in the form of an Array of bytes. I provide a set of methods for writing binary data with ActionScript 3.0. This class is the I/O counterpart to the L{DataInput} class, which reads binary data. @see: U{IDataOutput on Livedocs (external) } cCs||_|i|_dS(s{ @param encoder: Encoder containing the stream. @type encoder: L{amf3.Encoder} N(sencodersselfsstream(sselfsencoder((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys__init__s cCsUt|to5|tjo|iidqQ|iidn tddS(s$ Writes a Boolean value. @type value: C{bool} @param value: A C{Boolean} value determining which byte is written. If the parameter is C{True}, C{1} is written; if C{False}, C{0} is written. @raise ValueError: Non-boolean value found. iisNon-boolean value foundN(s isinstancesvaluesboolsTruesselfsstreams write_uchars ValueError(sselfsvalue((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys writeBooleans  cCs|ii|dS(s= Writes a byte. @type value: C{int} N(sselfsstreams write_charsvalue(sselfsvalue((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys writeBytescCs|ii|SdS(s[ Writes an unsigned byte. @type value: C{int} @since: 0.5 N(sselfsstreams write_ucharsvalue(sselfsvalue((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pyswriteUnsignedBytescCs|ii|dS(s} Writes an IEEE 754 double-precision (64-bit) floating point number. @type value: C{number} N(sselfsstreams write_doublesvalue(sselfsvalue((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys writeDoublescCs|ii|dS(s| Writes an IEEE 754 single-precision (32-bit) floating point number. @type value: C{float} N(sselfsstreams write_floatsvalue(sselfsvalue((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys writeFloatscCs|ii|dS(sN Writes a 32-bit signed integer. @type value: C{int} N(sselfsstreams write_longsvalue(sselfsvalue((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pyswriteIntscCs#|iit|i|dS(s Writes a multibyte string to the datastream using the specified character set. @type value: C{str} @param value: The string value to be written. @type charset: C{str} @param charset: The string denoting the character set to use. Possible character set strings include C{shift-jis}, C{cn-gb}, C{iso-8859-1} and others. @see: U{Supported character sets on Livedocs (external) } N(sselfsstreamswritesunicodesvaluesencodescharset(sselfsvaluescharset((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pyswriteMultiBytes cCs|ii|||dS(s Writes an object to data stream in AMF serialized format. @param value: The object to be serialized. @type use_references: C{bool} @param use_references: N(sselfsencoders writeElementsvaluesuse_referencess use_proxies(sselfsvaluesuse_referencess use_proxies((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys writeObjectscCs|ii|dS(sy Writes a 16-bit integer. @type value: C{int} @param value: A byte value as an integer. N(sselfsstreams write_shortsvalue(sselfsvalue((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys writeShortscCs|ii|dS(s Writes a 16-bit unsigned integer. @type value: C{int} @param value: A byte value as an integer. @since: 0.5 N(sselfsstreams write_ushortsvalue(sselfsvalue((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pyswriteUnsignedShort scCs|ii|dS(s Writes a 32-bit unsigned integer. @type value: C{int} @param value: A byte value as an unsigned integer. N(sselfsstreams write_ulongsvalue(sselfsvalue((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pyswriteUnsignedIntscCsst|t ot|d}nti}|i||i}|i i t ||i i |dS(s7 Writes a UTF-8 string to the data stream. The length of the UTF-8 string in bytes is written first, as a 16-bit integer, followed by the bytes representing the characters of the string. @type value: C{str} @param value: The string value to be written. sutf8N(s isinstancesvaluesunicodesutilsBufferedByteStreamsbufswrite_utf8_stringsgetvaluesbytessselfsstreams write_ushortslenswrite(sselfsvaluesbytessbuf((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pyswriteUTFs    cCsCt}t|to |}nt|d}|ii|dS(s Writes a UTF-8 string. Similar to L{writeUTF}, but does not prefix the string with a 16-bit length word. @type value: C{str} @param value: The string value to be written. sutf8N(sNonesvals isinstancesvaluesunicodesselfsstreamswrite_utf8_string(sselfsvaluesval((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys writeUTFBytes4s  (s__name__s __module__s__doc__s__init__s writeBooleans writeByteswriteUnsignedBytes writeDoubles writeFloatswriteIntswriteMultiBytesTruesNones writeObjects writeShortswriteUnsignedShortswriteUnsignedIntswriteUTFs writeUTFBytes(((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys DataOutputs       s DataInputcBstZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZRS(s1 I provide a set of methods for reading binary data with ActionScript 3.0. This class is the I/O counterpart to the L{DataOutput} class, which writes binary data. @see: U{IDataInput on Livedocs (external) } cCs0t|tpt||_|i|_dS(s @param decoder: AMF3 decoder containing the stream. @type decoder: L{amf3.Decoder} N(s isinstancesdecodersDecodersAssertionErrorsselfsstream(sselfsdecoder((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys__init__Qs cCsL|iid}|djotSn"|djotSn tddS(s Read C{Boolean}. @raise ValueError: Error reading Boolean. @rtype: C{bool} @return: A Boolean value, C{True} if the byte is nonzero, C{False} otherwise. isssError reading booleanN(sselfsstreamsreadsbytesFalsesTrues ValueError(sselfsbyte((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys readBoolean[s  cCs|iiSdS(s Reads a signed byte. @rtype: C{int} @return: The returned value is in the range -128 to 127. N(sselfsstreams read_char(sself((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pysreadBytemscCs|iiSdS(s Reads an IEEE 754 double-precision floating point number from the data stream. @rtype: C{number} @return: An IEEE 754 double-precision floating point number. N(sselfsstreams read_double(sself((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys readDoublevscCs|iiSdS(s Reads an IEEE 754 single-precision floating point number from the data stream. @rtype: C{number} @return: An IEEE 754 single-precision floating point number. N(sselfsstreams read_float(sself((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys readFloatscCs|iiSdS(s Reads a signed 32-bit integer from the data stream. @rtype: C{int} @return: The returned value is in the range -2147483648 to 2147483647. N(sselfsstreams read_long(sself((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pysreadIntscCs#|ii|}t||SdS(s Reads a multibyte string of specified length from the data stream using the specified character set. @type length: C{int} @param length: The number of bytes from the data stream to read. @type charset: C{str} @param charset: The string denoting the character set to use. @rtype: C{str} @return: UTF-8 encoded string. N(sselfsstreamsreadslengthsbytessunicodescharset(sselfslengthscharsetsbytes((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys readMultiBytes cCs|iiSdS(sb Reads an object from the data stream. @return: The deserialized object. N(sselfsdecoders readElement(sself((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys readObjectscCs|iiSdS(s Reads a signed 16-bit integer from the data stream. @rtype: C{uint} @return: The returned value is in the range -32768 to 32767. N(sselfsstreams read_short(sself((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys readShortscCs|iiSdS(s Reads an unsigned byte from the data stream. @rtype: C{uint} @return: The returned value is in the range 0 to 255. N(sselfsstreams read_uchar(sself((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pysreadUnsignedBytescCs|iiSdS(s Reads an unsigned 32-bit integer from the data stream. @rtype: C{uint} @return: The returned value is in the range 0 to 4294967295. N(sselfsstreams read_ulong(sself((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pysreadUnsignedIntscCs|iiSdS(s Reads an unsigned 16-bit integer from the data stream. @rtype: C{uint} @return: The returned value is in the range 0 to 65535. N(sselfsstreams read_ushort(sself((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pysreadUnsignedShortscCs#|ii}|ii|SdS(s Reads a UTF-8 string from the data stream. The string is assumed to be prefixed with an unsigned short indicating the length in bytes. @rtype: C{str} @return: A UTF-8 string produced by the byte representation of characters. N(sselfsstreams read_ushortslengthsread_utf8_string(sselfslength((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pysreadUTFs cCs|i|dSdS(s^ Reads a sequence of C{length} UTF-8 bytes from the data stream and returns a string. @type length: C{int} @param length: The number of bytes from the data stream to read. @rtype: C{str} @return: A UTF-8 string produced by the byte representation of characters of specified C{length}. sutf-8N(sselfs readMultiByteslength(sselfslength((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys readUTFBytess (s__name__s __module__s__doc__s__init__s readBooleansreadBytes readDoubles readFloatsreadInts readMultiBytes readObjects readShortsreadUnsignedBytesreadUnsignedIntsreadUnsignedShortsreadUTFs readUTFBytes(((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys DataInputFs     s ByteArraycBsEtZdZdfdYZdZdZdZdZRS(sZ I am a C{StringIO} type object containing byte data from the AMF stream. ActionScript 3.0 introduced the C{flash.utils.ByteArray} class to support the manipulation of raw data in the form of an Array of bytes. Supports C{zlib} compression. Possible uses of the C{ByteArray} class: - Creating a custom protocol to connect to a client. - Writing your own AMF/Remoting packet. - Optimizing the size of your data by using custom data types. @see: U{ByteArray on Livedocs (external) } s__amf__cBstZeZRS(N(s__name__s __module__sTruesamf3(((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys__amf__scOss|idt|_tii|||t i|t ||it i|t ||it |_dS(Nscontext(skwargsspopsContextsselfscontextsutilsBufferedByteStreams__init__sargss DataInputsDecoders DataOutputsEncodersFalses compressed(sselfsargsskwargs((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys__init__s cCsDt|tot|i|iSnt|i|SdS(N(s isinstancesothers ByteArrayscmpsselfsgetvalue(sselfsother((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys__cmp__ scCsG|i}|io)ti|}|dd|d}n|SdS(Nisi(sselfsgetvaluesbufs compressedszlibscompress(sselfsbuf((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys__str__s   cCs t|_dS(s> Forces compression of the underlying stream. N(sTruesselfs compressed(sself((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pyscompresss(s__name__s __module__s__doc__s__amf__s__init__s__cmp__s__str__scompress(((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys ByteArrays   sClassDefinitioncBs tZdZdZdZRS(s cCs||_t|_|id|_|iot|i|_nti |_ |i oti |_ n3|i o'|i|ijoti|_ qndS(Ni(saliassselfsNones referencescompilesattr_lens static_attrsslensObjectEncodingsDYNAMICsencodingsexternalsEXTERNALsdynamicsencodable_propertiessSTATIC(sselfsalias((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys__init__%s        cCs0d|ii|i|i|it|fSdS(Ns><%s.ClassDefinition reference=%r encoding=%r alias=%r at 0x%x>(sselfs __class__s __module__s referencesencodingsaliassid(sself((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys__repr__8s(s__name__s __module__s__doc__s__init__s__repr__(((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pysClassDefinition!s  sContextcBstZdZedZdZdZdZdZdZ dZ dZ d Z d Z d Zd Zd ZdZRS(s. I hold the AMF3 context for en/decoding streams. @ivar strings: A list of string references. @type strings: C{list} @ivar classes: A list of L{ClassDefinition}. @type classes: C{list} @ivar legacy_xml: A list of legacy encoded XML documents. @type legacy_xml: C{list} cCsztidtdt|_h|_h|_tidt|_ti dt|_ d|_ t i i|d|dS(Nsuse_hashs exceptionsi(sutilsIndexedCollectionsTruesFalsesselfsstringssclassess class_refs legacy_xmls IndexedMapsobject_aliasess class_idxspyamfs BaseContexts__init__s exceptions(sselfs exceptions((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys__init__Is   cCsVtii||iih|_h|_|ii|iid|_ dS(s% Clears the context. iN( spyamfs BaseContextsclearsselfsstringssclassess class_refs legacy_xmlsobject_aliasess class_idx(sself((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pysclearTs     cCs|ii||dS(sK Maps an object to an aliased object. @since: 0.4 N(sselfsobject_aliasessmapsobjsalias(sselfsobjsalias((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pyssetObjectAliasbscCs|ii|}|tjo2|itjotSnti d|fn|ii |}|tjo2|itjotSnti d|fn|SdS(s Get an alias of an object. @since: 0.4 @raise pyamf.ReferenceError: Unknown object alias. @raise pyamf.ReferenceError: Unknown mapped alias. sUnknown object alias for %rsUnknown mapped alias for %rN( sselfsobject_aliasessgetReferenceTosobjsrefsNones exceptionssFalsespyamfsReferenceErrorsgetMappedByReferencesmapped(sselfsobjsmappedsref((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pysgetObjectAliasjs  cCsK|ii|}|tjo|iotid|fn|SdS(s Gets a string based on a reference C{ref}. @param ref: The reference index. @type ref: C{str} @raise pyamf.ReferenceError: The referenced string could not be found. @rtype: C{str} @return: The referenced string. sString reference %r not foundN( sselfsstringssgetByReferencesrefsisNones exceptionsspyamfsReferenceError(sselfsrefsi((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys getStrings cCsK|ii|}|tjo|iotid|fn|SdS(s Return string reference. @type s: C{str} @param s: The referenced string. @raise pyamf.ReferenceError: The string reference could not be found. @return: The reference index to the string. @rtype: C{int} s!Reference for string %r not foundN( sselfsstringssgetReferenceTosssisNones exceptionsspyamfsReferenceError(sselfsssi((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pysgetStringReferences cCsht|t o tnt|djo&|i otSnti dn|i i |SdS(s Creates a reference to C{s}. If the reference already exists, that reference is returned. @type s: C{str} @param s: The string to be referenced. @rtype: C{int} @return: The reference index. @raise TypeError: The parameter C{s} is not of C{basestring} type. @raise pyamf.ReferenceError: Trying to store a reference to an empty string. is+Cannot store a reference to an empty stringN( s isinstancesss basestrings TypeErrorslensselfs exceptionssNonespyamfsReferenceErrorsstringssappend(sselfss((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys addStrings   cCsRy|i|SWn<tj o0|i otSntid|fnXdS(s Return class reference. @raise pyamf.ReferenceError: The class reference could not be found. @return: Class reference. sClass reference %r not foundN(sselfs class_refsrefsKeyErrors exceptionssNonespyamfsReferenceError(sselfsref((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pysgetClassByReferences cCsRy|i|SWn<tj o0|i otSntid|fnXdS(s Return class reference. @raise pyamf.ReferenceError: The class reference could not be found. @return: Class reference. sClass alias for %r not foundN(sselfsclassessklasssKeyErrors exceptionssNonespyamfsReferenceError(sselfsklass((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pysgetClasss cCsG|i}||i|<|}|i|<||_|id7_|SdS(sj Creates a reference to C{class_def}. @param alias: C{ClassDefinition} instance. iN( sselfs class_idxsrefsaliass class_refscdsclassessklasss reference(sselfsaliassklasssrefscd((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pysaddClasss   cCsT|ii|}|tjo-|i otSntid|fn|SdS(s Return the legacy XML reference. This is the C{flash.xml.XMLDocument} class in ActionScript 3.0 and the top-level C{XML} class in ActionScript 1.0 and 2.0. @type ref: C{int} @param ref: The reference index. @raise pyamf.ReferenceError: The legacy XML reference could not be found. @return: Instance of L{ET} s!Legacy XML reference %r not foundN( sselfs legacy_xmlsgetByReferencesrefsisNones exceptionsspyamfsReferenceError(sselfsrefsi((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys getLegacyXMLs   cCsT|ii|}|tjo-|i otSntid|fn|SdS(s  Return legacy XML reference. @type doc: L{ET} @param doc: The XML document to reference. @raise pyamf.ReferenceError: The reference could not be found. @return: The reference to C{doc}. @rtype: C{int} s#Reference for document %r not foundN( sselfs legacy_xmlsgetReferenceTosdocsisNones exceptionsspyamfsReferenceError(sselfsdocsi((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pysgetLegacyXMLReferences   cCs|ii|SdS(s< Creates a reference to C{doc}. If C{doc} is already referenced that index will be returned. Otherwise a new index will be created. @type doc: L{ET} @param doc: The XML document to reference. @rtype: C{int} @return: The reference to C{doc}. N(sselfs legacy_xmlsappendsdoc(sselfsdoc((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys addLegacyXMLs cCs|id|iSdS(Ns exceptions(sselfs __class__s exceptions(sself((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys__copy__(s(s__name__s __module__s__doc__sTrues__init__sclearssetObjectAliassgetObjectAliass getStringsgetStringReferences addStringsgetClassByReferencesgetClasssaddClasss getLegacyXMLsgetLegacyXMLReferences addLegacyXMLs__copy__(((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pysContext=s             sDecodercBsFtZdZeZhed<ed<ed<ed<e d<e d<e d<e d<e d <ed <ed <ed <ed } for the AMF3 integer data format. N(s decode_intsselfsstreamssigned(sselfssigned((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys readIntegerzscsd}|\}}|o|oii|Sn|djodSnii|}t |djo|oii |n|SdS(sd Reads and returns a string from the stream. @type use_references: C{bool} cs(i}|d?|t@djfSdS(Nii(sselfsreadUnsignedIntegersxs REFERENCE_BIT(sx(sself(s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys readLengths iuN( s readLengthslengths is_referencesuse_referencessselfscontexts getStringsstreamsread_utf8_stringsresultslens addString(sselfsuse_referencess is_references readLengthslengthsresult((sselfs*build/bdist.linux-x86_64/egg/pyamf/amf3.pys readStrings  cCs|i}|t@djo|ii|d?Sn|ii}t i |d}|i t j o||i 7}n|ii||SdS(sk Read date from the stream. The timezone is ignored as the date is always in UTC. iif1000.0N(sselfsreadUnsignedIntegersrefs REFERENCE_BITscontexts getObjectsstreams read_doublesmssutils get_datetimesresultstimezone_offsetsNones addObject(sselfsresultsmssref((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pysreadDates cCs4|i}|t@djo|ii|d?Sn|dL}|iid}|djoHg}|ii |x't |D]}|i |iqW|Snti}|ii |x7|djo)|i||<|iid}qWx*t |D]}|i}|||} iisutf8sN(sselfsreadUnsignedIntegerssizes REFERENCE_BITscontexts getObjects readStringsencodeskeysresults addObjectsxrangesisappends readElementspyamfs MixedArraysel(sselfselsisresultskeyssize((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys readArrays0         cCsh|t@dj}|dL}|o#|ii|}||ifSn|i}t }|djo t i }nyt i |}Wn<t ij o-|iont it i|}nXt|}|d@|_|d?|_g|_|idjoCx@t|iD]+}|iid}|ii|qWn|ii||i||fSdS(s9 Reads class definition from the stream. iisiisutf8N(srefs REFERENCE_BITsis_refsselfscontextsgetClassByReferences class_defsaliass readStringsnamesNonespyamfsASObjectsget_class_aliassUnknownClassAliassstrictsTypedObjectClassAliass TypedObjectsClassDefinitionsencodingsattr_lensstatic_propertiessxrangesisencodeskeysappendsaddClasssklass(sselfsrefsnamesisis_refsaliasskeys class_def((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys_getClassDefinitions6         c s|tjo i}nd}d}i}|t@djo>ii |d?}|t joi |}n|Sn|dL}i |\}}|id}t}ii||ititifjo|itne|itijo||||||n4|itijo|||ntid|i||d|t joi |}n|SdS(s Reads an object from the stream. @raise pyamf.EncodeError: Decoding an object in amf3 tagged as amf0 only is not allowed. @raise pyamf.DecodeError: Unknown object encoding. cs(x!|iD]}i||} N(sselfs_readXML(sself((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys readXMLStringfscCs|itSdS(s Read a legacy XML Document from the stream. @return: The XML Document. @rtype: L{ET} N(sselfs_readXMLsTrue(sself((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pysreadXMLpscCs|i}|t@djo|ii|d?Sn|ii|d?}yt i |}t }Wnt i j o t}nXt|d|i}||_ |ii||SdS(s Reads a string of data from the stream. Detects if the L{ByteArray} was compressed using C{zlib}. @see: L{ByteArray} @note: This is not supported in ActionScript 1.0 and 2.0. iiscontextN(sselfsreadUnsignedIntegersrefs REFERENCE_BITscontexts getObjectsstreamsreadsbufferszlibs decompresssTrues compressedserrorsFalses ByteArraysobjs addObject(sselfsbuffers compressedsobjsref((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys readByteArrayys    ()s__name__s __module__s__doc__sContexts context_classsTYPE_UNDEFINEDs TYPE_NULLsTYPE_BOOL_FALSEsTYPE_BOOL_TRUEs TYPE_INTEGERs TYPE_NUMBERs TYPE_STRINGsTYPE_XMLs TYPE_DATEs TYPE_ARRAYs TYPE_OBJECTsTYPE_XMLSTRINGsTYPE_BYTEARRAYstype_maps__init__s readUndefinedsreadNulls readBoolFalses readBoolTrues readNumbersreadUnsignedIntegersreadSignedIntegersFalses readIntegersTrues readStringsreadDates readArrays_getClassDefinitionsNones readObjectsreadProxyObjects_readXMLs readXMLStringsreadXMLs readByteArray(((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pysDecoder,s, {        + * :  sEncoderc BstZdZeZeieieiei ei ei ei fdfe fdfeifdfeefdfefdfeidfefdfeieieifdfeifd feifd feieifd feieifd fg Zd Z e!e"dZ#dZ$dZ%dZ&dZ'dZ(dZ)dZ*dZ+e!dZ,e!dZ-e!e"dZ.e!e"dZ/dZ0e!e"dZ1e!dZ2e!e"dZ3RS(s& Encodes an AMF3 data stream. s writeFuncs writeBooleans writeNulls writeIntegers writeNumbers writeStringswriteByteArrays writeDateswriteXMLswriteUndefineds writeClasss writeInstancecOsD|idt|_|idt|_tii |||dS(Ns use_proxiessstring_references( skwargsspopsuse_proxies_defaultsselfs use_proxiessTruesstring_referencesspyamfs BaseEncoders__init__sargs(sselfsargsskwargs((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys__init__scCsP|i|}|tjotid|fn||d|d|dS(s  Writes the data. @param data: The data to be encoded to the AMF3 data stream. @type data: C{mixed} @param use_references: Default is C{True}. @type use_references: C{bool} @raise EncodeError: Cannot find encoder func for C{data}. sUnknown type %rsuse_referencess use_proxiesN( sselfs_writeElementFuncsdatasfuncsNonespyamfs EncodeErrorsuse_referencess use_proxies(sselfsdatasuse_referencess use_proxiessfunc((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys writeElements  cOstiddS(s/ Classes cannot be serialised. s"Class objects cannot be serialisedN(spyamfs EncodeError(sselfsargsskwargs((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys writeClassscOs|iitdS(sC Writes an C{pyamf.Undefined} value to the stream. N(sselfsstreamswritesTYPE_UNDEFINED(sselfsargsskwargs((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pyswriteUndefinedscOs|iitdS(s7 Writes a C{null} value to the stream. N(sselfsstreamswrites TYPE_NULL(sselfsargsskwargs((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys writeNullscKs,t}| o t}n|ii|dS(s1 Writes a Boolean to the stream. N(sTYPE_BOOL_TRUEstsnsTYPE_BOOL_FALSEsselfsstreamswrite(sselfsnskwargsst((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys writeBooleans  cCsVy|iit|Wn7tj o+t|t|<|iit|nXdS(s AMF3 integers are encoded. @param n: The integer data to be encoded to the AMF3 data stream. @type n: integer data @see: U{Parsing Integers on OSFlash } for more info. N(sselfsstreamswritesENCODED_INT_CACHEsnsKeyErrors encode_int(sselfsn((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys _writeIntegers cKs_|tjp |tjo|it|dSn|iit|iit |dS(s Writes an integer to the stream. @type n: integer data @param n: The integer data to be encoded to the AMF3 data stream. @type use_references: C{bool} @kwarg use_references: Default is C{True}. N( sns MIN_29B_INTs MAX_29B_INTsselfs writeNumbersfloatsstreamswrites TYPE_INTEGERs encode_int(sselfsnskwargs((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys writeIntegers cKs$|iit|ii|dS(sJ Writes a float to the stream. @type n: C{float} N(sselfsstreamswrites TYPE_NUMBERs write_doublesn(sselfsnskwargs((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys writeNumberscKs|djo|iitdSnt|}|tjo |}n<|t jo|i d}nt |i d}|}|i oL|i i |}|tj o|i|d>dSn|i i|n|it|d>tB|ii|dS(s Writes a raw string to the stream. @type n: C{str} or C{unicode} @param n: The string data to be encoded to the AMF3 data stream. sNsutf8i(snsselfsstreams write_uchars REFERENCE_BITstypestsstrsbytessunicodesencodesstring_referencesscontextsgetStringReferencesrefsNones _writeIntegers addStringslenswrite(sselfsnskwargssrefsbytesst((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys _writeString s&       cKs/|o|iitn|i||dS(s Writes a string to the stream. If C{n} is not a unicode string, an attempt will be made to convert it. @type n: C{basestring} @param n: The string data to be encoded to the AMF3 data stream. N(s writeTypesselfsstreamswrites TYPE_STRINGs _writeStringsnskwargs(sselfsns writeTypeskwargs((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys writeString0scKst|tiotid|fn|iit |t joL|i i |}|tj o|i|d>dSn|i i|n|iit|itj o||i8}nti|}|ii|ddS(s Writes a C{datetime} instance to the stream. @type n: L{datetime} @param n: The C{Date} data to be encoded to the AMF3 data stream. @type use_references: C{bool} @param use_references: Default is C{True}. s|A datetime.time instance was found but AMF3 has no way to encode time objects. Please use datetime.datetime instead (got:%r)iNf1000.0(s isinstancesnsdatetimestimespyamfs EncodeErrorsselfsstreamswrites TYPE_DATEsuse_referencessTruescontextsgetObjectReferencesrefsNones _writeIntegers addObjects write_uchars REFERENCE_BITstimezone_offsetsutils get_timestampsmss write_double(sselfsnsuse_referencesskwargssrefsms((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys writeDate=s  c CsG|tjo |i}n|of|ii|}|tjo)t|}|ii |||}n|i ||dt dSn|i it|oL|ii|}|tj o|i|d>dSn|ii|n|it|d>tB|i idgi}|D]}||i|q#~dS(sM Writes a C{tuple}, C{set} or C{list} to the stream. @type n: One of C{__builtin__.tuple}, C{__builtin__.set} or C{__builtin__.list} @param n: The C{list} data to be encoded to the AMF3 data stream. @type use_references: C{bool} @param use_references: Default is C{True}. s use_proxiesNi(s use_proxiessNonesselfscontextsgetObjectAliassnsref_objsArrayCollectionsproxyssetObjectAliass writeObjectsuse_referencessFalsesstreamswrites TYPE_ARRAYsgetObjectReferencesrefs _writeIntegers addObjectslens REFERENCE_BITs write_ucharsappends_[1]sxs writeElement( sselfsnsuse_referencess use_proxiessref_objsrefs_[1]sproxysx((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys writeList_s*       c Csd|jotidn|tjo |i}n|tjoo|ii|}|tjo2t ti |} |ii || | }n|i||dtdSn|iit|oL|ii|}|tj o|i|d>dSn|ii|n|i}g}g}xh|D]`} t| ttfo|i| q8t| t t!fo|i| q8t"dq8Wt#|} xM|D]E} | | jo djno!|i| ||i%| =qqW|i&t#|djo|ddjo8x5|D])} |it | ||i%| =q-Wn|it#|d>t'Bx,|D]$} |i(| |i)|| qW|ii*dx|D]} |i)|| qWdS(s Writes a C{dict} to the stream. @type n: C{__builtin__.dict} @param n: The C{dict} data to be encoded to the AMF3 data stream. @type use_references: C{bool} @param use_references: Default is C{True}. @raise ValueError: Non C{int}/C{str} key value found in the C{dict} @raise EncodeError: C{dict} contains empty string keys. ss&dicts cannot contain empty string keyss use_proxiesNis#Non int/str key value found in dicti(,snspyamfs EncodeErrors use_proxiessNonesselfsTruescontextsgetObjectAliassref_objs ObjectProxysASObjectsproxyssetObjectAliass writeObjectsuse_referencessFalsesstreamswrites TYPE_ARRAYsgetObjectReferencesrefs _writeIntegers addObjectskeyssint_keyssstr_keyssxs isinstancesintslongsappendsstrsunicodes ValueErrorslenslsindexssorts REFERENCE_BITs _writeStrings writeElements write_ucharsk( sselfsnsuse_referencess use_proxiessref_objsstr_keyssrefskeyssint_keyssproxyskslsx((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys writeDictsf            $ cKs|i}|tijo|i}|i|dSn|ii|n|i}|ii|} t}t}| o7t}| i}|io | itj o t}qnyti|}WnIti j o:t!i|}t!i#|}||dt|}nXt%|} |ii&| |i'|o|ii| ind}| i(t)i*jo|| i+d>7}nt,|| i(d>Bt-d>Bt-B}|ii|t,| id>t-B| _|io|ii/dn|i0|i|i1o|i2t3|dSn|i4|d|\}} |o| o5gi7}|i9D]} ||i0| q ~ngi7}|i9D]} ||i;|| qB~| i(t)i<jodSqn| i(t)i=joV| o;x8| i>D]&\} } |i0| |i;| qWn|ii/dndS( sA Writes an object to the stream. @param obj: The object data to be encoded to the AMF3 data stream. @type obj: object data @param use_references: Default is C{True}. @type use_references: C{bool} @raise EncodeError: Encoding an object in amf3 tagged as amf0 only. s use_proxiesNisdeferiiiscodec(@s use_proxiessNonesselfsTruesobjs __class__sdictscontextsgetObjectAliassref_objs ObjectProxysproxyssetObjectAliass writeObjectsuse_referencessFalsesstreamswrites TYPE_OBJECTsgetObjectReferencesrefs _writeIntegers addObjectsklssgetClasss definitionsaliass class_refs anonymouss referencespyamfsget_class_aliassUnknownClassAliassutils alias_klasssget_class_metasmetasClassDefinitionsaddClasssklasssencodingsObjectEncodingsEXTERNALsattr_lens encode_ints REFERENCE_BITsfinal_references write_uchars _writeStringsexternals __writeamf__s DataOutputsgetEncodableAttributesssasdasappends_[1]s static_attrssattrs writeElementsSTATICsDYNAMICs iteritemssvalue(sselfsobjsuse_referencess use_proxiessref_objs alias_klasssmetasfinal_referencesrefsdasproxysattrs definitionsvalues class_refs_[1]saliassklsssa((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys writeObjects~          #  55   cKs|iit|oL|ii|}|t j o|i |d>dSn|ii |nt |}t|}|i |d>tB|ii|dS(s Writes a L{ByteArray} to the data stream. @param n: The L{ByteArray} data to be encoded to the AMF3 data stream. @type n: L{ByteArray} @param use_references: Default is C{True}. @type use_references: C{bool} iN(sselfsstreamswritesTYPE_BYTEARRAYsuse_referencesscontextsgetObjectReferencesnsrefsNones _writeIntegers addObjectsstrsbufslensls REFERENCE_BIT(sselfsnsuse_referencesskwargssbufslsref((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pyswriteByteArrayas   cCs|ii|}|tjo t}nt}|tjo|i i t n|i i t |oL|ii|}|tj o|i|d>dSn|ii|n|itii|ddS(s Writes a XML string to the data stream. @type n: L{ET} @param n: The XML Document to be encoded to the AMF3 data stream. @type use_references: C{bool} @param use_references: Default is C{True}. iNsutf-8(sselfscontextsgetLegacyXMLReferencesnsisNonesTrues is_legacysFalsesstreamswritesTYPE_XMLSTRINGsTYPE_XMLsuse_referencessgetObjectReferencesrefs _writeIntegers addObjects _writeStringsutilsETstostring(sselfsnsuse_referencess use_proxiess is_legacysisref((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pyswriteXML{s    (4s__name__s __module__s__doc__sContexts context_classstypessBuiltinFunctionTypesBuiltinMethodTypes FunctionTypes GeneratorTypes ModuleTypes LambdaTypes MethodTypesboolsNoneTypesintslongsfloats StringTypess ByteArraysdatetimesdatestimesutils is_ET_elementspyamfs UndefinedTypes ClassTypesTypeTypes InstanceTypes ObjectTypestype_maps__init__sTruesNones writeElements writeClassswriteUndefineds writeNulls writeBooleans _writeIntegers writeIntegers writeNumbers _writeStrings writeStrings writeDates writeLists writeDicts writeInstances writeObjectswriteByteArrayswriteXML(((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pysEncoders*        # "+V p ccsMt|||}x4no,y|iVWqtij oPqXqWdS(s A helper function to decode an AMF3 datastream. @type stream: L{BufferedByteStream} @param stream: AMF3 data. @type context: L{Context} @param context: Context. iN(sDecodersstreamscontextsstrictsdecoders readElementspyamfsEOStream(sstreamscontextsstrictsdecoder((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pysdecodescOsS|idt}ti}t||}x|D]}|i |q4W|SdS(sC A helper function to encode an element into AMF3 format. @type args: List of args to encode. @keyword context: Any initial context to use. @type context: L{Context} @return: C{StringIO} type object containing the encoded AMF3 data. @rtype: L{BufferedByteStream} scontextN( skwargssgetsNonescontextsutilsBufferedByteStreamsbufsEncodersencodersargsselements writeElement(sargsskwargssencoderscontextselementsbuf((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pysencodes  cCs@|tjp |tjotdn|djo|d7}nd}t}|djo0|}|dL}|td|d?d @B7}n|d jo |td|d ?d @B7}n|d jo |td|d ?d @B7}n|tj o |}n|djo|t|d @7}n|t|d @7}|SdS(s Encodes an int as a variable length signed 29-bit integer as defined by the spec. @param n: The integer to be encoded @return: The encoded string @rtype: C{str} @raise OverflowError: Out of range. s Out of rangeii siiiiii?iiiN(sns MIN_29B_INTs MAX_29B_INTs OverflowErrorsbytessNones real_valueschr(sns real_valuesbytes((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys encode_ints*            cCsd}}|i}xQ|d@djo |djo2|dK}||d@O}|i}|d7}qW|djo|dK}||O}nS|dK}||O}|d@djo-|o|d 8}q|dK}|d7}n|Sd S( s Decode C{int}. iiiiiiiii N(snsresultsstreams read_ucharsbssigned(sstreamssignedsresultsbsn((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys decode_ints(         (s encode_ints decode_intii(7s__doc__stypessdatetimeszlibspyamfsutils pyamf.flexs ObjectProxysArrayCollectionsFalsesuse_proxies_defaultssets NameErrorssetssSetsTYPE_UNDEFINEDs TYPE_NULLsTYPE_BOOL_FALSEsTYPE_BOOL_TRUEs TYPE_INTEGERs TYPE_NUMBERs TYPE_STRINGsTYPE_XMLs TYPE_DATEs TYPE_ARRAYs TYPE_OBJECTsTYPE_XMLSTRINGsTYPE_BYTEARRAYs REFERENCE_BITs MAX_29B_INTs MIN_29B_INTsENCODED_INT_CACHEsObjectEncodingsobjects DataOutputs DataInputsBufferedByteStreams ByteArraysClassDefinitions BaseContextsContexts BaseDecodersDecoders BaseEncodersEncodersNonesdecodesencodes encode_ints decode_ints cpyamf.amf3s ImportErrorsregister_classsrangesx('s ObjectProxysTYPE_BOOL_FALSEssetspyamfs TYPE_INTEGERsdatetimes TYPE_STRINGs TYPE_NULLs TYPE_DATEsEncodersdecodes decode_ints REFERENCE_BITs DataInputs MIN_29B_INTsDecodersencodes TYPE_NUMBERsTYPE_BYTEARRAYs encode_intsClassDefinitionsObjectEncodingsENCODED_INT_CACHEsTYPE_UNDEFINEDsTYPE_BOOL_TRUEsContextsArrayCollectionstypessuse_proxies_defaults TYPE_OBJECTs ByteArraysutilsTYPE_XMLszlibs DataOutputs MAX_29B_INTsTYPE_XMLSTRINGs TYPE_ARRAYsx((s*build/bdist.linux-x86_64/egg/pyamf/amf3.pys?sh       4l  )  PK:-pyamf/adapters/_sqlalchemy_orm_collections.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE for details. """ SQLAlchemy adapter module. @see: U{SQLAlchemy homepage (external)} @since: 0.4 """ from sqlalchemy.orm import collections import pyamf from pyamf.adapters import util pyamf.add_type(collections.InstrumentedList, util.to_list) pyamf.add_type(collections.InstrumentedDict, util.to_dict) pyamf.add_type(collections.InstrumentedSet, util.to_set) PKR:I&Xpyamf/adapters/_array.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ `array` adapter module. Will convert all array.array instances to a python list before encoding. All type information is lost (but degrades nicely). @since: 0.5 """ import array import pyamf from pyamf.adapters import util if hasattr(array, 'array'): pyamf.add_type(array.ArrayType, util.to_list) PKm;} @since: 0.1b """ from django.db.models import query import pyamf from pyamf.adapters import util pyamf.add_type(query.QuerySet, util.to_list) PK;8!pyamf/adapters/_sqlalchemy_orm.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE for details. """ SQLAlchemy adapter module. @see: U{SQLAlchemy homepage (external)} @since: 0.4 """ from sqlalchemy import orm, __version__ try: from sqlalchemy.orm import class_mapper except ImportError: from sqlalchemy.orm.util import class_mapper import pyamf UnmappedInstanceError = None try: class_mapper(dict) except Exception, e: UnmappedInstanceError = e.__class__ class SaMappedClassAlias(pyamf.ClassAlias): KEY_ATTR = 'sa_key' LAZY_ATTR = 'sa_lazy' EXCLUDED_ATTRS = [ '_entity_name', '_instance_key', '_sa_adapter', '_sa_appender', '_sa_class_manager', '_sa_initiator', '_sa_instance_state', '_sa_instrumented', '_sa_iterator', '_sa_remover', '_sa_session_id', '_state' ] STATE_ATTR = '_sa_instance_state' if __version__.startswith('0.4'): STATE_ATTR = '_state' def getCustomProperties(self): self.mapper = class_mapper(self.klass) self.exclude_attrs.update(self.EXCLUDED_ATTRS) self.properties = [] for prop in self.mapper.iterate_properties: self.properties.append(prop.key) self.encodable_properties.update(self.properties) self.decodable_properties.update(self.properties) self.static_attrs.update(self.properties) def getEncodableAttributes(self, obj, **kwargs): """ Returns a C{tuple} containing a dict of static and dynamic attributes for C{obj}. """ sa, da = pyamf.ClassAlias.getEncodableAttributes(self, obj, **kwargs) if not da: da = {} lazy_attrs = [] # primary_key_from_instance actually changes obj.__dict__ if # primary key properties do not already exist in obj.__dict__ da[self.KEY_ATTR] = self.mapper.primary_key_from_instance(obj) for attr in self.properties: if attr not in obj.__dict__: lazy_attrs.append(attr) da[self.LAZY_ATTR] = lazy_attrs return sa, da def getDecodableAttributes(self, obj, attrs, **kwargs): """ """ attrs = pyamf.ClassAlias.getDecodableAttributes(self, obj, attrs, **kwargs) # Delete lazy-loaded attrs. # # Doing it this way ensures that lazy-loaded attributes are not # attached to the object, even if there is a default value specified # in the __init__ method. # # This is the correct behavior, because SQLAlchemy ignores __init__. # So, an object retreived from a DB with SQLAlchemy will not have a # lazy-loaded value, even if __init__ specifies a default value. if self.LAZY_ATTR in attrs: obj_state = None if hasattr(orm.attributes, 'instance_state'): obj_state = orm.attributes.instance_state(obj) for lazy_attr in attrs[self.LAZY_ATTR]: if lazy_attr in obj.__dict__: # Delete directly from the dict, so # SA callbacks are not triggered. del obj.__dict__[lazy_attr] # Delete from committed_state so SA thinks this attribute was # never modified. # # If the attribute was set in the __init__ method, # SA will think it is modified and will try to update # it in the database. if obj_state is not None: if lazy_attr in obj_state.committed_state: del obj_state.committed_state[lazy_attr] if lazy_attr in obj_state.dict: del obj_state.dict[lazy_attr] if lazy_attr in attrs: del attrs[lazy_attr] del attrs[self.LAZY_ATTR] if self.KEY_ATTR in attrs: del attrs[self.KEY_ATTR] return attrs def is_class_sa_mapped(klass): """ @rtype: C{bool} """ if not isinstance(klass, type): klass = type(klass) try: class_mapper(klass) except UnmappedInstanceError: return False return True pyamf.register_alias_type(SaMappedClassAlias, is_class_sa_mapped) PK:Jpyamf/adapters/__init__.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ The adapter package provides additional functionality for other Python packages. This includes registering classes, setting up type maps etc. @since: 0.1.0 """ import os.path import glob from pyamf.util import imports class PackageImporter(object): """ Package importer used for lazy module loading. """ def __init__(self, name): self.name = name def __call__(self, mod): __import__('%s.%s' % ('pyamf.adapters', self.name)) adapters_registered = False def register_adapters(): global adapters_registered if adapters_registered is True: return try: import pkg_resources packageDir = pkg_resources.resource_filename('pyamf', 'adapters') except: packageDir = os.path.dirname(__file__) for f in glob.glob(os.path.join(packageDir, '*.py')): mod = os.path.basename(f).split(os.path.extsep, 1)[0] if mod == '__init__' or not mod.startswith('_'): continue try: register_adapter(mod[1:].replace('_', '.'), PackageImporter(mod)) except ImportError: pass adapters_registered = True def register_adapter(mod, func): """ Registers a callable to be executed when a module is imported. If the module already exists then the callable will be executed immediately. You can register the same module multiple times, the callables will be executed in the order they were registered. The root module must exist (i.e. be importable) otherwise an C{ImportError} will be thrown. @param mod: The fully qualified module string, as used in the imports statement. E.g. 'foo.bar.baz'. The string must map to a module otherwise the callable will not fire. @type mod: C{str} @param func: The function to call when C{mod} is imported. This function must take one arg, the newly imported C{module} object. @type func: callable @raise TypeError: C{func} must be callable """ if not callable(func): raise TypeError('func must be callable') imports.when_imported(str(mod), func) PKm; o`*pyamf/adapters/_django_db_models_fields.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ C{django.db.models.fields} adapter module. @see: U{Django Project} @since: 0.4 """ from django.db.models import fields import pyamf def convert_NOT_PROVIDED(x, encoder): """ @rtype: L{Undefined} """ return pyamf.Undefined pyamf.add_type(lambda x: x is fields.NOT_PROVIDED, convert_NOT_PROVIDED) PKm;}`:800+pyamf/adapters/_django_utils_translation.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ C{django.utils.translation} adapter module. @see: U{Django Project} @since: 0.4.2 """ from django.utils.translation import ugettext_lazy import pyamf def convert_lazy(l, encoder=None): if l.__class__._delegate_unicode: return unicode(l) if l.__class__._delegate_str: return str(l) raise ValueError('Don\'t know how to convert lazy value %s' % (repr(l),)) pyamf.add_type(type(ugettext_lazy('foo')), convert_lazy) PKJc#;y y (pyamf/adapters/_django_db_models_base.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ C{django.db.models} adapter module. @see: U{Django Project} @since: 0.4.1 """ from django.db.models.base import Model from django.db.models import fields from django.db.models.fields import related, files import datetime import pyamf from pyamf.util import imports class DjangoReferenceCollection(dict): """ This helper class holds a dict of klass to pk/objects loaded from the underlying db. @since: 0.5 """ def _getClass(self, klass): if klass not in self.keys(): self[klass] = {} return self[klass] def getClassKey(self, klass, key): """ Return an instance based on klass/key. If an instance cannot be found then L{KeyError} is raised. @param klass: The class of the instance. @param key: The primary_key of the instance. @return: The instance linked to the C{klass}/C{key}. @rtype: Instance of L{klass}. """ d = self._getClass(klass) return d[key] def addClassKey(self, klass, key, obj): """ Adds an object to the collection, based on klass and key. @param klass: The class of the object. @param key: The datastore key of the object. @param obj: The loaded instance from the datastore. """ d = self._getClass(klass) d[key] = obj class DjangoClassAlias(pyamf.ClassAlias): """ """ def getCustomProperties(self): self.fields = {} self.relations = {} self.columns = [] self.meta = self.klass._meta for x in self.meta.local_fields: if isinstance(x, files.FileField): self.readonly_attrs.update([x.name]) if not isinstance(x, related.ForeignKey): self.fields[x.name] = x else: self.relations[x.name] = x self.columns.append(x.attname) for k, v in self.klass.__dict__.iteritems(): if isinstance(v, related.ReverseManyRelatedObjectsDescriptor): self.fields[k] = v.field parent_fields = [] for field in self.meta.parents.values(): parent_fields.append(field.attname) del self.relations[field.name] self.exclude_attrs.update(parent_fields) props = self.fields.keys() self.static_attrs.update(props) self.encodable_properties.update(props) self.decodable_properties.update(props) def _compile_base_class(self, klass): if klass is Model: return pyamf.ClassAlias._compile_base_class(self, klass) def _encodeValue(self, field, value): if value is fields.NOT_PROVIDED: return pyamf.Undefined if value is None: return value # deal with dates .. if isinstance(field, fields.DateTimeField): return value elif isinstance(field, fields.DateField): return datetime.datetime(value.year, value.month, value.day, 0, 0, 0) elif isinstance(field, fields.TimeField): return datetime.datetime(1970, 1, 1, value.hour, value.minute, value.second, value.microsecond) elif isinstance(value, files.FieldFile): return value.name return value def _decodeValue(self, field, value): if value is pyamf.Undefined: return fields.NOT_PROVIDED if isinstance(field, fields.AutoField) and value == 0: return None elif isinstance(field, fields.DateTimeField): # deal with dates return value elif isinstance(field, fields.DateField): if not value: return None return datetime.date(value.year, value.month, value.day) elif isinstance(field, fields.TimeField): if not value: return None return datetime.time(value.hour, value.minute, value.second, value.microsecond) return value def getEncodableAttributes(self, obj, **kwargs): sa, da = pyamf.ClassAlias.getEncodableAttributes(self, obj, **kwargs) for name, prop in self.fields.iteritems(): if name not in sa: continue if isinstance(prop, related.ManyToManyField): sa[name] = [x for x in getattr(obj, name).all()] else: sa[name] = self._encodeValue(prop, getattr(obj, name)) if not da: da = {} keys = da.keys() for key in keys: if key.startswith('_'): del da[key] elif key in self.columns: del da[key] for name, relation in self.relations.iteritems(): if '_%s_cache' % name in obj.__dict__: da[name] = getattr(obj, name) else: da[name] = pyamf.Undefined if not da: da = None return sa, da def getDecodableAttributes(self, obj, attrs, **kwargs): attrs = pyamf.ClassAlias.getDecodableAttributes(self, obj, attrs, **kwargs) for n in self.decodable_properties: f = self.fields[n] attrs[f.attname] = self._decodeValue(f, attrs[n]) # primary key of django object must always be set first for # relationships with other model objects to work properly # and dict.iteritems() does not guarantee order # # django also forces the use only one attribute as primary key, so # our obj._meta.pk.attname check is sufficient) try: setattr(obj, obj._meta.pk.attname, attrs[obj._meta.pk.attname]) del attrs[obj._meta.pk.attname] except KeyError: pass return attrs def getDjangoObjects(context): """ Returns a reference to the C{django_objects} on the context. If it doesn't exist then it is created. @param context: The context to load the C{django_objects} index from. @type context: Instance of L{pyamf.BaseContext} @return: The C{django_objects} index reference. @rtype: Instance of L{DjangoReferenceCollection} @since: 0.5 """ if not hasattr(context, 'django_objects'): context.django_objects = DjangoReferenceCollection() return context.django_objects def writeDjangoObject(self, obj, *args, **kwargs): """ The Django ORM creates new instances of objects for each db request. This is a problem for PyAMF as it uses the id(obj) of the object to do reference checking. We could just ignore the problem, but the objects are conceptually the same so the effort should be made to attempt to resolve references for a given object graph. We create a new map on the encoder context object which contains a dict of C{object.__class__: {key1: object1, key2: object2, .., keyn: objectn}}. We use the primary key to do the reference checking. @since: 0.5 """ if not isinstance(obj, Model): self.writeNonDjangoObject(obj, *args, **kwargs) return context = self.context kls = obj.__class__ s = obj.pk django_objects = getDjangoObjects(context) try: referenced_object = django_objects.getClassKey(kls, s) except KeyError: referenced_object = obj django_objects.addClassKey(kls, s, obj) self.writeNonDjangoObject(referenced_object, *args, **kwargs) def install_django_reference_model_hook(mod): """ Called when L{pyamf.amf0} or L{pyamf.amf3} are imported. Attaches the L{writeDjangoObject} method to the C{Encoder} class in that module. @param mod: The module imported. @since: 0.4.1 """ if not hasattr(mod.Encoder, 'writeNonDjangoObject'): mod.Encoder.writeNonDjangoObject = mod.Encoder.writeObject mod.Encoder.writeObject = writeDjangoObject # initialise the module here: hook into pyamf pyamf.register_alias_type(DjangoClassAlias, Model) # hook the L{writeDjangobject} method to the Encoder class on import imports.when_imported('pyamf.amf0', install_django_reference_model_hook) imports.when_imported('pyamf.amf3', install_django_reference_model_hook) PK;S3..*pyamf/adapters/_google_appengine_ext_db.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Google App Engine adapter module. Sets up basic type mapping and class mappings for using the Datastore API in Google App Engine. @see: U{Datastore API on Google App Engine (external) } @since: 0.3.1 """ from google.appengine.ext import db from google.appengine.ext.db import polymodel import datetime import pyamf from pyamf.util import imports from pyamf.adapters import util class ModelStub(object): """ This class represents a L{db.Model} or L{db.Expando} class as the typed object is being read from the AMF stream. Once the attributes have been read from the stream and through the magic of Python, the instance of this class will be converted into the correct type. @ivar klass: The referenced class either L{db.Model} or L{db.Expando}. This is used so we can proxy some of the method calls during decoding. @type klass: L{db.Model} or L{db.Expando} @see: L{DataStoreClassAlias.applyAttributes} """ def __init__(self, klass): self.klass = klass def properties(self): return self.klass.properties() def dynamic_properties(self): return [] class GAEReferenceCollection(dict): """ This helper class holds a dict of klass to key/objects loaded from the Datastore. @since: 0.4.1 """ def _getClass(self, klass): if not issubclass(klass, (db.Model, db.Expando)): raise TypeError('expected db.Model/db.Expando class, got %s' % (klass,)) if klass not in self.keys(): self[klass] = {} return self[klass] def getClassKey(self, klass, key): """ Return an instance based on klass/key. If an instance cannot be found then L{KeyError} is raised. @param klass: The class of the instance. @param key: The key of the instance. @return: The instance linked to the C{klass}/C{key}. @rtype: Instance of L{klass}. """ if not isinstance(key, basestring): raise TypeError('basestring type expected for test, got %s' % (repr(key),)) d = self._getClass(klass) return d[key] def addClassKey(self, klass, key, obj): """ Adds an object to the collection, based on klass and key. @param klass: The class of the object. @param key: The datastore key of the object. @param obj: The loaded instance from the datastore. """ if not isinstance(key, basestring): raise TypeError('basestring type expected for test, got %s' % (repr(key),)) d = self._getClass(klass) d[key] = obj class DataStoreClassAlias(pyamf.ClassAlias): """ This class contains all the business logic to interact with Google's Datastore API's. Any L{db.Model} or L{db.Expando} classes will use this class alias for encoding/decoding. We also add a number of indexes to the encoder context to aggressively decrease the number of Datastore API's that we need to complete. """ # The name of the attribute used to represent the key KEY_ATTR = '_key' def _compile_base_class(self, klass): if klass in (db.Model, polymodel.PolyModel): return pyamf.ClassAlias._compile_base_class(self, klass) def getCustomProperties(self): props = [self.KEY_ATTR] self.reference_properties = {} self.properties = {} reverse_props = [] for name, prop in self.klass.properties().iteritems(): self.properties[name] = prop props.append(name) if isinstance(prop, db.ReferenceProperty): self.reference_properties[name] = prop if issubclass(self.klass, polymodel.PolyModel): del self.properties['_class'] props.remove('_class') # check if the property is a defined as a collection_name. These types # of properties are read-only and the datastore freaks out if you # attempt to meddle with it. We delete the attribute entirely .. for name, value in self.klass.__dict__.iteritems(): if isinstance(value, db._ReverseReferenceProperty): reverse_props.append(name) self.static_attrs.update(props) self.encodable_properties.update(self.properties.keys()) self.decodable_properties.update(self.properties.keys()) self.readonly_attrs.update(reverse_props) if not self.reference_properties: self.reference_properties = None if not self.properties: self.properties = None def getEncodableAttributes(self, obj, codec=None): sa, da = pyamf.ClassAlias.getEncodableAttributes(self, obj, codec=codec) sa[self.KEY_ATTR] = str(obj.key()) if obj.is_saved() else None gae_objects = getGAEObjects(codec.context) if codec else None if self.reference_properties and gae_objects: for name, prop in self.reference_properties.iteritems(): klass = prop.reference_class key = prop.get_value_for_datastore(obj) if not key: continue key = str(key) try: sa[name] = gae_objects.getClassKey(klass, key) except KeyError: ref_obj = getattr(obj, name) gae_objects.addClassKey(klass, key, ref_obj) sa[name] = ref_obj if da: for k, v in da.copy().iteritems(): if k.startswith('_'): del da[k] if not da: da = {} for attr in obj.dynamic_properties(): da[attr] = getattr(obj, attr) if not da: da = None return sa, da def createInstance(self, codec=None): return ModelStub(self.klass) def getDecodableAttributes(self, obj, attrs, codec=None): try: key = attrs[self.KEY_ATTR] except KeyError: key = attrs[self.KEY_ATTR] = None attrs = pyamf.ClassAlias.getDecodableAttributes(self, obj, attrs, codec=codec) del attrs[self.KEY_ATTR] new_obj = None # attempt to load the object from the datastore if KEY_ATTR exists. if key and codec: new_obj = loadInstanceFromDatastore(self.klass, key, codec) # clean up the stub if isinstance(obj, ModelStub) and hasattr(obj, 'klass'): del obj.klass if new_obj: obj.__dict__ = new_obj.__dict__.copy() obj.__class__ = self.klass apply_init = True if self.properties: for k in [k for k in attrs.keys() if k in self.properties.keys()]: prop = self.properties[k] v = attrs[k] if isinstance(prop, db.FloatProperty) and isinstance(v, (int, long)): attrs[k] = float(v) elif isinstance(prop, db.ListProperty) and v is None: attrs[k] = [] elif isinstance(v, datetime.datetime): # Date/Time Property fields expect specific types of data # whereas PyAMF only decodes into datetime.datetime objects. if isinstance(prop, db.DateProperty): attrs[k] = v.date() elif isinstance(prop, db.TimeProperty): attrs[k] = v.time() if new_obj is None and isinstance(v, ModelStub) and prop.required and k in self.reference_properties: apply_init = False del attrs[k] # If the object does not exist in the datastore, we must fire the # class constructor. This sets internal attributes that pyamf has # no business messing with .. if new_obj is None and apply_init is True: obj.__init__(**attrs) return attrs def getGAEObjects(context): """ Returns a reference to the C{gae_objects} on the context. If it doesn't exist then it is created. @param context: The context to load the C{gae_objects} index from. @type context: Instance of L{pyamf.BaseContext} @return: The C{gae_objects} index reference. @rtype: Instance of L{GAEReferenceCollection} @since: 0.4.1 """ if not hasattr(context, 'gae_objects'): context.gae_objects = GAEReferenceCollection() return context.gae_objects def loadInstanceFromDatastore(klass, key, codec=None): """ Attempt to load an instance from the datastore, based on C{klass} and C{key}. We create an index on the codec's context (if it exists) so we can check that first before accessing the datastore. @param klass: The class that will be loaded from the datastore. @type klass: Sub-class of L{db.Model} or L{db.Expando} @param key: The key which is used to uniquely identify the instance in the datastore. @type key: C{str} @param codec: The codec to reference the C{gae_objects} index. If supplied,The codec must have have a context attribute. @type codec: Instance of L{pyamf.BaseEncoder} or L{pyamf.BaseDecoder} @return: The loaded instance from the datastore. @rtype: Instance of C{klass}. @since: 0.4.1 """ if not issubclass(klass, (db.Model, db.Expando)): raise TypeError('expected db.Model/db.Expando class, got %s' % (klass,)) if not isinstance(key, basestring): raise TypeError('string expected for key, got %s', (repr(key),)) key = str(key) if codec is None: return klass.get(key) gae_objects = getGAEObjects(codec.context) try: return gae_objects.getClassKey(klass, key) except KeyError: pass obj = klass.get(key) gae_objects.addClassKey(klass, key, obj) return obj def writeGAEObject(self, object, *args, **kwargs): """ The GAE Datastore creates new instances of objects for each get request. This is a problem for PyAMF as it uses the id(obj) of the object to do reference checking. We could just ignore the problem, but the objects are conceptually the same so the effort should be made to attempt to resolve references for a given object graph. We create a new map on the encoder context object which contains a dict of C{object.__class__: {key1: object1, key2: object2, .., keyn: objectn}}. We use the datastore key to do the reference checking. @since: 0.4.1 """ if not (isinstance(object, db.Model) and object.is_saved()): self.writeNonGAEObject(object, *args, **kwargs) return context = self.context kls = object.__class__ s = str(object.key()) gae_objects = getGAEObjects(context) try: referenced_object = gae_objects.getClassKey(kls, s) except KeyError: referenced_object = object gae_objects.addClassKey(kls, s, object) self.writeNonGAEObject(referenced_object, *args, **kwargs) def install_gae_reference_model_hook(mod): """ Called when L{pyamf.amf0} or L{pyamf.amf3} are imported. Attaches the L{writeGAEObject} method to the C{Encoder} class in that module. @param mod: The module imported. @since: 0.4.1 """ if not hasattr(mod.Encoder, 'writeNonGAEObject'): mod.Encoder.writeNonGAEObject = mod.Encoder.writeObject mod.Encoder.writeObject = writeGAEObject # initialise the module here: hook into pyamf pyamf.add_type(db.Query, util.to_list) pyamf.register_alias_type(DataStoreClassAlias, db.Model, db.Expando) # hook the L{writeGAEObject} method to the Encoder class on import imports.when_imported('pyamf.amf0', install_gae_reference_model_hook) imports.when_imported('pyamf.amf3', install_gae_reference_model_hook) PK:u3;t.pyamf/adapters/_sqlalchemy_orm_collections.pyc; bZJc@sodZdklZdkZdklZeieieieiei ei eiei ei dS(sm SQLAlchemy adapter module. @see: U{SQLAlchemy homepage (external)} @since: 0.4 (s collectionsN(sutil( s__doc__ssqlalchemy.orms collectionsspyamfspyamf.adapterssutilsadd_typesInstrumentedListsto_listsInstrumentedDictsto_dictsInstrumentedSetsto_set(sutilspyamfs collections((sJbuild/bdist.linux-x86_64/egg/pyamf/adapters/_sqlalchemy_orm_collections.pys? s    PK:u3;4 ++pyamf/adapters/_array.pyc; L]Jc@sSdZdkZdkZdklZeedoeieieindS(s `array` adapter module. Will convert all array.array instances to a python list before encoding. All type information is lost (but degrades nicely). @since: 0.5 N(sutilsarray( s__doc__sarrayspyamfspyamf.adapterssutilshasattrsadd_types ArrayTypesto_list(sutilsarrayspyamf((s5build/bdist.linux-x86_64/egg/pyamf/adapters/_array.pys? s    PK:u3; Bpyamf/adapters/_collections.pyc; -xJc@s}dZdkZdkZdklZeedoeieieineedoeiei ei ndS(s* collections adapter module. @since: 0.5 N(sutilsdeques defaultdict( s__doc__s collectionsspyamfspyamf.adapterssutilshasattrsadd_typesdequesto_lists defaultdictsto_dict(sutilspyamfs collections((s;build/bdist.linux-x86_64/egg/pyamf/adapters/_collections.pys?s   PK:u3;#DDpyamf/adapters/_decimal.pyc; VJc@sLdZdkZdkZdZeedoeieiendS(s1 Adapter for the C{decimal} module. @since: 0.4 NcCsU|tj ot|tio"|itjot|SqBnti ddS(s Called when an instance of L{decimal.Decimal} is about to be encoded to an AMF stream. @param x: The L{decimal.Decimal} instance to encode. @param encoder: The L{pyamf.BaseEncoder} instance about to perform the operation. @return: If the encoder is in 'strict' mode then C{x} will be converted to a float. Otherwise an L{pyamf.EncodeError} with a friendly message is raised. sUnable to encode decimal.Decimal instances as there is no way to guarantee exact conversion. Use strict=False to convert to a float.N( sencodersNones isinstancespyamfs BaseEncodersstrictsFalsesfloatsxs EncodeError(sxsencoder((s7build/bdist.linux-x86_64/egg/pyamf/adapters/_decimal.pysconvert_Decimals  sDecimal(s__doc__sdecimalspyamfsconvert_Decimalshasattrsadd_typesDecimal(sconvert_Decimalsdecimalspyamf((s7build/bdist.linux-x86_64/egg/pyamf/adapters/_decimal.pys?s    PK:u3;rWpyamf/adapters/_sets.pyc; bZJc@s}dZdkZdkZdklZeedoeieieineedoeiei eindS(s5 Adapter for the stdlib C{sets} module. @since: 0.4 N(sutils ImmutableSetsSet( s__doc__ssetsspyamfspyamf.adapterssutilshasattrsadd_types ImmutableSetsto_tuplesSet(sutilspyamfssets((s4build/bdist.linux-x86_64/egg/pyamf/adapters/_sets.pys?s   PK:u3;S655pyamf/adapters/util.pyc; Jc@sbdZdkZeed odklZndZdZdZdZ dZ dS( s+ Useful helpers for adapters. @since: 0.4 Nsset(sSetcCst|SdS(sM Converts an arbitrary object C{obj} to a list. @rtype: L{list} N(slistsobj(sobjsencoder((s3build/bdist.linux-x86_64/egg/pyamf/adapters/util.pysto_listscCst|SdS(sM Converts an arbitrary object C{obj} to a dict. @rtype: L{dict} N(sdictsobj(sobjsencoder((s3build/bdist.linux-x86_64/egg/pyamf/adapters/util.pysto_dictscCst|SdS(sK Converts an arbitrary object C{obj} to a set. @rtype: L{set} N(ssetsobj(sobjsencoder((s3build/bdist.linux-x86_64/egg/pyamf/adapters/util.pysto_set"scCst|SdS(sO Converts an arbitrary object C{obj} to a tuple. @rtype: L{tuple} N(stuplesx(sxsencoder((s3build/bdist.linux-x86_64/egg/pyamf/adapters/util.pysto_tuple+scCst|SdS(s` Converts an arbitrary object C{obj} to a string. @rtype: L{tuple} @since: 0.5 N(sstrsx(sxsencoder((s3build/bdist.linux-x86_64/egg/pyamf/adapters/util.pys to_string3s( s__doc__s __builtin__shasattrssetssSetssetsto_liststo_dictsto_setsto_tuples to_string(sto_setssetsto_tuplesto_lists __builtin__s to_stringsto_dict((s3build/bdist.linux-x86_64/egg/pyamf/adapters/util.pys?s  PK:u3;/p99*pyamf/adapters/_django_db_models_query.pyc; -xJc@sCdZdklZdkZdklZeieieidS(s Django query adapter module. Sets up basic type mapping and class mappings for a Django models. @see: U{Django Project} @since: 0.1b (squeryN(sutil( s__doc__sdjango.db.modelssqueryspyamfspyamf.adapterssutilsadd_typesQuerySetsto_list(sutilsqueryspyamf((sFbuild/bdist.linux-x86_64/egg/pyamf/adapters/_django_db_models_query.pys? s   PK:u3;8W"pyamf/adapters/_sqlalchemy_orm.pyc; Jc@sdZdklZlZydklZWn ej odklZnXdkZe Z yee Wne j oZ e iZ nXdeifdYZdZeieedS(sm SQLAlchemy adapter module. @see: U{SQLAlchemy homepage (external)} @since: 0.4 (sorms __version__(s class_mapperNsSaMappedClassAliasc BsytZdZdZddddddd d d d d dg Zd Zeido dZndZdZ dZ RS(Nssa_keyssa_lazys _entity_names _instance_keys _sa_adapters _sa_appenders_sa_class_managers _sa_initiators_sa_instance_states_sa_instrumenteds _sa_iterators _sa_removers_sa_session_ids_states0.4cCst|i|_|ii|ig|_x'|iiD]}|ii |i q;W|i i|i|i i|i|ii|idS(N(s class_mappersselfsklasssmappers exclude_attrssupdatesEXCLUDED_ATTRSs propertiessiterate_propertiesspropsappendskeysencodable_propertiessdecodable_propertiess static_attrs(sselfsprop((s>build/bdist.linux-x86_64/egg/pyamf/adapters/_sqlalchemy_orm.pysgetCustomProperties,s  cKstii|||\}}| o h}ng}|i i |||i build/bdist.linux-x86_64/egg/pyamf/adapters/_sqlalchemy_orm.pysgetEncodableAttributes9s   cKs)tii||||}|i|jot}t t i dot i i |}nx||iD]}||ijo|i|=n|tj o@||ijo|i|=n||ijo|i|=qn||jo ||=qhqhW||i=n|i|jo||i=n|SdS(s sinstance_stateN(spyamfs ClassAliassgetDecodableAttributessselfsobjsattrsskwargss LAZY_ATTRsNones obj_stateshasattrsorms attributessinstance_states lazy_attrs__dict__scommitted_statesdictsKEY_ATTR(sselfsobjsattrsskwargss lazy_attrs obj_state((s>build/bdist.linux-x86_64/egg/pyamf/adapters/_sqlalchemy_orm.pysgetDecodableAttributesQs*   ( s__name__s __module__sKEY_ATTRs LAZY_ATTRsEXCLUDED_ATTRSs STATE_ATTRs __version__s startswithsgetCustomPropertiessgetEncodableAttributessgetDecodableAttributes(((s>build/bdist.linux-x86_64/egg/pyamf/adapters/_sqlalchemy_orm.pysSaMappedClassAliass*  cCsQt|t ot|}nyt|Wntj o tSnXtSdS(s @rtype: C{bool} N(s isinstancesklassstypes class_mappersUnmappedInstanceErrorsFalsesTrue(sklass((s>build/bdist.linux-x86_64/egg/pyamf/adapters/_sqlalchemy_orm.pysis_class_sa_mappeds (s__doc__s sqlalchemysorms __version__ssqlalchemy.orms class_mappers ImportErrorssqlalchemy.orm.utilspyamfsNonesUnmappedInstanceErrorsdicts Exceptionses __class__s ClassAliassSaMappedClassAliassis_class_sa_mappedsregister_alias_type(sesSaMappedClassAliassis_class_sa_mappedspyamfs class_mappersormsUnmappedInstanceErrors __version__((s>build/bdist.linux-x86_64/egg/pyamf/adapters/_sqlalchemy_orm.pys? s e PK:u3;1: : pyamf/adapters/__init__.pyc; bZJc@sWdZdkZdkZdklZdefdYZea dZ dZ dS(s The adapter package provides additional functionality for other Python packages. This includes registering classes, setting up type maps etc. @since: 0.1.0 N(simportssPackageImportercBs tZdZdZdZRS(s8 Package importer used for lazy module loading. cCs ||_dS(N(snamesself(sselfsname((s7build/bdist.linux-x86_64/egg/pyamf/adapters/__init__.pys__init__scCstdd|ifdS(Ns%s.%sspyamf.adapters(s __import__sselfsname(sselfsmod((s7build/bdist.linux-x86_64/egg/pyamf/adapters/__init__.pys__call__s(s__name__s __module__s__doc__s__init__s__call__(((s7build/bdist.linux-x86_64/egg/pyamf/adapters/__init__.pysPackageImporters  cCs ttjodSnydk}|idd}Wntiit}nXxt i tii |dD]}tii |i tiidd}|djp|id oqony't|diddt|Wqotj oqoXqoWtadS( Nspyamfsadapterss*.pyiis__init__s_s.(sadapters_registeredsTrues pkg_resourcessresource_filenames packageDirsosspathsdirnames__file__sglobsjoinsfsbasenamessplitsextsepsmods startswithsregister_adaptersreplacesPackageImporters ImportError(sfs pkg_resourcess packageDirsmod((s7build/bdist.linux-x86_64/egg/pyamf/adapters/__init__.pysregister_adapterss$  (' cCs8t| otdntit||dS(s Registers a callable to be executed when a module is imported. If the module already exists then the callable will be executed immediately. You can register the same module multiple times, the callables will be executed in the order they were registered. The root module must exist (i.e. be importable) otherwise an C{ImportError} will be thrown. @param mod: The fully qualified module string, as used in the imports statement. E.g. 'foo.bar.baz'. The string must map to a module otherwise the callable will not fire. @type mod: C{str} @param func: The function to call when C{mod} is imported. This function must take one arg, the newly imported C{module} object. @type func: callable @raise TypeError: C{func} must be callable sfunc must be callableN(scallablesfuncs TypeErrorsimportss when_importedsstrsmod(smodsfunc((s7build/bdist.linux-x86_64/egg/pyamf/adapters/__init__.pysregister_adapter8s( s__doc__sos.pathsossglobs pyamf.utilsimportssobjectsPackageImportersFalsesadapters_registeredsregister_adapterssregister_adapter(sregister_adapterssimportssglobsPackageImportersregister_adaptersos((s7build/bdist.linux-x86_64/egg/pyamf/adapters/__init__.pys? s     PK:u3;ّ+pyamf/adapters/_django_db_models_fields.pyc; -xJc@s<dZdklZdkZdZeidedS(so C{django.db.models.fields} adapter module. @see: U{Django Project} @since: 0.4 (sfieldsNcCs tiSdS(s/ @rtype: L{Undefined} N(spyamfs Undefined(sxsencoder((sGbuild/bdist.linux-x86_64/egg/pyamf/adapters/_django_db_models_fields.pysconvert_NOT_PROVIDEDscCs |tijS(N(sxsfieldss NOT_PROVIDED(sx((sGbuild/bdist.linux-x86_64/egg/pyamf/adapters/_django_db_models_fields.pyss(s__doc__sdjango.db.modelssfieldsspyamfsconvert_NOT_PROVIDEDsadd_type(sfieldsspyamfsconvert_NOT_PROVIDED((sGbuild/bdist.linux-x86_64/egg/pyamf/adapters/_django_db_models_fields.pys? s   PK:u3;!G,pyamf/adapters/_django_utils_translation.pyc; -xJc@sHdZdklZdkZedZeieededS(sr C{django.utils.translation} adapter module. @see: U{Django Project} @since: 0.4.2 (s ugettext_lazyNcCsS|iiot|Sn|iiot|Sntdt|fdS(Ns'Don't know how to convert lazy value %s(sls __class__s_delegate_unicodesunicodes _delegate_strsstrs ValueErrorsrepr(slsencoder((sHbuild/bdist.linux-x86_64/egg/pyamf/adapters/_django_utils_translation.pys convert_lazys   sfoo(s__doc__sdjango.utils.translations ugettext_lazyspyamfsNones convert_lazysadd_typestype(s ugettext_lazys convert_lazyspyamf((sHbuild/bdist.linux-x86_64/egg/pyamf/adapters/_django_utils_translation.pys? s   PK:u3;gfD)D))pyamf/adapters/_django_db_models_base.pyc; ܧJc@sdZdklZdklZdklZlZdkZdk Z dk l Z de fdYZ de ifd YZd Zd Zd Ze ieee id ee idedS(sk C{django.db.models} adapter module. @see: U{Django Project} @since: 0.4.1 (sModel(sfields(srelatedsfilesN(simportssDjangoReferenceCollectioncBs)tZdZdZdZdZRS(ss This helper class holds a dict of klass to pk/objects loaded from the underlying db. @since: 0.5 cCs-||ijoh||gi}t||iD]} || q~~| |#     cKstii||||}x;|iD]0}|i |}|i |||||i P>Ppyamf/remoting/__init__.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ AMF Remoting support. A Remoting request from the client consists of a short preamble, headers, and bodies. The preamble contains basic information about the nature of the request. Headers can be used to request debugging information, send authentication info, tag transactions, etc. Bodies contain actual Remoting requests and responses. A single Remoting envelope can contain several requests; Remoting supports batching out of the box. Client headers and bodies need not be responded to in a one-to-one manner. That is, a body or header may not require a response. Debug information is requested by a header but sent back as a body object. The response index is essential for the Adobe Flash Player to understand the response therefore. @see: U{Remoting Envelope on OSFlash (external) } @see: U{Remoting Headers on OSFlash (external) } @see: U{Remoting Debug Headers on OSFlash (external) } @since: 0.1.0 """ import pyamf from pyamf import util __all__ = ['Envelope', 'Request', 'Response', 'decode', 'encode'] #: Succesful call. STATUS_OK = 0 #: Reserved for runtime errors. STATUS_ERROR = 1 #: Debug information. STATUS_DEBUG = 2 #: List of available status response codes. STATUS_CODES = { STATUS_OK: '/onResult', STATUS_ERROR: '/onStatus', STATUS_DEBUG: '/onDebugEvents' } #: AMF mimetype. CONTENT_TYPE = 'application/x-amf' ERROR_CALL_FAILED, = range(1) ERROR_CODES = { ERROR_CALL_FAILED: 'Server.Call.Failed' } APPEND_TO_GATEWAY_URL = 'AppendToGatewayUrl' REPLACE_GATEWAY_URL = 'ReplaceGatewayUrl' REQUEST_PERSISTENT_HEADER = 'RequestPersistentHeader' class RemotingError(pyamf.BaseError): """ Generic remoting error class. """ class RemotingCallFailed(RemotingError): """ Raised if C{Server.Call.Failed} received. """ pyamf.add_error_class(RemotingCallFailed, ERROR_CODES[ERROR_CALL_FAILED]) class HeaderCollection(dict): """ Collection of AMF message headers. """ def __init__(self, raw_headers={}): self.required = [] for (k, ig, v) in raw_headers: self[k] = v if ig: self.required.append(k) def is_required(self, idx): """ @raise KeyError: Unknown header found. """ if not idx in self: raise KeyError("Unknown header %s" % str(idx)) return idx in self.required def set_required(self, idx, value=True): """ @raise KeyError: Unknown header found. """ if not idx in self: raise KeyError("Unknown header %s" % str(idx)) if not idx in self.required: self.required.append(idx) def __len__(self): return len(self.keys()) class Envelope(object): """ I wrap an entire request, encapsulating headers and bodies. There can be more than one request in a single transaction. @ivar amfVersion: AMF encoding version. See L{pyamf.ENCODING_TYPES} @type amfVersion: C{int} or C{None} @ivar clientType: Client type. See L{ClientTypes} @type clientType: C{int} or C{None} @ivar headers: AMF headers, a list of name, value pairs. Global to each request. @type headers: L{HeaderCollection} @ivar bodies: A list of requests/response messages @type bodies: L{list} containing tuples of the key of the request and the instance of the L{Message} """ def __init__(self, amfVersion=None, clientType=None): self.amfVersion = amfVersion self.clientType = clientType self.headers = HeaderCollection() self.bodies = [] def __repr__(self): r = "\n" % ( self.amfVersion, self.clientType) for h in self.headers: r += " " + repr(h) + "\n" for request in iter(self): r += " " + repr(request) + "\n" r += "" return r def __setitem__(self, name, value): if not isinstance(value, Message): raise TypeError("Message instance expected") idx = 0 found = False for body in self.bodies: if name == body[0]: self.bodies[idx] = (name, value) found = True idx = idx + 1 if not found: self.bodies.append((name, value)) value.envelope = self def __getitem__(self, name): for body in self.bodies: if name == body[0]: return body[1] raise KeyError("'%r'" % (name,)) def __iter__(self): for body in self.bodies: yield body[0], body[1] raise StopIteration def __len__(self): return len(self.bodies) def iteritems(self): for body in self.bodies: yield body raise StopIteration def keys(self): return [body[0] for body in self.bodies] def items(self): return self.bodies def __contains__(self, name): for body in self.bodies: if name == body[0]: return True return False def __eq__(self, other): if isinstance(other, Envelope): return (self.amfVersion == other.amfVersion and self.clientType == other.clientType and self.headers == other.headers and self.bodies == other.bodies) if hasattr(other, 'keys') and hasattr(other, 'items'): keys, o_keys = self.keys(), other.keys() if len(o_keys) != len(keys): return False for k in o_keys: if k not in keys: return False keys.remove(k) for k, v in other.items(): if self[k] != v: return False return True class Message(object): """ I represent a singular request/response, containing a collection of headers and one body of data. I am used to iterate over all requests in the L{Envelope}. @ivar envelope: The parent envelope of this AMF Message. @type envelope: L{Envelope} @ivar body: The body of the message. @type body: C{mixed} @ivar headers: The message headers. @type headers: C{dict} """ def __init__(self, envelope, body): self.envelope = envelope self.body = body def _get_headers(self): return self.envelope.headers headers = property(_get_headers) class Request(Message): """ An AMF Request payload. @ivar target: The target of the request @type target: C{basestring} """ def __init__(self, target, body=[], envelope=None): Message.__init__(self, envelope, body) self.target = target def __repr__(self): return "<%s target=%s>%s" % ( type(self).__name__, repr(self.target), repr(self.body), type(self).__name__) class Response(Message): """ An AMF Response. @ivar status: The status of the message. Default is L{STATUS_OK}. @type status: Member of L{STATUS_CODES}. """ def __init__(self, body, status=STATUS_OK, envelope=None): Message.__init__(self, envelope, body) self.status = status def __repr__(self): return "<%s status=%s>%s" % ( type(self).__name__, _get_status(self.status), repr(self.body), type(self).__name__ ) class BaseFault(object): """ I represent a C{Fault} message (C{mx.rpc.Fault}). @ivar level: The level of the fault. @type level: C{str} @ivar code: A simple code describing the fault. @type code: C{str} @ivar details: Any extra details of the fault. @type details: C{str} @ivar description: Text description of the fault. @type description: C{str} @see: U{mx.rpc.Fault on Livedocs (external) } """ level = None class __amf__: static = ('level', 'code', 'type', 'details', 'description') def __init__(self, *args, **kwargs): self.code = kwargs.get('code', '') self.type = kwargs.get('type', '') self.details = kwargs.get('details', '') self.description = kwargs.get('description', '') def __repr__(self): x = '%s level=%s' % (self.__class__.__name__, self.level) if self.code not in ('', None): x += ' code=%s' % repr(self.code) if self.type not in ('', None): x += ' type=%s' % repr(self.type) if self.description not in ('', None): x += ' description=%s' % repr(self.description) if self.details not in ('', None): x += '\nTraceback:\n%s' % (repr(self.details),) return x def raiseException(self): """ Raises an exception based on the fault object. There is no traceback available. """ raise get_exception_from_fault(self), self.description, None class ErrorFault(BaseFault): """ I represent an error level fault. """ level = 'error' def _read_header(stream, decoder, strict=False): """ Read AMF L{Message} header. @type stream: L{BufferedByteStream} @param stream: AMF data. @type decoder: L{amf0.Decoder} @param decoder: AMF decoder instance @type strict: C{bool} @param strict: Use strict decoding policy. Default is C{False}. @raise DecodeError: The data that was read from the stream does not match the header length. @rtype: C{tuple} @return: - Name of the header. - A C{bool} determining if understanding this header is required. - Value of the header. """ name_len = stream.read_ushort() name = stream.read_utf8_string(name_len) required = bool(stream.read_uchar()) data_len = stream.read_ulong() pos = stream.tell() data = decoder.readElement() if strict and pos + data_len != stream.tell(): raise pyamf.DecodeError( "Data read from stream does not match header length") return (name, required, data) def _write_header(name, header, required, stream, encoder, strict=False): """ Write AMF message header. @type name: C{str} @param name: Name of the header. @type header: @param header: Raw header data. @type required: L{bool} @param required: Required header. @type stream: L{BufferedByteStream} @param stream: AMF data. @type encoder: L{amf0.Encoder} or L{amf3.Encoder} @param encoder: AMF encoder instance. @type strict: C{bool} @param strict: Use strict encoding policy. Default is C{False}. """ stream.write_ushort(len(name)) stream.write_utf8_string(name) stream.write_uchar(required) write_pos = stream.tell() stream.write_ulong(0) old_pos = stream.tell() encoder.writeElement(header) new_pos = stream.tell() if strict: stream.seek(write_pos) stream.write_ulong(new_pos - old_pos) stream.seek(new_pos) def _read_body(stream, decoder, strict=False, logger=None): """ Read AMF message body. @param stream: AMF data. @type stream: L{BufferedByteStream} @param decoder: AMF decoder instance. @type decoder: L{amf0.Decoder} @param strict: Use strict decoding policy. Default is C{False}. @type strict: C{bool} @raise DecodeError: Data read from stream does not match body length. @param logger: Used to log interesting events whilst reading a remoting body. @type logger: A L{logging.Logger} instance or C{None}. @rtype: C{tuple} @return: A C{tuple} containing: - ID of the request - L{Request} or L{Response} """ def _read_args(): """ @raise pyamf.DecodeError: Array type required for request body. """ if stream.read(1) != '\x0a': raise pyamf.DecodeError("Array type required for request body") x = stream.read_ulong() return [decoder.readElement() for i in xrange(x)] target = stream.read_utf8_string(stream.read_ushort()) response = stream.read_utf8_string(stream.read_ushort()) status = STATUS_OK is_request = True for code, s in STATUS_CODES.iteritems(): if not target.endswith(s): continue is_request = False status = code target = target[:0 - len(s)] if logger: logger.debug('Remoting target: %r' % (target,)) data_len = stream.read_ulong() pos = stream.tell() if is_request: data = _read_args() else: data = decoder.readElement() if strict and pos + data_len != stream.tell(): raise pyamf.DecodeError("Data read from stream does not match body " "length (%d != %d)" % (pos + data_len, stream.tell(),)) if is_request: return response, Request(target, body=data) if status == STATUS_ERROR and isinstance(data, pyamf.ASObject): data = get_fault(data) return target, Response(data, status) def _write_body(name, message, stream, encoder, strict=False): """ Write AMF message body. @param name: The name of the request. @type name: C{basestring} @param message: The AMF payload. @type message: L{Request} or L{Response} @type stream: L{BufferedByteStream} @type encoder: L{amf0.Encoder} @param encoder: Encoder to use. @type strict: C{bool} @param strict: Use strict encoding policy. Default is C{False}. @raise TypeError: Unknown message type for C{message}. """ def _encode_body(message): if isinstance(message, Response): encoder.writeElement(message.body) return stream.write('\x0a') stream.write_ulong(len(message.body)) for x in message.body: encoder.writeElement(x) if not isinstance(message, (Request, Response)): raise TypeError("Unknown message type") target = None if isinstance(message, Request): target = unicode(message.target) else: target = u"%s%s" % (name, _get_status(message.status)) target = target.encode('utf8') stream.write_ushort(len(target)) stream.write_utf8_string(target) response = 'null' if isinstance(message, Request): response = name stream.write_ushort(len(response)) stream.write_utf8_string(response) if not strict: stream.write_ulong(0) _encode_body(message) return write_pos = stream.tell() stream.write_ulong(0) old_pos = stream.tell() _encode_body(message) new_pos = stream.tell() stream.seek(write_pos) stream.write_ulong(new_pos - old_pos) stream.seek(new_pos) def _get_status(status): """ Get status code. @type status: C{str} @raise ValueError: The status code is unknown. @return: Status code. @see: L{STATUS_CODES} """ if status not in STATUS_CODES.keys(): # TODO print that status code.. raise ValueError("Unknown status code") return STATUS_CODES[status] def get_fault_class(level, **kwargs): if level == 'error': return ErrorFault return BaseFault def get_fault(data): try: level = data['level'] del data['level'] except KeyError: level = 'error' e = {} for x, y in data.iteritems(): if isinstance(x, unicode): e[str(x)] = y else: e[x] = y return get_fault_class(level, **e)(**e) def decode(stream, context=None, strict=False, logger=None, timezone_offset=None): """ Decodes the incoming stream as a remoting message. @param stream: AMF data. @type stream: L{BufferedByteStream} @param context: Context. @type context: L{amf0.Context} or L{amf3.Context} @param strict: Enforce strict decoding. Default is C{False}. @type strict: C{bool} @param logger: Used to log interesting events whilst decoding a remoting message. @type logger: A L{logging.Logger} instance or C{None}. @param timezone_offset: The difference between the current timezone and UTC. Date/times should always be handled in UTC to avoid confusion but this is required for legacy systems. @type timezone_offset: L{datetime.timedelta} @raise DecodeError: Malformed stream. @raise RuntimeError: Decoder is unable to fully consume the stream buffer. @return: Message envelope. @rtype: L{Envelope} """ if not isinstance(stream, util.BufferedByteStream): stream = util.BufferedByteStream(stream) if logger is not None: logger.debug('remoting.decode start') msg = Envelope() msg.amfVersion = stream.read_uchar() # see http://osflash.org/documentation/amf/envelopes/remoting#preamble # why we are doing this... if msg.amfVersion > 0x09: raise pyamf.DecodeError("Malformed stream (amfVersion=%d)" % msg.amfVersion) if context is None: context = pyamf.get_context(pyamf.AMF0, exceptions=False) decoder = pyamf.get_decoder(pyamf.AMF0, stream, context=context, strict=strict, timezone_offset=timezone_offset) msg.clientType = stream.read_uchar() header_count = stream.read_ushort() for i in xrange(header_count): name, required, data = _read_header(stream, decoder, strict) msg.headers[name] = data if required: msg.headers.set_required(name) body_count = stream.read_short() for i in range(body_count): context.clear() target, payload = _read_body(stream, decoder, strict, logger) msg[target] = payload if strict and stream.remaining() > 0: raise RuntimeError("Unable to fully consume the buffer") if logger is not None: logger.debug('remoting.decode end') return msg def encode(msg, context=None, strict=False, logger=None, timezone_offset=None): """ Encodes AMF stream and returns file object. @type msg: L{Envelope} @param msg: The message to encode. @type strict: C{bool} @param strict: Determines whether encoding should be strict. Specifically header/body lengths will be written correctly, instead of the default 0. Default is C{False}. Introduced in 0.4. @param logger: Used to log interesting events whilst encoding a remoting message. @type logger: A L{logging.Logger} instance or C{None}. @param timezone_offset: The difference between the current timezone and UTC. Date/times should always be handled in UTC to avoid confusion but this is required for legacy systems. @type timezone_offset: L{datetime.timedelta} @rtype: C{StringIO} @return: File object. """ stream = util.BufferedByteStream() if context is None: context = pyamf.get_context(pyamf.AMF0, exceptions=False) encoder = pyamf.get_encoder(pyamf.AMF0, stream, context=context, timezone_offset=timezone_offset, strict=strict) if msg.clientType == pyamf.ClientTypes.Flash9: encoder.use_amf3 = True stream.write_uchar(msg.amfVersion) stream.write_uchar(msg.clientType) stream.write_short(len(msg.headers)) for name, header in msg.headers.iteritems(): _write_header( name, header, int(msg.headers.is_required(name)), stream, encoder, strict) stream.write_short(len(msg)) for name, message in msg.iteritems(): encoder.context.clear() _write_body(name, message, stream, encoder, strict) stream.seek(0) return stream def get_exception_from_fault(fault): """ @raise RemotingError: Default exception from fault. """ # XXX nick: threading problems here? try: return pyamf.ERROR_CLASS_MAP[fault.code] except KeyError: # default to RemotingError return RemotingError pyamf.register_class(ErrorFault) PKǠ;O~pyamf/remoting/amf0.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ AMF0 Remoting support. @since: 0.1.0 """ import traceback import sys from pyamf import remoting from pyamf.remoting import gateway class RequestProcessor(object): def __init__(self, gateway): self.gateway = gateway def authenticateRequest(self, request, service_request, *args, **kwargs): """ Authenticates the request against the service. @param request: The AMF request @type request: L{Request} """ username = password = None if 'Credentials' in request.headers: cred = request.headers['Credentials'] username = cred['userid'] password = cred['password'] return self.gateway.authenticateRequest(service_request, username, password, *args, **kwargs) def buildErrorResponse(self, request, error=None): """ Builds an error response. @param request: The AMF request @type request: L{Request} @return: The AMF response @rtype: L{Response} """ if error is not None: cls, e, tb = error else: cls, e, tb = sys.exc_info() return remoting.Response(build_fault(cls, e, tb, self.gateway.debug), status=remoting.STATUS_ERROR) def _getBody(self, request, response, service_request, **kwargs): if 'DescribeService' in request.headers: return service_request.service.description return self.gateway.callServiceRequest(service_request, *request.body, **kwargs) def __call__(self, request, *args, **kwargs): """ Processes an AMF0 request. @param request: The request to be processed. @type request: L{Request} @return: The response to the request. @rtype: L{Response} """ response = remoting.Response(None) try: service_request = self.gateway.getServiceRequest(request, request.target) except gateway.UnknownServiceError: return self.buildErrorResponse(request) # we have a valid service, now attempt authentication try: authd = self.authenticateRequest(request, service_request, *args, **kwargs) except (SystemExit, KeyboardInterrupt): raise except: return self.buildErrorResponse(request) if not authd: # authentication failed response.status = remoting.STATUS_ERROR response.body = remoting.ErrorFault(code='AuthenticationError', description='Authentication failed') return response # authentication succeeded, now fire the preprocessor (if there is one) try: self.gateway.preprocessRequest(service_request, *args, **kwargs) except (SystemExit, KeyboardInterrupt): raise except: return self.buildErrorResponse(request) try: response.body = self._getBody(request, response, service_request, *args, **kwargs) return response except (SystemExit, KeyboardInterrupt): raise except: return self.buildErrorResponse(request) def build_fault(cls, e, tb, include_traceback=False): """ Builds a L{ErrorFault} object based on the last exception raised. If include_traceback is C{False} then the traceback will not be added to the L{remoting.ErrorFault}. """ if hasattr(cls, '_amf_code'): code = cls._amf_code else: code = cls.__name__ details = None if include_traceback: details = str(traceback.format_exception(cls, e, tb)).replace("\\n", '') return remoting.ErrorFault(code=code, description=str(e), details=details) PK^;pyamf/remoting/amf3.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ AMF3 RemoteObject support. @see: U{RemoteObject on LiveDocs } @since: 0.1.0 """ import calendar import time import uuid import sys import pyamf from pyamf import remoting from pyamf.flex import messaging class BaseServerError(pyamf.BaseError): """ Base server error. """ class ServerCallFailed(BaseServerError): """ A catchall error. """ _amf_code = 'Server.Call.Failed' def generate_random_id(): return str(uuid.uuid4()) def generate_acknowledgement(request=None): ack = messaging.AcknowledgeMessage() ack.messageId = generate_random_id() ack.clientId = generate_random_id() ack.timestamp = calendar.timegm(time.gmtime()) if request: ack.correlationId = request.messageId return ack def generate_error(request, cls, e, tb, include_traceback=False): """ Builds an L{ErrorMessage} based on the last traceback and the request that was sent. """ import traceback if hasattr(cls, '_amf_code'): code = cls._amf_code else: code = cls.__name__ detail = '' rootCause = None if include_traceback: detail = [] rootCause = e for x in traceback.format_exception(cls, e, tb): detail.append(x.replace("\\n", '')) return messaging.ErrorMessage(messageId=generate_random_id(), clientId=generate_random_id(), timestamp=calendar.timegm(time.gmtime()), correlationId = request.messageId, faultCode=code, faultString=str(e), faultDetail=str(detail), extendedData=detail, rootCause=rootCause) class RequestProcessor(object): def __init__(self, gateway): self.gateway = gateway def buildErrorResponse(self, request, error=None): """ Builds an error response. @param request: The AMF request @type request: L{Request} @return: The AMF response @rtype: L{Response} """ if error is not None: cls, e, tb = error else: cls, e, tb = sys.exc_info() return generate_error(request, cls, e, tb, self.gateway.debug) def _getBody(self, amf_request, ro_request, **kwargs): """ @raise ServerCallFailed: Unknown request. """ if isinstance(ro_request, messaging.CommandMessage): return self._processCommandMessage(amf_request, ro_request, **kwargs) elif isinstance(ro_request, messaging.RemotingMessage): return self._processRemotingMessage(amf_request, ro_request, **kwargs) elif isinstance(ro_request, messaging.AsyncMessage): return self._processAsyncMessage(amf_request, ro_request, **kwargs) else: raise ServerCallFailed("Unknown request: %s" % ro_request) def _processCommandMessage(self, amf_request, ro_request, **kwargs): """ @raise ServerCallFailed: Unknown Command operation. @raise ServerCallFailed: Authorization is not supported in RemoteObject. """ ro_response = generate_acknowledgement(ro_request) if ro_request.operation == messaging.CommandMessage.PING_OPERATION: ro_response.body = True return remoting.Response(ro_response) elif ro_request.operation == messaging.CommandMessage.LOGIN_OPERATION: raise ServerCallFailed("Authorization is not supported in RemoteObject") elif ro_request.operation == messaging.CommandMessage.DISCONNECT_OPERATION: return remoting.Response(ro_response) else: raise ServerCallFailed("Unknown Command operation %s" % ro_request.operation) def _processAsyncMessage(self, amf_request, ro_request, **kwargs): ro_response = generate_acknowledgement(ro_request) ro_response.body = True return remoting.Response(ro_response) def _processRemotingMessage(self, amf_request, ro_request, **kwargs): ro_response = generate_acknowledgement(ro_request) service_name = ro_request.operation if hasattr(ro_request, 'destination') and ro_request.destination: service_name = '%s.%s' % (ro_request.destination, service_name) service_request = self.gateway.getServiceRequest(amf_request, service_name) # fire the preprocessor (if there is one) self.gateway.preprocessRequest(service_request, *ro_request.body, **kwargs) ro_response.body = self.gateway.callServiceRequest(service_request, *ro_request.body, **kwargs) return remoting.Response(ro_response) def __call__(self, amf_request, **kwargs): """ Processes an AMF3 Remote Object request. @param amf_request: The request to be processed. @type amf_request: L{Request} @return: The response to the request. @rtype: L{Response} """ ro_request = amf_request.body[0] try: return self._getBody(amf_request, ro_request, **kwargs) except (KeyboardInterrupt, SystemExit): raise except: return remoting.Response(self.buildErrorResponse(ro_request), status=remoting.STATUS_ERROR) PK:u3;' r rpyamf/remoting/__init__.pyc; DȠJc@s dZdkZdklZdddddgZdZd Zd Zhed <ed <ed } @see: U{Remoting Headers on OSFlash (external) } @see: U{Remoting Debug Headers on OSFlash (external) } @since: 0.1.0 N(sutilsEnvelopesRequestsResponsesdecodesencodeiiis /onResults /onStatuss/onDebugEventssapplication/x-amfsServer.Call.FailedsAppendToGatewayUrlsReplaceGatewayUrlsRequestPersistentHeaders RemotingErrorcBstZdZRS(s' Generic remoting error class. (s__name__s __module__s__doc__(((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pys RemotingError=s sRemotingCallFailedcBstZdZRS(s3 Raised if C{Server.Call.Failed} received. (s__name__s __module__s__doc__(((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pysRemotingCallFailedCs sHeaderCollectioncBs8tZdZhdZdZedZdZRS(s, Collection of AMF message headers. cCsLg|_x<|D]4\}}}|||<|o|ii|qqWdS(N(sselfsrequireds raw_headerssksigsvsappend(sselfs raw_headerssksigsv((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pys__init__Ps   cCs9||j otdt|n||ijSdS(s8 @raise KeyError: Unknown header found. sUnknown header %sN(sidxsselfsKeyErrorsstrsrequired(sselfsidx((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pys is_requiredXscCsQ||j otdt|n||ij o|ii|ndS(s8 @raise KeyError: Unknown header found. sUnknown header %sN(sidxsselfsKeyErrorsstrsrequiredsappend(sselfsidxsvalue((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pys set_requiredas cCst|iSdS(N(slensselfskeys(sself((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pys__len__ks(s__name__s __module__s__doc__s__init__s is_requiredsTrues set_requireds__len__(((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pysHeaderCollectionKs   cBswtZdZeedZdZdZdZdZdZ dZ dZ d Z d Z d ZRS( s I wrap an entire request, encapsulating headers and bodies. There can be more than one request in a single transaction. @ivar amfVersion: AMF encoding version. See L{pyamf.ENCODING_TYPES} @type amfVersion: C{int} or C{None} @ivar clientType: Client type. See L{ClientTypes} @type clientType: C{int} or C{None} @ivar headers: AMF headers, a list of name, value pairs. Global to each request. @type headers: L{HeaderCollection} @ivar bodies: A list of requests/response messages @type bodies: L{list} containing tuples of the key of the request and the instance of the L{Message} cCs+||_||_t|_g|_dS(N(s amfVersionsselfs clientTypesHeaderCollectionsheaderssbodies(sselfs amfVersions clientType((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pys__init__s   cCsd|i|if}x)|iD]}|dt|d7}q Wx,t|D]}|dt|d7}qOW|d7}|SdS(Ns' s s s ( sselfs amfVersions clientTypesrsheadersshsreprsitersrequest(sselfshsrequestsr((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pys__repr__s   cCst|t otdnd}t}xI|iD]>}||djo||f|i|%s(stypesselfs__name__sreprstargetsbody(sself((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pys__repr__ s(s__name__s __module__s__doc__sNones__init__s__repr__(((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pysRequests cBs&tZdZeedZdZRS(s An AMF Response. @ivar status: The status of the message. Default is L{STATUS_OK}. @type status: Member of L{STATUS_CODES}. cCs ti|||||_dS(N(sMessages__init__sselfsenvelopesbodysstatus(sselfsbodysstatussenvelope((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pys__init__scCs<dt|it|it|it|ifSdS(Ns<%s status=%s>%s(stypesselfs__name__s _get_statussstatussreprsbody(sself((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pys__repr__s(s__name__s __module__s__doc__s STATUS_OKsNones__init__s__repr__(((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pysResponses s BaseFaultcBsBtZdZeZdfdYZdZdZdZRS(s I represent a C{Fault} message (C{mx.rpc.Fault}). @ivar level: The level of the fault. @type level: C{str} @ivar code: A simple code describing the fault. @type code: C{str} @ivar details: Any extra details of the fault. @type details: C{str} @ivar description: Text description of the fault. @type description: C{str} @see: U{mx.rpc.Fault on Livedocs (external) } s__amf__cBstZdddddfZRS(Nslevelscodestypesdetailss description(s__name__s __module__sstatic(((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pys__amf__7scOsX|idd|_|idd|_|idd|_|idd|_dS(Nscodesstypesdetailss description(skwargssgetsselfscodestypesdetailss description(sselfsargsskwargs((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pys__init__:scCsd|ii|if}|idtfjo|dt|i7}n|idtfjo|dt|i7}n|i dtfjo|dt|i 7}n|i dtfjo|dt|i f7}n|SdS(Ns %s level=%sss code=%ss type=%ss description=%ss Traceback: %s( sselfs __class__s__name__slevelsxscodesNonesreprstypes descriptionsdetails(sselfsx((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pys__repr__@scCst||itdS(si Raises an exception based on the fault object. There is no traceback available. N(sget_exception_from_faultsselfs descriptionsNone(sself((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pysraiseExceptionOs( s__name__s __module__s__doc__sNoneslevels__amf__s__init__s__repr__sraiseException(((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pys BaseFault$s   s ErrorFaultcBstZdZdZRS(s+ I represent an error level fault. serror(s__name__s __module__s__doc__slevel(((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pys ErrorFaultWs c Cs|i}|i|}t|i}|i}|i }|i }|o|||i jotidn|||fSdS(sY Read AMF L{Message} header. @type stream: L{BufferedByteStream} @param stream: AMF data. @type decoder: L{amf0.Decoder} @param decoder: AMF decoder instance @type strict: C{bool} @param strict: Use strict decoding policy. Default is C{False}. @raise DecodeError: The data that was read from the stream does not match the header length. @rtype: C{tuple} @return: - Name of the header. - A C{bool} determining if understanding this header is required. - Value of the header. s2Data read from stream does not match header lengthN(sstreams read_ushortsname_lensread_utf8_stringsnamesbools read_ucharsrequireds read_ulongsdata_lenstellspossdecoders readElementsdatasstrictspyamfs DecodeError( sstreamsdecodersstrictsname_lensnamesdatasrequiredspossdata_len((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pys _read_header_s    c Cs|it||i||i||i}|i d|i}|i ||i}|o/|i||i |||i|ndS(s5 Write AMF message header. @type name: C{str} @param name: Name of the header. @type header: @param header: Raw header data. @type required: L{bool} @param required: Required header. @type stream: L{BufferedByteStream} @param stream: AMF data. @type encoder: L{amf0.Encoder} or L{amf3.Encoder} @param encoder: AMF encoder instance. @type strict: C{bool} @param strict: Use strict encoding policy. Default is C{False}. iN(sstreams write_ushortslensnameswrite_utf8_strings write_ucharsrequiredstells write_poss write_ulongsold_possencoders writeElementsheadersnew_possstrictsseek( snamesheadersrequiredsstreamsencodersstricts write_possnew_possold_pos((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pys _write_headers        csd}ii} ii}t} t}xRt i D]D\}} | i|  oqRnt}|} | dt|  } qRW|o|id| fni} i}|o |} n i} |o|| ijo'tid|| ifn|o|t| d| fSn| tjot| ti ot!| } n| t"| | fSdS(s Read AMF message body. @param stream: AMF data. @type stream: L{BufferedByteStream} @param decoder: AMF decoder instance. @type decoder: L{amf0.Decoder} @param strict: Use strict decoding policy. Default is C{False}. @type strict: C{bool} @raise DecodeError: Data read from stream does not match body length. @param logger: Used to log interesting events whilst reading a remoting body. @type logger: A L{logging.Logger} instance or C{None}. @rtype: C{tuple} @return: A C{tuple} containing: - ID of the request - L{Request} or L{Response} csjiddjotidni}gi}t|D]}|i qI~SdS(sQ @raise pyamf.DecodeError: Array type required for request body. is s$Array type required for request bodyN( sstreamsreadspyamfs DecodeErrors read_ulongsxsappends_[1]sxrangesisdecoders readElement(sis_[1]sx(sstreamsdecoder(s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pys _read_argss  isRemoting target: %rs;Data read from stream does not match body length (%d != %d)sbodyN(#s _read_argssstreamsread_utf8_strings read_ushortstargetsresponses STATUS_OKsstatussTrues is_requests STATUS_CODESs iteritemsscodesssendswithsFalseslensloggersdebugs read_ulongsdata_lenstellspossdatasdecoders readElementsstrictspyamfs DecodeErrorsRequests STATUS_ERRORs isinstancesASObjects get_faultsResponse(sstreamsdecodersstrictsloggerscodes is_requestspossresponses _read_argssstatussdatastargetsssdata_len((sstreamsdecoders7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pys _read_bodys6      ' c sxd}t|ttf otdnt} t|tot|i} nd|t |i f} | i d} it| i| d}t|to |}nit|i|| oid||dSni}idi} ||i}i|i|| i|dS(s Write AMF message body. @param name: The name of the request. @type name: C{basestring} @param message: The AMF payload. @type message: L{Request} or L{Response} @type stream: L{BufferedByteStream} @type encoder: L{amf0.Encoder} @param encoder: Encoder to use. @type strict: C{bool} @param strict: Use strict encoding policy. Default is C{False}. @raise TypeError: Unknown message type for C{message}. cspt|toi|idSnidit |ix|iD]}i|qUWdS(Ns ( s isinstancesmessagesResponsesencoders writeElementsbodysstreamswrites write_ulongslensx(smessagesx(sstreamsencoder(s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pys _encode_bodys  sUnknown message typeu%s%ssutf8snulliN(s _encode_bodys isinstancesmessagesRequestsResponses TypeErrorsNonestargetsunicodesnames _get_statussstatussencodesstreams write_ushortslenswrite_utf8_stringsresponsesstricts write_ulongstells write_possold_possnew_possseek( snamesmessagesstreamsencodersstricts write_poss _encode_bodysnew_possresponsesold_posstarget((sstreamsencoders7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pys _write_bodys8            cCs/|tijotdnt|SdS(s Get status code. @type status: C{str} @raise ValueError: The status code is unknown. @return: Status code. @see: L{STATUS_CODES} sUnknown status codeN(sstatuss STATUS_CODESskeyss ValueError(sstatus((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pys _get_status0scKs|djotSntSdS(Nserror(slevels ErrorFaults BaseFault(slevelskwargs((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pysget_fault_class@s cCsy|d}|d=Wntj o d}nXh}xH|iD]:\}}t|to||t |} @param context: Context. @type context: L{amf0.Context} or L{amf3.Context} @param strict: Enforce strict decoding. Default is C{False}. @type strict: C{bool} @param logger: Used to log interesting events whilst decoding a remoting message. @type logger: A L{logging.Logger} instance or C{None}. @param timezone_offset: The difference between the current timezone and UTC. Date/times should always be handled in UTC to avoid confusion but this is required for legacy systems. @type timezone_offset: L{datetime.timedelta} @raise DecodeError: Malformed stream. @raise RuntimeError: Decoder is unable to fully consume the stream buffer. @return: Message envelope. @rtype: L{Envelope} sremoting.decode starti s Malformed stream (amfVersion=%d)s exceptionsscontextsstrictstimezone_offsetis"Unable to fully consume the buffersremoting.decode endN()s isinstancesstreamsutilsBufferedByteStreamsloggersNonesdebugsEnvelopesmsgs read_uchars amfVersionspyamfs DecodeErrorscontexts get_contextsAMF0sFalses get_decodersstrictstimezone_offsetsdecoders clientTypes read_ushorts header_countsxrangesis _read_headersnamesrequiredsdatasheaderss set_requireds read_shorts body_countsrangesclears _read_bodystargetspayloads remainings RuntimeError(sstreamscontextsstrictsloggerstimezone_offsetspayloadsmsgs body_countsdecodersdatastargets header_countsnamesisrequired((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pysdecodeYs@          c Cshti}|tjotitidt}nti ti|d|d|d|} |itiijo t| _n|i|i|i|i|it|ixH|iiD]7\}}t||t|ii||| |qW|it|x=|iD]/\}}| iit |||| |q W|i!d|SdS(s( Encodes AMF stream and returns file object. @type msg: L{Envelope} @param msg: The message to encode. @type strict: C{bool} @param strict: Determines whether encoding should be strict. Specifically header/body lengths will be written correctly, instead of the default 0. Default is C{False}. Introduced in 0.4. @param logger: Used to log interesting events whilst encoding a remoting message. @type logger: A L{logging.Logger} instance or C{None}. @param timezone_offset: The difference between the current timezone and UTC. Date/times should always be handled in UTC to avoid confusion but this is required for legacy systems. @type timezone_offset: L{datetime.timedelta} @rtype: C{StringIO} @return: File object. s exceptionsscontextstimezone_offsetsstrictiN("sutilsBufferedByteStreamsstreamscontextsNonespyamfs get_contextsAMF0sFalses get_encoderstimezone_offsetsstrictsencodersmsgs clientTypes ClientTypessFlash9sTruesuse_amf3s write_uchars amfVersions write_shortslensheaderss iteritemssnamesheaders _write_headersints is_requiredsmessagesclears _write_bodysseek( smsgscontextsstrictsloggerstimezone_offsetsnamesstreamsheadersmessagesencoder((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pysencodes,       cCs0yti|iSWntj o tSnXdS(s= @raise RemotingError: Default exception from fault. N(spyamfsERROR_CLASS_MAPsfaultscodesKeyErrors RemotingError(sfault((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pysget_exception_from_faults ()s__doc__spyamfsutils__all__s STATUS_OKs STATUS_ERRORs STATUS_DEBUGs STATUS_CODESs CONTENT_TYPEsrangesERROR_CALL_FAILEDs ERROR_CODESsAPPEND_TO_GATEWAY_URLsREPLACE_GATEWAY_URLsREQUEST_PERSISTENT_HEADERs BaseErrors RemotingErrorsRemotingCallFailedsadd_error_classsdictsHeaderCollectionsobjectsEnvelopesMessagesRequestsResponses BaseFaults ErrorFaultsFalses _read_headers _write_headersNones _read_bodys _write_bodys _get_statussget_fault_classs get_faultsdecodesencodesget_exception_from_faultsregister_class( sget_exception_from_faultspyamfsRemotingCallFaileds _write_headers STATUS_CODESs RemotingErrorsREPLACE_GATEWAY_URLsdecodes _read_bodys__all__sEnvelopes _get_statussREQUEST_PERSISTENT_HEADERs get_faultsget_fault_classsencodes STATUS_OKs BaseFaultsERROR_CALL_FAILEDsAPPEND_TO_GATEWAY_URLsRequestsutils ERROR_CODESs STATUS_DEBUGs _read_headers ErrorFaultsResponses _write_bodys STATUS_ERRORs CONTENT_TYPEsMessagesHeaderCollection((s7build/bdist.linux-x86_64/egg/pyamf/remoting/__init__.pys?sD  !$v3 % #E D   J4 PK:u3;wpyamf/remoting/amf0.pyc; Jc@sXdZdkZdkZdklZdklZdefdYZe dZ dS(s' AMF0 Remoting support. @since: 0.1.0 N(sremoting(sgatewaysRequestProcessorcBs8tZdZdZedZdZdZRS(NcCs ||_dS(N(sgatewaysself(sselfsgateway((s3build/bdist.linux-x86_64/egg/pyamf/remoting/amf0.pys__init__scOs_t}}d|ijo%|id}|d}|d}n|ii|||||SdS(s Authenticates the request against the service. @param request: The AMF request @type request: L{Request} s CredentialssuseridspasswordN( sNonesusernamespasswordsrequestsheadersscredsselfsgatewaysauthenticateRequestsservice_requestsargsskwargs(sselfsrequestsservice_requestsargsskwargssusernamespasswordscred((s3build/bdist.linux-x86_64/egg/pyamf/remoting/amf0.pysauthenticateRequests   cCsd|tj o|\}}}nti\}}}tit ||||i i dti SdS(s Builds an error response. @param request: The AMF request @type request: L{Request} @return: The AMF response @rtype: L{Response} sstatusN(serrorsNonesclssestbssyssexc_infosremotingsResponses build_faultsselfsgatewaysdebugs STATUS_ERROR(sselfsrequestserrorsestbscls((s3build/bdist.linux-x86_64/egg/pyamf/remoting/amf0.pysbuildErrorResponse's  cKs;d|ijo|iiSn|ii||i|SdS(NsDescribeService( srequestsheaderssservice_requestsservices descriptionsselfsgatewayscallServiceRequestsbodyskwargs(sselfsrequestsresponsesservice_requestskwargs((s3build/bdist.linux-x86_64/egg/pyamf/remoting/amf0.pys_getBody8scOs~tit}y|ii||i}Wn#ti j o|i |SnXy|i ||||}Wn/ttfj o n|i |SnX| o/ti|_tidddd|_|Sny|ii|||Wn/ttfj o n|i |SnXy&|i||||||_|SWn/ttfj o n|i |SnXdS(s Processes an AMF0 request. @param request: The request to be processed. @type request: L{Request} @return: The response to the request. @rtype: L{Response} scodesAuthenticationErrors descriptionsAuthentication failedN(sremotingsResponsesNonesresponsesselfsgatewaysgetServiceRequestsrequeststargetsservice_requestsUnknownServiceErrorsbuildErrorResponsesauthenticateRequestsargsskwargssauthds SystemExitsKeyboardInterrupts STATUS_ERRORsstatuss ErrorFaultsbodyspreprocessRequests_getBody(sselfsrequestsargsskwargssservice_requestsresponsesauthd((s3build/bdist.linux-x86_64/egg/pyamf/remoting/amf0.pys__call__?s>    (s__name__s __module__s__init__sauthenticateRequestsNonesbuildErrorResponses_getBodys__call__(((s3build/bdist.linux-x86_64/egg/pyamf/remoting/amf0.pysRequestProcessors     cCst|do |i}n |i}t}|o+tt i |||i dd}ntid|dt|d|SdS(s Builds a L{ErrorFault} object based on the last exception raised. If include_traceback is C{False} then the traceback will not be added to the L{remoting.ErrorFault}. s _amf_codes\nsscodes descriptionsdetailsN(shasattrsclss _amf_codescodes__name__sNonesdetailssinclude_tracebacksstrs tracebacksformat_exceptionsestbsreplacesremotings ErrorFault(sclssestbsinclude_tracebackscodesdetails((s3build/bdist.linux-x86_64/egg/pyamf/remoting/amf0.pys build_faultus  +( s__doc__s tracebackssysspyamfsremotingspyamf.remotingsgatewaysobjectsRequestProcessorsFalses build_fault(sRequestProcessorsremotings build_faults tracebackssyssgateway((s3build/bdist.linux-x86_64/egg/pyamf/remoting/amf0.pys?s     dPK:u3;ypyamf/remoting/amf3.pyc; =ڋJc@sdZdkZdkZdkZdkZdkZdklZdklZdei fdYZ de fdYZ dZ e d Zed Zd efd YZdS( s AMF3 RemoteObject support. @see: U{RemoteObject on LiveDocs } @since: 0.1.0 N(sremoting(s messagingsBaseServerErrorcBstZdZRS(s Base server error. (s__name__s __module__s__doc__(((s3build/bdist.linux-x86_64/egg/pyamf/remoting/amf3.pysBaseServerErrors sServerCallFailedcBstZdZdZRS(s A catchall error. sServer.Call.Failed(s__name__s __module__s__doc__s _amf_code(((s3build/bdist.linux-x86_64/egg/pyamf/remoting/amf3.pysServerCallFaileds cCsttiSdS(N(sstrsuuidsuuid4(((s3build/bdist.linux-x86_64/egg/pyamf/remoting/amf3.pysgenerate_random_id$scCs[ti}t|_t|_titi |_ |o|i|_ n|SdS(N( s messagingsAcknowledgeMessagesacksgenerate_random_ids messageIdsclientIdscalendarstimegmstimesgmtimes timestampsrequests correlationId(srequestsack((s3build/bdist.linux-x86_64/egg/pyamf/remoting/amf3.pysgenerate_acknowledgement(s   c Csdk}t|do |i}n |i}d}t}|oIg}|}x:|i |||D]} |i| iddqdWntidtdtdtitid|id |d t|d t|d |d | SdS(s Builds an L{ErrorMessage} based on the last traceback and the request that was sent. Ns _amf_codess\ns messageIdsclientIds timestamps correlationIds faultCodes faultStrings faultDetails extendedDatas rootCause(s tracebackshasattrsclss _amf_codescodes__name__sdetailsNones rootCausesinclude_tracebacksesformat_exceptionstbsxsappendsreplaces messagings ErrorMessagesgenerate_random_idscalendarstimegmstimesgmtimesrequests messageIdsstr( srequestsclssestbsinclude_tracebackscodes rootCauses tracebacksdetailsx((s3build/bdist.linux-x86_64/egg/pyamf/remoting/amf3.pysgenerate_error5s"   !sRequestProcessorcBsJtZdZedZdZdZdZdZdZ RS(NcCs ||_dS(N(sgatewaysself(sselfsgateway((s3build/bdist.linux-x86_64/egg/pyamf/remoting/amf3.pys__init__RscCsU|tj o|\}}}nti\}}}t|||||i i SdS(s Builds an error response. @param request: The AMF request @type request: L{Request} @return: The AMF response @rtype: L{Response} N( serrorsNonesclssestbssyssexc_infosgenerate_errorsrequestsselfsgatewaysdebug(sselfsrequestserrorsestbscls((s3build/bdist.linux-x86_64/egg/pyamf/remoting/amf3.pysbuildErrorResponseUs  cKst|tio|i|||Snet|tio|i |||Sn;t|ti o|i |||Snt d|dS(s; @raise ServerCallFailed: Unknown request. sUnknown request: %sN( s isinstances ro_requests messagingsCommandMessagesselfs_processCommandMessages amf_requestskwargssRemotingMessages_processRemotingMessages AsyncMessages_processAsyncMessagesServerCallFailed(sselfs amf_requests ro_requestskwargs((s3build/bdist.linux-x86_64/egg/pyamf/remoting/amf3.pys_getBodyescKst|}|itiijot|_t i |Sna|itii jot dn;|itii jot i |Snt d|idS(s @raise ServerCallFailed: Unknown Command operation. @raise ServerCallFailed: Authorization is not supported in RemoteObject. s.Authorization is not supported in RemoteObjectsUnknown Command operation %sN(sgenerate_acknowledgements ro_requests ro_responses operations messagingsCommandMessagesPING_OPERATIONsTruesbodysremotingsResponsesLOGIN_OPERATIONsServerCallFailedsDISCONNECT_OPERATION(sselfs amf_requests ro_requestskwargss ro_response((s3build/bdist.linux-x86_64/egg/pyamf/remoting/amf3.pys_processCommandMessagers  cKs&t|}t|_ti|SdS(N(sgenerate_acknowledgements ro_requests ro_responsesTruesbodysremotingsResponse(sselfs amf_requests ro_requestskwargss ro_response((s3build/bdist.linux-x86_64/egg/pyamf/remoting/amf3.pys_processAsyncMessages  cKst|}|i}t|do|iod|i|f}n|ii ||}|ii ||i ||ii||i ||_ ti|SdS(Ns destinations%s.%s(sgenerate_acknowledgements ro_requests ro_responses operations service_nameshasattrs destinationsselfsgatewaysgetServiceRequests amf_requestsservice_requestspreprocessRequestsbodyskwargsscallServiceRequestsremotingsResponse(sselfs amf_requests ro_requestskwargssservice_requests ro_responses service_name((s3build/bdist.linux-x86_64/egg/pyamf/remoting/amf3.pys_processRemotingMessages    cKsl|id}y|i|||SWnAttfj o n'ti |i |dti SnXdS(s Processes an AMF3 Remote Object request. @param amf_request: The request to be processed. @type amf_request: L{Request} @return: The response to the request. @rtype: L{Response} isstatusN( s amf_requestsbodys ro_requestsselfs_getBodyskwargssKeyboardInterrupts SystemExitsremotingsResponsesbuildErrorResponses STATUS_ERROR(sselfs amf_requestskwargss ro_request((s3build/bdist.linux-x86_64/egg/pyamf/remoting/amf3.pys__call__s  ( s__name__s __module__s__init__sNonesbuildErrorResponses_getBodys_processCommandMessages_processAsyncMessages_processRemotingMessages__call__(((s3build/bdist.linux-x86_64/egg/pyamf/remoting/amf3.pysRequestProcessorQs     (s__doc__scalendarstimesuuidssysspyamfsremotings pyamf.flexs messagings BaseErrorsBaseServerErrorsServerCallFailedsgenerate_random_idsNonesgenerate_acknowledgementsFalsesgenerate_errorsobjectsRequestProcessor( sgenerate_acknowledgementsremotingsuuidsRequestProcessorspyamfssyssServerCallFailedsBaseServerErrorsgenerate_random_idstimes messagingscalendarsgenerate_error((s3build/bdist.linux-x86_64/egg/pyamf/remoting/amf3.pys? s         PKG$;ٜpyamf/remoting/gateway/wsgi.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ WSGI server implementation. The Python Web Server Gateway Interface (WSGI) is a simple and universal interface between web servers and web applications or frameworks. The WSGI interface has two sides: the "server" or "gateway" side, and the "application" or "framework" side. The server side invokes a callable object (usually a function or a method) that is provided by the application side. Additionally WSGI provides middlewares; a WSGI middleware implements both sides of the API, so that it can be inserted "between" a WSGI server and a WSGI application -- the middleware will act as an application from the server's point of view, and as a server from the application's point of view. @see: U{WSGI homepage (external)} @see: U{PEP-333 (external)} @since: 0.1.0 """ import pyamf from pyamf import remoting from pyamf.remoting import gateway __all__ = ['WSGIGateway'] class WSGIGateway(gateway.BaseGateway): """ WSGI Remoting Gateway. """ def getResponse(self, request, environ): """ Processes the AMF request, returning an AMF response. @param request: The AMF Request. @type request: L{Envelope} @rtype: L{Envelope} @return: The AMF Response. """ response = remoting.Envelope(request.amfVersion, request.clientType) for name, message in request: processor = self.getProcessor(message) environ['pyamf.request'] = message response[name] = processor(message, http_request=environ) return response def badRequestMethod(self, environ, start_response): """ Return HTTP 400 Bad Request. """ response = "400 Bad Request\n\nTo access this PyAMF gateway you " \ "must use POST requests (%s received)" % environ['REQUEST_METHOD'] start_response('400 Bad Request', [ ('Content-Type', 'text/plain'), ('Content-Length', str(len(response))), ('Server', gateway.SERVER_NAME), ]) return [response] def __call__(self, environ, start_response): """ @rtype: C{StringIO} @return: File-like object. """ if environ['REQUEST_METHOD'] != 'POST': return self.badRequestMethod(environ, start_response) body = environ['wsgi.input'].read(int(environ['CONTENT_LENGTH'])) stream = None timezone_offset = self._get_timezone_offset() # Decode the request try: request = remoting.decode(body, strict=self.strict, logger=self.logger, timezone_offset=timezone_offset) except (pyamf.DecodeError, IOError): if self.logger: self.logger.exception(gateway.format_exception()) response = "400 Bad Request\n\nThe request body was unable to " \ "be successfully decoded." if self.debug: response += "\n\nTraceback:\n\n%s" % gateway.format_exception() start_response('400 Bad Request', [ ('Content-Type', 'text/plain'), ('Content-Length', str(len(response))), ('Server', gateway.SERVER_NAME), ]) return [response] except (KeyboardInterrupt, SystemExit): raise except: if self.logger: self.logger.exception(gateway.format_exception()) response = "500 Internal Server Error\n\nAn unexpected error " \ "occurred whilst decoding." if self.debug: response += "\n\nTraceback:\n\n%s" % gateway.format_exception() start_response('500 Internal Server Error', [ ('Content-Type', 'text/plain'), ('Content-Length', str(len(response))), ('Server', gateway.SERVER_NAME), ]) return [response] if self.logger: self.logger.info("AMF Request: %r" % request) # Process the request try: response = self.getResponse(request, environ) except (KeyboardInterrupt, SystemExit): raise except: if self.logger: self.logger.exception(gateway.format_exception()) response = "500 Internal Server Error\n\nThe request was " \ "unable to be successfully processed." if self.debug: response += "\n\nTraceback:\n\n%s" % gateway.format_exception() start_response('500 Internal Server Error', [ ('Content-Type', 'text/plain'), ('Content-Length', str(len(response))), ('Server', gateway.SERVER_NAME), ]) return [response] if self.logger: self.logger.info("AMF Response: %r" % response) # Encode the response try: stream = remoting.encode(response, strict=self.strict, timezone_offset=timezone_offset) except: if self.logger: self.logger.exception(gateway.format_exception()) response = "500 Internal Server Error\n\nThe request was " \ "unable to be encoded." if self.debug: response += "\n\nTraceback:\n\n%s" % gateway.format_exception() start_response('500 Internal Server Error', [ ('Content-Type', 'text/plain'), ('Content-Length', str(len(response))), ('Server', gateway.SERVER_NAME), ]) return [response] response = stream.getvalue() start_response('200 OK', [ ('Content-Type', remoting.CONTENT_TYPE), ('Content-Length', str(len(response))), ('Server', gateway.SERVER_NAME), ]) return [response] PKG$; pyamf/remoting/gateway/google.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Gateway for Google App Engine. This gateway allows you to expose functions in Google App Engine web applications to AMF clients and servers. @see: U{Google App Engine homepage (external) } @since: 0.3.1 """ import sys import os.path try: sys.path.remove(os.path.dirname(os.path.abspath(__file__))) except ValueError: pass google = __import__('google.appengine.ext.webapp') webapp = google.appengine.ext.webapp from pyamf import remoting from pyamf.remoting import gateway __all__ = ['WebAppGateway'] class WebAppGateway(webapp.RequestHandler, gateway.BaseGateway): """ Google App Engine Remoting Gateway. """ __name__ = None def __init__(self, *args, **kwargs): gateway.BaseGateway.__init__(self, *args, **kwargs) def getResponse(self, request): """ Processes the AMF request, returning an AMF response. @param request: The AMF Request. @type request: L{Envelope} @rtype: L{Envelope} @return: The AMF Response. """ response = remoting.Envelope(request.amfVersion, request.clientType) for name, message in request: self.request.amf_request = message processor = self.getProcessor(message) response[name] = processor(message, http_request=self.request) return response def get(self): self.response.headers['Content-Type'] = 'text/plain' self.response.headers['Server'] = gateway.SERVER_NAME self.error(405) self.response.out.write("405 Method Not Allowed\n\n" "To access this PyAMF gateway you must use POST requests " "(%s received)" % self.request.method) def post(self): body = self.request.body_file.read() stream = None timezone_offset = self._get_timezone_offset() # Decode the request try: request = remoting.decode(body, strict=self.strict, logger=self.logger, timezone_offset=timezone_offset) except (KeyboardInterrupt, SystemExit): raise except: fe = gateway.format_exception() if self.logger: self.logger.exception(fe) response = ("400 Bad Request\n\nThe request body was unable to " "be successfully decoded.") if self.debug: response += "\n\nTraceback:\n\n%s" % fe self.error(400) self.response.headers['Content-Type'] = 'text/plain' self.response.headers['Server'] = gateway.SERVER_NAME self.response.out.write(response) return if self.logger: self.logger.info("AMF Request: %r" % request) # Process the request try: response = self.getResponse(request) except (KeyboardInterrupt, SystemExit): raise except: fe = gateway.format_exception() if self.logger: self.logger.exception(fe) response = "500 Internal Server Error\n\nThe request was " \ "unable to be successfully processed." if self.debug: response += "\n\nTraceback:\n\n%s" % fe self.error(500) self.response.headers['Content-Type'] = 'text/plain' self.response.headers['Server'] = gateway.SERVER_NAME self.response.out.write(response) return if self.logger: self.logger.info("AMF Response: %r" % response) # Encode the response try: stream = remoting.encode(response, strict=self.strict, logger=self.logger, timezone_offset=timezone_offset) except: fe = gateway.format_exception() if self.logger: self.logger.exception(fe) response = "500 Internal Server Error\n\nThe request was " \ "unable to be encoded." if self.debug: response += "\n\nTraceback:\n\n%s" % fe self.error(500) self.response.headers['Content-Type'] = 'text/plain' self.response.headers['Server'] = gateway.SERVER_NAME self.response.out.write(response) return response = stream.getvalue() self.response.headers['Content-Type'] = remoting.CONTENT_TYPE self.response.headers['Content-Length'] = str(len(response)) self.response.headers['Server'] = gateway.SERVER_NAME self.response.out.write(response) def __call__(self, *args, **kwargs): return self PKp3;} @ivar service: Facilitates the request. @type service: L{ServiceWrapper} @ivar method: The method to call on the service. A value of C{None} means that the service will be called directly. @type method: C{None} or C{str} """ def __init__(self, amf_request, service, method): self.request = amf_request self.service = service self.method = method def __call__(self, *args): return self.service(self.method, args) class ServiceCollection(dict): """ I hold a collection of services, mapping names to objects. """ def __contains__(self, value): if isinstance(value, basestring): return value in self.keys() return value in self.values() class BaseGateway(object): """ Generic Remoting gateway. @ivar services: A map of service names to callables. @type services: L{ServiceCollection} @ivar authenticator: A callable that will check the credentials of the request before allowing access to the service. Will return a C{bool} value. @type authenticator: C{Callable} or C{None} @ivar preprocessor: Called before the actual service method is invoked. Useful for setting up sessions etc. @type preprocessor: C{Callable} or C{None} @ivar logger: A logging instance. @ivar strict: Defines whether the gateway should use strict en/decoding. @type strict: C{bool} @ivar timezone_offset: A L{datetime.timedelta} between UTC and the timezone to be encoded. Most dates should be handled as UTC to avoid confusion but for older legacy systems this is not an option. Supplying an int as this will be interpretted in seconds. @ivar debug: Provides debugging information when an error occurs. Use only in non production settings. @type debug: C{bool} """ _request_class = ServiceRequest def __init__(self, services={}, **kwargs): if not hasattr(services, 'iteritems'): raise TypeError("dict type required for services") self.services = ServiceCollection() self.authenticator = kwargs.pop('authenticator', None) self.preprocessor = kwargs.pop('preprocessor', None) self.expose_request = kwargs.pop('expose_request', False) self.strict = kwargs.pop('strict', False) self.logger = kwargs.pop('logger', None) self.timezone_offset = kwargs.pop('timezone_offset', None) self.debug = kwargs.pop('debug', False) if kwargs: raise TypeError('Unknown kwargs: %r' % (kwargs,)) for name, service in services.iteritems(): self.addService(service, name) def addService(self, service, name=None, description=None, authenticator=None, expose_request=None, preprocessor=None): """ Adds a service to the gateway. @param service: The service to add to the gateway. @type service: C{callable}, class instance, or a module @param name: The name of the service. @type name: C{str} @raise pyamf.remoting.RemotingError: Service already exists. @raise TypeError: C{service} cannot be a scalar value. @raise TypeError: C{service} must be C{callable} or a module. """ if isinstance(service, (int, long, float, basestring)): raise TypeError("Service cannot be a scalar value") allowed_types = (types.ModuleType, types.FunctionType, types.DictType, types.MethodType, types.InstanceType, types.ObjectType) if not callable(service) and not isinstance(service, allowed_types): raise TypeError("Service must be a callable, module, or an object") if name is None: # TODO: include the module in the name if isinstance(service, (type, types.ClassType)): name = service.__name__ elif isinstance(service, types.FunctionType): name = service.func_name elif isinstance(service, types.ModuleType): name = service.__name__ else: name = str(service) if name in self.services: raise remoting.RemotingError("Service %s already exists" % name) self.services[name] = ServiceWrapper(service, description, authenticator, expose_request, preprocessor) def _get_timezone_offset(self): if self.timezone_offset is None: return None if isinstance(self.timezone_offset, datetime.timedelta): return self.timezone_offset return datetime.timedelta(seconds=self.timezone_offset) def removeService(self, service): """ Removes a service from the gateway. @param service: The service to remove from the gateway. @type service: C{callable} or a class instance @raise NameError: Service not found. """ if service not in self.services: raise NameError("Service %s not found" % str(service)) for name, wrapper in self.services.iteritems(): if isinstance(service, basestring) and service == name: del self.services[name] return elif isinstance(service, ServiceWrapper) and wrapper == service: del self.services[name] return elif isinstance(service, (type, types.ClassType, types.FunctionType)) and wrapper.service == service: del self.services[name] return # shouldn't ever get here raise RuntimeError("Something went wrong ...") def getServiceRequest(self, request, target): """ Returns a service based on the message. @raise UnknownServiceError: Unknown service. @param request: The AMF request. @type request: L{Request} @rtype: L{ServiceRequest} """ try: return self._request_class( request.envelope, self.services[target], None) except KeyError: pass try: sp = target.split('.') name, meth = '.'.join(sp[:-1]), sp[-1] return self._request_class( request.envelope, self.services[name], meth) except (ValueError, KeyError): pass raise UnknownServiceError("Unknown service %s" % target) def getProcessor(self, request): """ Returns request processor. @param request: The AMF message. @type request: L{Request} """ if request.target == 'null': from pyamf.remoting import amf3 return amf3.RequestProcessor(self) else: from pyamf.remoting import amf0 return amf0.RequestProcessor(self) def getResponse(self, amf_request): """ Returns the response to the request. Any implementing gateway must define this function. @param amf_request: The AMF request. @type amf_request: L{Envelope} @return: The AMF response. @rtype: L{Envelope} """ raise NotImplementedError def mustExposeRequest(self, service_request): """ Decides whether the underlying http request should be exposed as the first argument to the method call. This is granular, looking at the service method first, then at the service level and finally checking the gateway. @rtype: C{bool} """ expose_request = service_request.service.mustExposeRequest(service_request) if expose_request is None: if self.expose_request is None: return False return self.expose_request return expose_request def getAuthenticator(self, service_request): """ Gets an authenticator callable based on the service_request. This is granular, looking at the service method first, then at the service level and finally to see if there is a global authenticator function for the gateway. Returns C{None} if one could not be found. """ auth = service_request.service.getAuthenticator(service_request) if auth is None: return self.authenticator return auth def authenticateRequest(self, service_request, username, password, **kwargs): """ Processes an authentication request. If no authenticator is supplied, then authentication succeeds. @return: Returns a C{bool} based on the result of authorization. A value of C{False} will stop processing the request and return an error to the client. @rtype: C{bool} """ authenticator = self.getAuthenticator(service_request) if authenticator is None: return True args = (username, password) if hasattr(authenticator, '_pyamf_expose_request'): http_request = kwargs.get('http_request', None) args = (http_request,) + args return authenticator(*args) == True def getPreprocessor(self, service_request): """ Gets a preprocessor callable based on the service_request. This is granular, looking at the service method first, then at the service level and finally to see if there is a global preprocessor function for the gateway. Returns C{None} if one could not be found. """ preproc = service_request.service.getPreprocessor(service_request) if preproc is None: return self.preprocessor return preproc def preprocessRequest(self, service_request, *args, **kwargs): """ Preprocesses a request. """ processor = self.getPreprocessor(service_request) if processor is None: return args = (service_request,) + args if hasattr(processor, '_pyamf_expose_request'): http_request = kwargs.get('http_request', None) args = (http_request,) + args return processor(*args) def callServiceRequest(self, service_request, *args, **kwargs): """ Executes the service_request call """ if self.mustExposeRequest(service_request): http_request = kwargs.get('http_request', None) args = (http_request,) + args return service_request(*args) def authenticate(func, c, expose_request=False): """ A decorator that facilitates authentication per method. Setting C{expose_request} to C{True} will set the underlying request object (if there is one), usually HTTP and set it to the first argument of the authenticating callable. If there is no request object, the default is C{None}. @raise TypeError: C{func} and authenticator must be callable. """ if not callable(func): raise TypeError('func must be callable') if not callable(c): raise TypeError('Authenticator must be callable') attr = func if isinstance(func, types.UnboundMethodType): attr = func.im_func if expose_request is True: c = globals()['expose_request'](c) setattr(attr, '_pyamf_authenticator', c) return func def expose_request(func): """ A decorator that adds an expose_request flag to the underlying callable. @raise TypeError: C{func} must be callable. """ if not callable(func): raise TypeError("func must be callable") if isinstance(func, types.UnboundMethodType): setattr(func.im_func, '_pyamf_expose_request', True) else: setattr(func, '_pyamf_expose_request', True) return func def preprocess(func, c, expose_request=False): """ A decorator that facilitates preprocessing per method. Setting C{expose_request} to C{True} will set the underlying request object (if there is one), usually HTTP and set it to the first argument of the preprocessing callable. If there is no request object, the default is C{None}. @raise TypeError: C{func} and preprocessor must be callable. """ if not callable(func): raise TypeError('func must be callable') if not callable(c): raise TypeError('Preprocessor must be callable') attr = func if isinstance(func, types.UnboundMethodType): attr = func.im_func if expose_request is True: c = globals()['expose_request'](c) setattr(attr, '_pyamf_preprocessor', c) return func def format_exception(): import traceback f = util.StringIO() traceback.print_exc(file=f) return f.getvalue() PKG$;n%K\\ pyamf/remoting/gateway/django.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Gateway for the Django framework. This gateway allows you to expose functions in Django to AMF clients and servers. @see: U{Django homepage (external)} @since: 0.1.0 """ django = __import__('django.http') http = django.http conf = __import__('django.conf') conf = conf.conf import pyamf from pyamf import remoting from pyamf.remoting import gateway __all__ = ['DjangoGateway'] class DjangoGateway(gateway.BaseGateway): """ An instance of this class is suitable as a Django view. An example usage would be through C{urlconf}:: from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^gateway/', 'yourproject.yourapp.gateway.gw_instance'), ) where C{yourproject.yourapp.gateway.gw_instance} refers to an instance of this class. @ivar expose_request: The standard Django view always has the request object as the first parameter. To disable this functionality, set this to C{False}. @type expose_request: C{bool} """ def __init__(self, *args, **kwargs): kwargs['expose_request'] = kwargs.get('expose_request', True) try: tz = conf.settings.AMF_TIME_OFFSET except AttributeError: tz = None try: debug = conf.settings.DEBUG except AttributeError: debug = False kwargs['timezone_offset'] = kwargs.get('timezone_offset', tz) kwargs['debug'] = kwargs.get('debug', debug) gateway.BaseGateway.__init__(self, *args, **kwargs) def getResponse(self, http_request, request): """ Processes the AMF request, returning an AMF response. @param http_request: The underlying HTTP Request. @type http_request: C{HTTPRequest} @param request: The AMF Request. @type request: L{Envelope} @rtype: L{Envelope} @return: The AMF Response. """ response = remoting.Envelope(request.amfVersion, request.clientType) for name, message in request: http_request.amf_request = message processor = self.getProcessor(message) response[name] = processor(message, http_request=http_request) return response def __call__(self, http_request): """ Processes and dispatches the request. @param http_request: The C{HTTPRequest} object. @type http_request: C{HTTPRequest} @return: The response to the request. @rtype: C{HTTPResponse} """ if http_request.method != 'POST': return http.HttpResponseNotAllowed(['POST']) stream = None timezone_offset = self._get_timezone_offset() # Decode the request try: request = remoting.decode(http_request.raw_post_data, strict=self.strict, logger=self.logger, timezone_offset=timezone_offset) except (pyamf.DecodeError, IOError): fe = gateway.format_exception() if self.logger: self.logger.exception(fe) response = "400 Bad Request\n\nThe request body was unable to " \ "be successfully decoded." if self.debug: response += "\n\nTraceback:\n\n%s" % fe return http.HttpResponseBadRequest(mimetype='text/plain', content=response) except (KeyboardInterrupt, SystemExit): raise except: fe = gateway.format_exception() if self.logger: self.logger.exception(fe) response = ('500 Internal Server Error\n\n' 'An unexpected error occurred.') if self.debug: response += "\n\nTraceback:\n\n%s" % fe return http.HttpResponseServerError(mimetype='text/plain', content=response) if self.logger: self.logger.info("AMF Request: %r" % request) # Process the request try: response = self.getResponse(http_request, request) except (KeyboardInterrupt, SystemExit): raise except: fe = gateway.format_exception() if self.logger: self.logger.exception(fe) response = "500 Internal Server Error\n\nThe request was " \ "unable to be successfully processed." if self.debug: response += "\n\nTraceback:\n\n%s" % fe return http.HttpResponseServerError(mimetype='text/plain', content=response) if self.logger: self.logger.info("AMF Response: %r" % response) # Encode the response try: stream = remoting.encode(response, strict=self.strict, logger=self.logger, timezone_offset=timezone_offset) except: fe = gateway.format_exception() if self.logger: self.logger.exception(fe) response = ("500 Internal Server Error\n\nThe request was " "unable to be encoded.") if self.debug: response += "\n\nTraceback:\n\n%s" % fe return http.HttpResponseServerError(mimetype='text/plain', content=response) buf = stream.getvalue() http_response = http.HttpResponse(mimetype=remoting.CONTENT_TYPE) http_response['Server'] = gateway.SERVER_NAME http_response['Content-Length'] = str(len(buf)) http_response.write(buf) return http_response PK,;&44!pyamf/remoting/gateway/twisted.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Twisted server implementation. This gateway allows you to expose functions in Twisted to AMF clients and servers. @see: U{Twisted homepage (external)} @since: 0.1.0 """ import sys import os.path try: sys.path.remove('') except ValueError: pass try: sys.path.remove(os.path.dirname(os.path.abspath(__file__))) except ValueError: pass twisted = __import__('twisted') __import__('twisted.internet.defer') __import__('twisted.internet.threads') __import__('twisted.web.resource') __import__('twisted.web.server') defer = twisted.internet.defer threads = twisted.internet.threads resource = twisted.web.resource server = twisted.web.server from pyamf import remoting from pyamf.remoting import gateway, amf0, amf3 __all__ = ['TwistedGateway'] class AMF0RequestProcessor(amf0.RequestProcessor): """ A Twisted friendly implementation of L{amf0.RequestProcessor} """ def __call__(self, request, *args, **kwargs): """ Calls the underlying service method. @return: A C{Deferred} that will contain the AMF L{Response}. @rtype: C{twisted.internet.defer.Deferred} """ try: service_request = self.gateway.getServiceRequest( request, request.target) except gateway.UnknownServiceError: return defer.succeed(self.buildErrorResponse(request)) response = remoting.Response(None) deferred_response = defer.Deferred() def eb(failure): errMesg = "%s: %s" % (failure.type, failure.getErrorMessage()) if self.gateway.logger: self.gateway.logger.error(errMesg) self.gateway.logger.info(failure.getTraceback()) deferred_response.callback(self.buildErrorResponse( request, (failure.type, failure.value, failure.tb))) def response_cb(result): if self.gateway.logger: self.gateway.logger.debug("AMF Response: %s" % (result,)) response.body = result deferred_response.callback(response) def preprocess_cb(result): d = defer.maybeDeferred(self._getBody, request, response, service_request, **kwargs) d.addCallback(response_cb).addErrback(eb) def auth_cb(result): if result is not True: response.status = remoting.STATUS_ERROR response.body = remoting.ErrorFault(code='AuthenticationError', description='Authentication failed') deferred_response.callback(response) return d = defer.maybeDeferred(self.gateway.preprocessRequest, service_request, *args, **kwargs) d.addCallback(preprocess_cb).addErrback(eb) # we have a valid service, now attempt authentication d = defer.maybeDeferred(self.authenticateRequest, request, service_request, **kwargs) d.addCallback(auth_cb).addErrback(eb) return deferred_response class AMF3RequestProcessor(amf3.RequestProcessor): """ A Twisted friendly implementation of L{amf3.RequestProcessor} """ def _processRemotingMessage(self, amf_request, ro_request, **kwargs): ro_response = amf3.generate_acknowledgement(ro_request) amf_response = remoting.Response(ro_response, status=remoting.STATUS_OK) try: service_name = ro_request.operation if hasattr(ro_request, 'destination') and ro_request.destination: service_name = '%s.%s' % (ro_request.destination, service_name) service_request = self.gateway.getServiceRequest(amf_request, service_name) except gateway.UnknownServiceError: return defer.succeed(remoting.Response( self.buildErrorResponse(ro_request), status=remoting.STATUS_ERROR)) deferred_response = defer.Deferred() def eb(failure): errMesg = "%s: %s" % (failure.type, failure.getErrorMessage()) if self.gateway.logger: self.gateway.logger.error(errMesg) self.gateway.logger.info(failure.getTraceback()) ro_response = self.buildErrorResponse(ro_request, (failure.type, failure.value, failure.tb)) deferred_response.callback(remoting.Response(ro_response, status=remoting.STATUS_ERROR)) def response_cb(result): ro_response.body = result res = remoting.Response(ro_response) if self.gateway.logger: self.gateway.logger.debug("AMF Response: %r" % (res,)) deferred_response.callback(res) def process_cb(result): d = defer.maybeDeferred(self.gateway.callServiceRequest, service_request, *ro_request.body, **kwargs) d.addCallback(response_cb).addErrback(eb) d = defer.maybeDeferred(self.gateway.preprocessRequest, service_request, *ro_request.body, **kwargs) d.addCallback(process_cb).addErrback(eb) return deferred_response def __call__(self, amf_request, **kwargs): """ Calls the underlying service method. @return: A C{deferred} that will contain the AMF L{Response}. @rtype: C{Deferred} """ deferred_response = defer.Deferred() ro_request = amf_request.body[0] def cb(amf_response): deferred_response.callback(amf_response) def eb(failure): errMesg = "%s: %s" % (failure.type, failure.getErrorMessage()) if self.gateway.logger: self.gateway.logger.error(errMesg) self.gateway.logger.info(failure.getTraceback()) deferred_response.callback(self.buildErrorResponse(ro_request, (failure.type, failure.value, failure.tb))) d = defer.maybeDeferred(self._getBody, amf_request, ro_request, **kwargs) d.addCallback(cb).addErrback(eb) return deferred_response class TwistedGateway(gateway.BaseGateway, resource.Resource): """ Twisted Remoting gateway for C{twisted.web}. @ivar expose_request: Forces the underlying HTTP request to be the first argument to any service call. @type expose_request: C{bool} """ allowedMethods = ('POST',) def __init__(self, *args, **kwargs): if 'expose_request' not in kwargs: kwargs['expose_request'] = True gateway.BaseGateway.__init__(self, *args, **kwargs) resource.Resource.__init__(self) def _finaliseRequest(self, request, status, content, mimetype='text/plain'): """ Finalises the request. @param request: The HTTP Request. @type request: C{http.Request} @param status: The HTTP status code. @type status: C{int} @param content: The content of the response. @type content: C{str} @param mimetype: The MIME type of the request. @type mimetype: C{str} """ request.setResponseCode(status) request.setHeader("Content-Type", mimetype) request.setHeader("Content-Length", str(len(content))) request.setHeader("Server", gateway.SERVER_NAME) request.write(content) request.finish() def render_POST(self, request): """ Read remoting request from the client. @type request: The HTTP Request. @param request: C{twisted.web.http.Request} """ def handleDecodeError(failure): """ Return HTTP 400 Bad Request. """ errMesg = "%s: %s" % (failure.type, failure.getErrorMessage()) if self.logger: self.logger.error(errMesg) self.logger.info(failure.getTraceback()) body = "400 Bad Request\n\nThe request body was unable to " \ "be successfully decoded." if self.debug: body += "\n\nTraceback:\n\n%s" % failure.getTraceback() self._finaliseRequest(request, 400, body) request.content.seek(0, 0) timezone_offset = self._get_timezone_offset() d = threads.deferToThread(remoting.decode, request.content.read(), strict=self.strict, logger=self.logger, timezone_offset=timezone_offset) def cb(amf_request): if self.logger: self.logger.debug("AMF Request: %r" % amf_request) x = self.getResponse(request, amf_request) x.addCallback(self.sendResponse, request) # Process the request d.addCallback(cb).addErrback(handleDecodeError) return server.NOT_DONE_YET def sendResponse(self, amf_response, request): def cb(result): self._finaliseRequest(request, 200, result.getvalue(), remoting.CONTENT_TYPE) def eb(failure): """ Return 500 Internal Server Error. """ errMesg = "%s: %s" % (failure.type, failure.getErrorMessage()) if self.logger: self.logger.error(errMesg) self.logger.info(failure.getTraceback()) body = "500 Internal Server Error\n\nThere was an error encoding " \ "the response." if self.debug: body += "\n\nTraceback:\n\n%s" % failure.getTraceback() self._finaliseRequest(request, 500, body) timezone_offset = self._get_timezone_offset() d = threads.deferToThread(remoting.encode, amf_response, strict=self.strict, logger=self.logger, timezone_offset=timezone_offset) d.addCallback(cb).addErrback(eb) def getProcessor(self, request): """ Determines the request processor, based on the request. @param request: The AMF message. @type request: L{Request} """ if request.target == 'null': return AMF3RequestProcessor(self) return AMF0RequestProcessor(self) def getResponse(self, http_request, amf_request): """ Processes the AMF request, returning an AMF L{Response}. @param http_request: The underlying HTTP Request @type http_request: C{twisted.web.http.Request} @param amf_request: The AMF Request. @type amf_request: L{Envelope} """ response = remoting.Envelope(amf_request.amfVersion, amf_request.clientType) dl = [] def cb(body, name): response[name] = body for name, message in amf_request: processor = self.getProcessor(message) http_request.amf_request = message d = defer.maybeDeferred( processor, message, http_request=http_request) dl.append(d.addCallback(cb, name)) def cb2(result): return response def eb(failure): """ Return 500 Internal Server Error. """ errMesg = "%s: %s" % (failure.type, failure.getErrorMessage()) if self.logger: self.logger.error(errMesg) self.logger.info(failure.getTraceback()) body = "500 Internal Server Error\n\nThe request was unable to " \ "be successfully processed." if self.debug: body += "\n\nTraceback:\n\n%s" % failure.getTraceback() self._finaliseRequest(http_request, 500, body) d = defer.DeferredList(dl) return d.addCallback(cb2).addErrback(eb) def authenticateRequest(self, service_request, username, password, **kwargs): """ Processes an authentication request. If no authenticator is supplied, then authentication succeeds. @return: C{Deferred}. @rtype: C{twisted.internet.defer.Deferred} """ authenticator = self.getAuthenticator(service_request) if self.logger: self.logger.debug('Authenticator expands to: %r' % authenticator) if authenticator is None: return defer.succeed(True) args = (username, password) if hasattr(authenticator, '_pyamf_expose_request'): http_request = kwargs.get('http_request', None) args = (http_request,) + args return defer.maybeDeferred(authenticator, *args) def preprocessRequest(self, service_request, *args, **kwargs): """ Preprocesses a request. """ processor = self.getPreprocessor(service_request) if self.logger: self.logger.debug('Preprocessor expands to: %r' % processor) if processor is None: return args = (service_request,) + args if hasattr(processor, '_pyamf_expose_request'): http_request = kwargs.get('http_request', None) args = (http_request,) + args return defer.maybeDeferred(processor, *args) PK:u3;}ccpyamf/remoting/gateway/wsgi.pyc; DȠJc@sOdZdkZdklZdklZdgZdeifdYZdS(s? WSGI server implementation. The Python Web Server Gateway Interface (WSGI) is a simple and universal interface between web servers and web applications or frameworks. The WSGI interface has two sides: the "server" or "gateway" side, and the "application" or "framework" side. The server side invokes a callable object (usually a function or a method) that is provided by the application side. Additionally WSGI provides middlewares; a WSGI middleware implements both sides of the API, so that it can be inserted "between" a WSGI server and a WSGI application -- the middleware will act as an application from the server's point of view, and as a server from the application's point of view. @see: U{WSGI homepage (external)} @see: U{PEP-333 (external)} @since: 0.1.0 N(sremoting(sgateways WSGIGatewaycBs)tZdZdZdZdZRS(s WSGI Remoting Gateway. cCsfti|i|i}xC|D];\}}|i |}||d<||d|||} @rtype: L{Envelope} @return: The AMF Response. s pyamf.requests http_requestN( sremotingsEnvelopesrequests amfVersions clientTypesresponsesnamesmessagesselfs getProcessors processorsenviron(sselfsrequestsenvironsnames processorsmessagesresponse((s;build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/wsgi.pys getResponse%s  cCsPd|d}|dddfdtt|fdtifg|gSdS( s. Return HTTP 400 Bad Request. sV400 Bad Request To access this PyAMF gateway you must use POST requests (%s received)sREQUEST_METHODs400 Bad Requests Content-Types text/plainsContent-LengthsServerN(senvironsresponsesstart_responsesstrslensgateways SERVER_NAME(sselfsenvironsstart_responsesresponse((s;build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/wsgi.pysbadRequestMethod7s7cCs|ddjo|i||Sn|dit|d}t}|i }y+t i |d|i d|id|}WnQtitfj o|io|iitind}|io|d ti7}n|d d d fd tt|fdtifg|gSnttfj o n|io|iitind}|io|d ti7}n|dd d fd tt|fdtifg|gSnX|io|iid|ny|i||}Wnttfj o n|io|iitind}|io|d ti7}n|dd d fd tt|fdtifg|gSnX|io|iid|ny"t i|d|i d|}Wn|io|iitind}|io|d ti7}n|dd d fd tt|fdtifg|gSnX|i }|dd t i!fd tt|fdtifg|gSdS(sH @rtype: C{StringIO} @return: File-like object. sREQUEST_METHODsPOSTs wsgi.inputsCONTENT_LENGTHsstrictsloggerstimezone_offsetsH400 Bad Request The request body was unable to be successfully decoded.s Traceback: %ss400 Bad Requests Content-Types text/plainsContent-LengthsServersH500 Internal Server Error An unexpected error occurred whilst decoding.s500 Internal Server ErrorsAMF Request: %rsO500 Internal Server Error The request was unable to be successfully processed.sAMF Response: %rs@500 Internal Server Error The request was unable to be encoded.s200 OKN("senvironsselfsbadRequestMethodsstart_responsesreadsintsbodysNonesstreams_get_timezone_offsetstimezone_offsetsremotingsdecodesstrictsloggersrequestspyamfs DecodeErrorsIOErrors exceptionsgatewaysformat_exceptionsresponsesdebugsstrslens SERVER_NAMEsKeyboardInterrupts SystemExitsinfos getResponsesencodesgetvalues CONTENT_TYPE(sselfsenvironsstart_responsesbodysstreamsrequestsresponsestimezone_offset((s;build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/wsgi.pys__call__Fsr   7   7    7    7  :(s__name__s __module__s__doc__s getResponsesbadRequestMethods__call__(((s;build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/wsgi.pys WSGIGateway s   (s__doc__spyamfsremotingspyamf.remotingsgateways__all__s BaseGateways WSGIGateway(spyamfsremotingsgateways__all__s WSGIGateway((s;build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/wsgi.pys?s     PK:u3;`$!pyamf/remoting/gateway/google.pyc; DȠJc@sdZdkZdkZy,eiieiieiieWne j onXe dZ e i i iZdklZdklZdgZdeieifdYZdS(s Gateway for Google App Engine. This gateway allows you to expose functions in Google App Engine web applications to AMF clients and servers. @see: U{Google App Engine homepage (external) } @since: 0.3.1 Nsgoogle.appengine.ext.webapp(sremoting(sgateways WebAppGatewaycBsAtZdZeZdZdZdZdZdZRS(s- Google App Engine Remoting Gateway. cOstii|||dS(N(sgateways BaseGateways__init__sselfsargsskwargs(sselfsargsskwargs((s=build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/google.pys__init__(scCskti|i|i}xH|D]@\}}||i_ |i |}||d|i||} @rtype: L{Envelope} @return: The AMF Response. s http_requestN( sremotingsEnvelopesrequests amfVersions clientTypesresponsesnamesmessagesselfs amf_requests getProcessors processor(sselfsrequestsnames processorsmessagesresponse((s=build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/google.pys getResponse+s  cCsQd|iids cCsC|iii}t}|i}y+t i |d|i d|i d|}Wnt tfj o nti}|i o|i i|nd}|io|d|7}n|idd|iidsiisBaseServiceErrorcBstZdZRS(s Base service error. (s__name__s __module__s__doc__(((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pysBaseServiceErrors sUnknownServiceErrorcBstZdZdZRS(s7 Client made a request for an unknown service. sService.ResourceNotFound(s__name__s __module__s__doc__s _amf_code(((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pysUnknownServiceError#s sUnknownServiceMethodErrorcBstZdZdZRS(s6 Client made a request for an unknown method. sService.MethodNotFound(s__name__s __module__s__doc__s _amf_code(((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pysUnknownServiceMethodError*s sInvalidServiceMethodErrorcBstZdZdZRS(s: Client made a request for an invalid methodname. sService.MethodInvalid(s__name__s __module__s__doc__s _amf_code(((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pysInvalidServiceMethodError1s sServiceWrappercBsktZdZeeeedZdZdZdZdZedZ edZ edZ RS( s Wraps a supplied service with extra functionality. @ivar service: The original service. @type service: C{callable} @ivar description: A description of the service. @type description: C{str} cCs1||_||_||_||_||_dS(N(sservicesselfs descriptions authenticatorsexpose_requests preprocessor(sselfsservices descriptions authenticatorsexpose_requests preprocessor((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pys__init__As     cCs;t|tot|i|iSnt|i|SdS(N(s isinstancesothersServiceWrapperscmpsselfs__dict__sservice(sselfsother((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pys__cmp__IscCst}t|ittifo|i}n |i}|tj ot|}|i dot dnyt ||}Wn)t j otdt|nXt| ot dt|n|Snt| otdt|in|SdS(s @raise InvalidServiceMethodError: Calls to private methods are not allowed. @raise UnknownServiceMethodError: Unknown method. @raise InvalidServiceMethodError: Service method must be callable. s_s(Calls to private methods are not allowedsUnknown method %ss"Service method %s must be callableN(sNonesservices isinstancesselfstypestypess ClassTypesmethodsstrs startswithsInvalidServiceMethodErrorsgetattrsfuncsAttributeErrorsUnknownServiceMethodErrorscallable(sselfsmethodsparamssfuncsservice((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pys_get_service_funcOs&   cCs |i||}||SdS(st Executes the service. If the service is a class, it will be instantiated. @param method: The method to call on the service. @type method: C{None} or C{mixed} @param params: The params to pass to the service. @type params: C{list} or C{tuple} @return: The result of the execution. @rtype: C{mixed} N(sselfs_get_service_funcsmethodsparamssfunc(sselfsmethodsparamssfunc((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pys__call__vs cCsih}xXt|iD]G}t|i|}|idp t| oqn|||} @ivar service: Facilitates the request. @type service: L{ServiceWrapper} @ivar method: The method to call on the service. A value of C{None} means that the service will be called directly. @type method: C{None} or C{str} cCs||_||_||_dS(N(s amf_requestsselfsrequestsservicesmethod(sselfs amf_requestsservicesmethod((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pys__init__s  cGs|i|i|SdS(N(sselfsservicesmethodsargs(sselfsargs((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pys__call__s(s__name__s __module__s__doc__s__init__s__call__(((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pysServiceRequests  sServiceCollectioncBstZdZdZRS(sD I hold a collection of services, mapping names to objects. cCs8t|to||ijSn||ijSdS(N(s isinstancesvalues basestringsselfskeyssvalues(sselfsvalue((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pys __contains__s(s__name__s __module__s__doc__s __contains__(((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pysServiceCollections s BaseGatewaycBstZdZeZhdZeeeeedZdZdZ dZ dZ dZ dZ d Zd Zd Zd Zd ZRS(s9 Generic Remoting gateway. @ivar services: A map of service names to callables. @type services: L{ServiceCollection} @ivar authenticator: A callable that will check the credentials of the request before allowing access to the service. Will return a C{bool} value. @type authenticator: C{Callable} or C{None} @ivar preprocessor: Called before the actual service method is invoked. Useful for setting up sessions etc. @type preprocessor: C{Callable} or C{None} @ivar logger: A logging instance. @ivar strict: Defines whether the gateway should use strict en/decoding. @type strict: C{bool} @ivar timezone_offset: A L{datetime.timedelta} between UTC and the timezone to be encoded. Most dates should be handled as UTC to avoid confusion but for older legacy systems this is not an option. Supplying an int as this will be interpretted in seconds. @ivar debug: Provides debugging information when an error occurs. Use only in non production settings. @type debug: C{bool} cKst|d otdnt|_|idt|_|idt|_ |idt |_ |idt |_ |idt|_ |idt|_|id t |_|otd |fnx*|iD]\}}|i||qWdS( Ns iteritemssdict type required for servicess authenticators preprocessorsexpose_requestsstrictsloggerstimezone_offsetsdebugsUnknown kwargs: %r(shasattrsservicess TypeErrorsServiceCollectionsselfskwargsspopsNones authenticators preprocessorsFalsesexpose_requestsstrictsloggerstimezone_offsetsdebugs iteritemssnamesservices addService(sselfsservicesskwargssnamesservice((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pys__init__s  cCsRt|ttttfotdntiti ti ti ti ti f}t| ot|| otdn|tjovt|ttifo |i}qt|ti o |i}qt|tio |i}qt|}n||ijotid|nt||||||i|} @rtype: L{ServiceRequest} s.isUnknown service %sN(sselfs_request_classsrequestsenvelopesservicesstargetsNonesKeyErrorssplitsspsjoinsnamesmeths ValueErrorsUnknownServiceError(sselfsrequeststargetsspsmethsname((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pysgetServiceRequestss!#!cCsL|idjodkl}|i|Sndkl}|i|SdS(s Returns request processor. @param request: The AMF message. @type request: L{Request} snull(samf3(samf0N(srequeststargetspyamf.remotingsamf3sRequestProcessorsselfsamf0(sselfsrequestsamf0samf3((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pys getProcessors   cCs tdS(s: Returns the response to the request. Any implementing gateway must define this function. @param amf_request: The AMF request. @type amf_request: L{Envelope} @return: The AMF response. @rtype: L{Envelope} N(sNotImplementedError(sselfs amf_request((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pys getResponses cCsJ|ii|}|tjo#|itjotSn|iSn|SdS(s Decides whether the underlying http request should be exposed as the first argument to the method call. This is granular, looking at the service method first, then at the service level and finally checking the gateway. @rtype: C{bool} N(sservice_requestsservicesmustExposeRequestsexpose_requestsNonesselfsFalse(sselfsservice_requestsexpose_request((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pysmustExposeRequests  cCs2|ii|}|tjo |iSn|SdS(s2 Gets an authenticator callable based on the service_request. This is granular, looking at the service method first, then at the service level and finally to see if there is a global authenticator function for the gateway. Returns C{None} if one could not be found. N(sservice_requestsservicesgetAuthenticatorsauthsNonesselfs authenticator(sselfsservice_requestsauth((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pysgetAuthenticators   cKsw|i|}|tjotSn||f}t |do#|i dt}|f|}n||tjSdS(sO Processes an authentication request. If no authenticator is supplied, then authentication succeeds. @return: Returns a C{bool} based on the result of authorization. A value of C{False} will stop processing the request and return an error to the client. @rtype: C{bool} s_pyamf_expose_requests http_requestN( sselfsgetAuthenticatorsservice_requests authenticatorsNonesTruesusernamespasswordsargsshasattrskwargssgets http_request(sselfsservice_requestsusernamespasswordskwargssargss http_requests authenticator((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pysauthenticateRequests   cCs2|ii|}|tjo |iSn|SdS(s/ Gets a preprocessor callable based on the service_request. This is granular, looking at the service method first, then at the service level and finally to see if there is a global preprocessor function for the gateway. Returns C{None} if one could not be found. N(sservice_requestsservicesgetPreprocessorspreprocsNonesselfs preprocessor(sselfsservice_requestspreproc((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pysgetPreprocessors   cOsr|i|}|tjodSn|f|}t|do#|idt}|f|}n||SdS(s) Preprocesses a request. Ns_pyamf_expose_requests http_request( sselfsgetPreprocessorsservice_requests processorsNonesargsshasattrskwargssgets http_request(sselfsservice_requestsargsskwargss http_requests processor((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pyspreprocessRequests  cOsA|i|o#|idt}|f|}n||SdS(s3 Executes the service_request call s http_requestN(sselfsmustExposeRequestsservice_requestskwargssgetsNones http_requestsargs(sselfsservice_requestsargsskwargss http_request((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pyscallServiceRequests (s__name__s __module__s__doc__sServiceRequests_request_classs__init__sNones addServices_get_timezone_offsets removeServicesgetServiceRequests getProcessors getResponsesmustExposeRequestsgetAuthenticatorsauthenticateRequestsgetPreprocessorspreprocessRequestscallServiceRequest(((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pys BaseGateways  '         cCst| otdnt| otdn|}t|tio |i}n|t jot d|}nt |d||SdS(sx A decorator that facilitates authentication per method. Setting C{expose_request} to C{True} will set the underlying request object (if there is one), usually HTTP and set it to the first argument of the authenticating callable. If there is no request object, the default is C{None}. @raise TypeError: C{func} and authenticator must be callable. sfunc must be callablesAuthenticator must be callablesexpose_requests_pyamf_authenticatorN( scallablesfuncs TypeErrorscsattrs isinstancestypessUnboundMethodTypesim_funcsexpose_requestsTruesglobalsssetattr(sfuncscsexpose_requestsattr((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pys authenticate s   cCs`t| otdnt|tiot|idtnt|dt|SdS(s A decorator that adds an expose_request flag to the underlying callable. @raise TypeError: C{func} must be callable. sfunc must be callables_pyamf_expose_requestN( scallablesfuncs TypeErrors isinstancestypessUnboundMethodTypessetattrsim_funcsTrue(sfunc((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pysexpose_request*scCst| otdnt| otdn|}t|tio |i}n|t jot d|}nt |d||SdS(su A decorator that facilitates preprocessing per method. Setting C{expose_request} to C{True} will set the underlying request object (if there is one), usually HTTP and set it to the first argument of the preprocessing callable. If there is no request object, the default is C{None}. @raise TypeError: C{func} and preprocessor must be callable. sfunc must be callablesPreprocessor must be callablesexpose_requests_pyamf_preprocessorN( scallablesfuncs TypeErrorscsattrs isinstancestypessUnboundMethodTypesim_funcsexpose_requestsTruesglobalsssetattr(sfuncscsexpose_requestsattr((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pys preprocess;s   cCs3dk}ti}|id||iSdS(Nsfile(s tracebacksutilsStringIOsfs print_excsgetvalue(s tracebacksf((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pysformat_exceptionXs  ( s__doc__ssysstypessdatetimespyamfsremotingsutilsplatformspython_implementationsimpls ImportErrorsjoinsmaps __version__s version_infos SERVER_NAMEs BaseErrorsBaseServiceErrorsUnknownServiceErrorsUnknownServiceMethodErrorsInvalidServiceMethodErrorsobjectsServiceWrappersServiceRequestsdictsServiceCollections BaseGatewaysFalses authenticatesexpose_requests preprocesssformat_exception(sremotingsUnknownServiceErrorspyamfsdatetimes BaseGatewaysexpose_requestsInvalidServiceMethodErrors authenticates SERVER_NAMEsServiceCollections preprocessspython_implementationsBaseServiceErrorsServiceRequestsutilstypesssyssformat_exceptionsServiceWrappersimplsUnknownServiceMethodError((s?build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/__init__.pys?s0       J    PK:u3;u8`WW!pyamf/remoting/gateway/django.pyc; DȠJc@sydZedZeiZedZeiZdkZdklZdklZdgZ dei fdYZ dS(s Gateway for the Django framework. This gateway allows you to expose functions in Django to AMF clients and servers. @see: U{Django homepage (external)} @since: 0.1.0 s django.https django.confN(sremoting(sgateways DjangoGatewaycBs)tZdZdZdZdZRS(sK An instance of this class is suitable as a Django view. An example usage would be through C{urlconf}:: from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^gateway/', 'yourproject.yourapp.gateway.gw_instance'), ) where C{yourproject.yourapp.gateway.gw_instance} refers to an instance of this class. @ivar expose_request: The standard Django view always has the request object as the first parameter. To disable this functionality, set this to C{False}. @type expose_request: C{bool} cOs|idt|d} @param request: The AMF Request. @type request: L{Envelope} @rtype: L{Envelope} @return: The AMF Response. s http_requestN( sremotingsEnvelopesrequests amfVersions clientTypesresponsesnamesmessages http_requests amf_requestsselfs getProcessors processor(sselfs http_requestsrequestsnames processorsmessagesresponse((s=build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/django.pys getResponseBs   c Cs9|idjotidgSnt}|i}y.t i |i d|i d|i d|}Wntitfj oiti}|i o|i i|nd}|io|d|7}ntiddd |Snttfj o njti}|i o|i i|nd }|io|d|7}ntiddd |SnX|i o|i id |ny|i||}Wnttfj o njti}|i o|i i|nd }|io|d|7}ntiddd |SnX|i o|i id |ny+t i|d|i d|i d|}Wniti}|i o|i i|nd}|io|d|7}ntiddd |SnX|i}ti!dt i"}ti$|d} @since: 0.1.0 Nsstwistedstwisted.internet.deferstwisted.internet.threadsstwisted.web.resourcestwisted.web.server(sremoting(sgatewaysamf0samf3sTwistedGatewaysAMF0RequestProcessorcBstZdZdZRS(sq A Twisted friendly implementation of L{amf0.RequestProcessor} c syiiiWn,tij otii SnXt i t  tid d d d}tii} | i|iSdS(s Calls the underlying service method. @return: A C{Deferred} that will contain the AMF L{Response}. @rtype: C{twisted.internet.defer.Deferred} csd|i|if}iio0iii|iii|i ni i |i|i|ifdS(Ns%s: %s(sfailurestypesgetErrorMessageserrMesgsselfsgatewaysloggerserrorsinfos getTracebacksdeferred_responsescallbacksbuildErrorResponsesrequestsvaluestb(sfailureserrMesg(sdeferred_responsesselfsrequest(s>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pysebCs  csEiioiiid|fn|_idS(NsAMF Response: %s( sselfsgatewaysloggersdebugsresultsresponsesbodysdeferred_responsescallback(sresult(sdeferred_responsesselfsresponse(s>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pys response_cbMs  cs8tii}|i i dS(N( sdefers maybeDeferredsselfs_getBodysrequestsresponsesservice_requestskwargssds addCallbacks response_cbs addErrbackseb(sresultsd(sservice_requestsselfsrequestsebskwargss response_cbsresponse(s>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pys preprocess_cbUs cs|tj o<ti_tidddd_i dSnt i i i}|iidS(NscodesAuthenticationErrors descriptionsAuthentication failed(sresultsTruesremotings STATUS_ERRORsresponsesstatuss ErrorFaultsbodysdeferred_responsescallbacksdefers maybeDeferredsselfsgatewayspreprocessRequestsservice_requestsargsskwargssds addCallbacks preprocess_cbs addErrbackseb(sresultsd(sservice_requests preprocess_cbsselfsargssebskwargssdeferred_responsesresponse(s>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pysauth_cb[s    N(sselfsgatewaysgetServiceRequestsrequeststargetsservice_requestsUnknownServiceErrorsdeferssucceedsbuildErrorResponsesremotingsResponsesNonesresponsesDeferredsdeferred_responsesebs response_cbs preprocess_cbsauth_cbs maybeDeferredsauthenticateRequestskwargssds addCallbacks addErrback( sselfsrequestsargsskwargssservice_requestsauth_cbs preprocess_cbsresponsesdeferred_responsesebs response_cbsd(( sselfsrequestsargsskwargssservice_requests response_cbs preprocess_cbsebsdeferred_responsesresponses>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pys__call__3s  ! (s__name__s __module__s__doc__s__call__(((s>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pysAMF0RequestProcessor-s sAMF3RequestProcessorcBs tZdZdZdZRS(sq A Twisted friendly implementation of L{amf3.RequestProcessor} c  sEtitidti} ySi}t doi odi |f}ni i||Wn>t ij o/titiidtiSnXtiddd}tii ii}|i |i!SdS(Nsstatuss destinations%s.%scsd|i|if}iio0iii|iii|i ni |i|i |i f}iti|dtidS(Ns%s: %ssstatus(sfailurestypesgetErrorMessageserrMesgsselfsgatewaysloggerserrorsinfos getTracebacksbuildErrorResponses ro_requestsvaluestbs ro_responsesdeferred_responsescallbacksremotingsResponses STATUS_ERROR(sfailures ro_responseserrMesg(sselfsdeferred_responses ro_request(s>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pysebs $csT|_ti}iioiii d|fni |dS(NsAMF Response: %r( sresults ro_responsesbodysremotingsResponsesressselfsgatewaysloggersdebugsdeferred_responsescallback(sresultsres(s ro_responsesselfsdeferred_response(s>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pys response_cbs   cs;tiiii}|i i dS(N(sdefers maybeDeferredsselfsgatewayscallServiceRequestsservice_requests ro_requestsbodyskwargssds addCallbacks response_cbs addErrbackseb(sresultsd(sservice_requestsselfsebskwargss response_cbs ro_request(s>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pys process_cbs("samf3sgenerate_acknowledgements ro_requests ro_responsesremotingsResponses STATUS_OKs amf_responses operations service_nameshasattrs destinationsselfsgatewaysgetServiceRequests amf_requestsservice_requestsUnknownServiceErrorsdeferssucceedsbuildErrorResponses STATUS_ERRORsDeferredsdeferred_responsesebs response_cbs process_cbs maybeDeferredspreprocessRequestsbodyskwargssds addCallbacks addErrback( sselfs amf_requests ro_requestskwargssservice_requests ro_responsesds service_names process_cbs amf_responsesdeferred_responsesebs response_cb((sselfs ro_requestskwargssservice_requests response_cbs ro_responsesebsdeferred_responses>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pys_processRemotingMessagexs$      !c spti|idd}d}tii ||}|i |i|SdS(s Calls the underlying service method. @return: A C{deferred} that will contain the AMF L{Response}. @rtype: C{Deferred} icsi|dS(N(sdeferred_responsescallbacks amf_response(s amf_response(sdeferred_response(s>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pyscbscsd|i|if}iio0iii|iii|i ni i |i|i|ifdS(Ns%s: %s(sfailurestypesgetErrorMessageserrMesgsselfsgatewaysloggerserrorsinfos getTracebacksdeferred_responsescallbacksbuildErrorResponses ro_requestsvaluestb(sfailureserrMesg(sdeferred_responsesselfs ro_request(s>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pysebs  N(sdefersDeferredsdeferred_responses amf_requestsbodys ro_requestscbsebs maybeDeferredsselfs_getBodyskwargssds addCallbacks addErrback(sselfs amf_requestskwargssdscbsebsdeferred_responses ro_request((sselfsdeferred_responses ro_requests>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pys__call__s    (s__name__s __module__s__doc__s_processRemotingMessages__call__(((s>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pysAMF3RequestProcessorrs  3cBsbtZdZdfZdZddZdZdZdZdZ d Z d Z RS( s Twisted Remoting gateway for C{twisted.web}. @ivar expose_request: Forces the underlying HTTP request to be the first argument to any service call. @type expose_request: C{bool} sPOSTcOsEd|jot|dbuild/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pys__init__s s text/plaincCsg|i||id||idtt||idti |i ||i dS(sm Finalises the request. @param request: The HTTP Request. @type request: C{http.Request} @param status: The HTTP status code. @type status: C{int} @param content: The content of the response. @type content: C{str} @param mimetype: The MIME type of the request. @type mimetype: C{str} s Content-TypesContent-LengthsServerN( srequestssetResponseCodesstatuss setHeadersmimetypesstrslenscontentsgateways SERVER_NAMEswritesfinish(sselfsrequestsstatusscontentsmimetype((s>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pys_finaliseRequests   c sd}iiddi}tit i ii di di d|}d}|i|i|tiSdS(s Read remoting request from the client. @type request: The HTTP Request. @param request: C{twisted.web.http.Request} csd|i|if}io*ii|ii|ind}i o|d|i7}ni d|dS(s6 Return HTTP 400 Bad Request. s%s: %ssH400 Bad Request The request body was unable to be successfully decoded.s Traceback: %siN( sfailurestypesgetErrorMessageserrMesgsselfsloggerserrorsinfos getTracebacksbodysdebugs_finaliseRequestsrequest(sfailuresbodyserrMesg(sselfsrequest(s>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pyshandleDecodeErrors  isstrictsloggerstimezone_offsetcsKioiid|ni|}|iidS(NsAMF Request: %r( sselfsloggersdebugs amf_requests getResponsesrequestsxs addCallbacks sendResponse(s amf_requestsx(sselfsrequest(s>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pyscbs N(shandleDecodeErrorsrequestscontentsseeksselfs_get_timezone_offsetstimezone_offsetsthreadss deferToThreadsremotingsdecodesreadsstrictsloggersdscbs addCallbacks addErrbacksservers NOT_DONE_YET(sselfsrequestshandleDecodeErrorsdscbstimezone_offset((sselfsrequests>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pys render_POSTs   c sqd}d}i}titi|di di d|}|i |i|dS(Ncs#id|itidS(Ni(sselfs_finaliseRequestsrequestsresultsgetvaluesremotings CONTENT_TYPE(sresult(sselfsrequest(s>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pyscbscsd|i|if}io*ii|ii|ind}i o|d|i7}ni d|dS(s; Return 500 Internal Server Error. s%s: %ssD500 Internal Server Error There was an error encoding the response.s Traceback: %siN( sfailurestypesgetErrorMessageserrMesgsselfsloggerserrorsinfos getTracebacksbodysdebugs_finaliseRequestsrequest(sfailuresbodyserrMesg(sselfsrequest(s>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pyseb"s  sstrictsloggerstimezone_offset(scbsebsselfs_get_timezone_offsetstimezone_offsetsthreadss deferToThreadsremotingsencodes amf_responsesstrictsloggersds addCallbacks addErrback(sselfs amf_responsesrequestsdscbstimezone_offsetseb((sselfsrequests>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pys sendResponses  cCs,|idjot|Snt|SdS(s Determines the request processor, based on the request. @param request: The AMF message. @type request: L{Request} snullN(srequeststargetsAMF3RequestProcessorsselfsAMF0RequestProcessor(sselfsrequest((s>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pys getProcessor;sc sti|i|ig}d}x]|D]U\}}i |}|_ti||d} |i| i||q1Wd}d} ti|} | i|i| SdS(s) Processes the AMF request, returning an AMF L{Response}. @param http_request: The underlying HTTP Request @type http_request: C{twisted.web.http.Request} @param amf_request: The AMF Request. @type amf_request: L{Envelope} cs||build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pyscbTss http_requestcsSdS(N(sresponse(sresult(sresponse(s>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pyscb2ascsd|i|if}io*ii|ii|ind}i o|d|i7}ni d|dS(s; Return 500 Internal Server Error. s%s: %ssO500 Internal Server Error The request was unable to be successfully processed.s Traceback: %siN( sfailurestypesgetErrorMessageserrMesgsselfsloggerserrorsinfos getTracebacksbodysdebugs_finaliseRequests http_request(sfailuresbodyserrMesg(sselfs http_request(s>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pysebds  N(sremotingsEnvelopes amf_requests amfVersions clientTypesresponsesdlscbsnamesmessagesselfs getProcessors processors http_requestsdefers maybeDeferredsdsappends addCallbackscb2sebs DeferredLists addErrback( sselfs http_requests amf_requestsdlsnamescbs processorscb2smessagesebsresponsesd((sselfs http_requestsresponses>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pys getResponseGs      cKs|i|}|io|iid|n|tjotit Sn||f}t |do#|idt}|f|}nti||SdS(s Processes an authentication request. If no authenticator is supplied, then authentication succeeds. @return: C{Deferred}. @rtype: C{twisted.internet.defer.Deferred} sAuthenticator expands to: %rs_pyamf_expose_requests http_requestN(sselfsgetAuthenticatorsservice_requests authenticatorsloggersdebugsNonesdeferssucceedsTruesusernamespasswordsargsshasattrskwargssgets http_requests maybeDeferred(sselfsservice_requestsusernamespasswordskwargssargss http_requests authenticator((s>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pysauthenticateRequestzs   cOs|i|}|io|iid|n|tjodSn|f|}t|do#|i dt}|f|}nt i ||SdS(s) Preprocesses a request. sPreprocessor expands to: %rNs_pyamf_expose_requests http_request(sselfsgetPreprocessorsservice_requests processorsloggersdebugsNonesargsshasattrskwargssgets http_requestsdefers maybeDeferred(sselfsservice_requestsargsskwargss http_requests processor((s>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pyspreprocessRequests   ( s__name__s __module__s__doc__sallowedMethodss__init__s_finaliseRequests render_POSTs sendResponses getProcessors getResponsesauthenticateRequestspreprocessRequest(((s>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pysTwistedGateways     -  3 (s__doc__ssyssos.pathsosspathsremoves ValueErrorsdirnamesabspaths__file__s __import__stwistedsinternetsdefersthreadsswebsresourcesserverspyamfsremotingspyamf.remotingsgatewaysamf0samf3s__all__sRequestProcessorsAMF0RequestProcessorsAMF3RequestProcessors BaseGatewaysResourcesTwistedGateway(sdefersremotingsresources__all__stwistedsTwistedGatewaysserverssyssamf0samf3sthreadssAMF3RequestProcessorsAMF0RequestProcessorsgatewaysos((s>build/bdist.linux-x86_64/egg/pyamf/remoting/gateway/twisted.pys? s2  ,           EVPK:*@@!pyamf/remoting/client/__init__.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Remoting client implementation. @since: 0.1.0 """ import httplib import urlparse import pyamf from pyamf import remoting #: Default AMF client type. #: @see: L{ClientTypes} DEFAULT_CLIENT_TYPE = pyamf.ClientTypes.Flash6 #: Default user agent is C{PyAMF/x.x.x}. DEFAULT_USER_AGENT = 'PyAMF/%s' % '.'.join(map(lambda x: str(x), pyamf.__version__)) HTTP_OK = 200 def convert_args(args): if args == (tuple(),): return [] else: return [x for x in args] class ServiceMethodProxy(object): """ Serves as a proxy for calling a service method. @ivar service: The parent service. @type service: L{ServiceProxy} @ivar name: The name of the method. @type name: C{str} or C{None} @see: L{ServiceProxy.__getattr__} """ def __init__(self, service, name): self.service = service self.name = name def __call__(self, *args): """ Inform the proxied service that this function has been called. """ return self.service._call(self, *args) def __str__(self): """ Returns the full service name, including the method name if there is one. """ service_name = str(self.service) if self.name is not None: service_name = '%s.%s' % (service_name, self.name) return service_name class ServiceProxy(object): """ Serves as a service object proxy for RPC calls. Generates L{ServiceMethodProxy} objects for method calls. @see: L{RequestWrapper} for more info. @ivar _gw: The parent gateway @type _gw: L{RemotingService} @ivar _name: The name of the service @type _name: C{str} @ivar _auto_execute: If set to C{True}, when a service method is called, the AMF request is immediately sent to the remote gateway and a response is returned. If set to C{False}, a L{RequestWrapper} is returned, waiting for the underlying gateway to fire the L{execute} method. """ def __init__(self, gw, name, auto_execute=True): self._gw = gw self._name = name self._auto_execute = auto_execute def __getattr__(self, name): return ServiceMethodProxy(self, name) def _call(self, method_proxy, *args): """ Executed when a L{ServiceMethodProxy} is called. Adds a request to the underlying gateway. If C{_auto_execute} is set to C{True}, then the request is immediately called on the remote gateway. """ request = self._gw.addRequest(method_proxy, *args) if self._auto_execute: response = self._gw.execute_single(request) # XXX nick: What to do about Fault objects here? return response.body return request def __call__(self, *args): """ This allows services to be 'called' without a method name. """ return self._call(ServiceMethodProxy(self, None), *args) def __str__(self): """ Returns a string representation of the name of the service. """ return self._name class RequestWrapper(object): """ A container object that wraps a service method request. @ivar gw: The underlying gateway. @type gw: L{RemotingService} @ivar id: The id of the request. @type id: C{str} @ivar service: The service proxy. @type service: L{ServiceProxy} @ivar args: The args used to invoke the call. @type args: C{list} """ def __init__(self, gw, id_, service, *args): self.gw = gw self.id = id_ self.service = service self.args = args def __str__(self): return str(self.id) def setResponse(self, response): """ A response has been received by the gateway """ # XXX nick: What to do about Fault objects here? self.response = response self.result = self.response.body if isinstance(self.result, remoting.ErrorFault): self.result.raiseException() def _get_result(self): """ Returns the result of the called remote request. If the request has not yet been called, an C{AttributeError} exception is raised. """ if not hasattr(self, '_result'): raise AttributeError("'RequestWrapper' object has no attribute 'result'") return self._result def _set_result(self, result): self._result = result result = property(_get_result, _set_result) class RemotingService(object): """ Acts as a client for AMF calls. @ivar url: The url of the remote gateway. Accepts C{http} or C{https} as valid schemes. @type url: C{str} @ivar requests: The list of pending requests to process. @type requests: C{list} @ivar request_number: A unique identifier for tracking the number of requests. @ivar amf_version: The AMF version to use. See L{ENCODING_TYPES}. @type amf_version: C{int} @ivar referer: The referer, or HTTP referer, identifies the address of the client. Ignored by default. @type referer: C{str} @ivar client_type: The client type. See L{ClientTypes}. @type client_type: C{int} @ivar user_agent: Contains information about the user agent (client) originating the request. See L{DEFAULT_USER_AGENT}. @type user_agent: C{str} @ivar connection: The underlying connection to the remoting server. @type connection: C{httplib.HTTPConnection} or C{httplib.HTTPSConnection} @ivar headers: A list of persistent headers to send with each request. @type headers: L{HeaderCollection} @ivar http_headers: A dict of HTTP headers to apply to the underlying HTTP connection. @type http_headers: L{dict} @ivar strict: Whether to use strict AMF en/decoding or not. @type strict: C{bool} """ def __init__(self, url, amf_version=pyamf.AMF0, client_type=DEFAULT_CLIENT_TYPE, referer=None, user_agent=DEFAULT_USER_AGENT, strict=False, logger=None): self.logger = logger self.original_url = url self.requests = [] self.request_number = 1 self.user_agent = user_agent self.referer = referer self.amf_version = amf_version self.client_type = client_type self.headers = remoting.HeaderCollection() self.http_headers = {} self.strict = strict self._setUrl(url) def _setUrl(self, url): """ @param url: Gateway URL. @type url: C{str} @raise ValueError: Unknown scheme. """ self.url = urlparse.urlparse(url) self._root_url = urlparse.urlunparse(['', ''] + list(self.url[2:])) port = None hostname = None if hasattr(self.url, 'port'): if self.url.port is not None: port = self.url.port else: if ':' not in self.url[1]: hostname = self.url[1] port = None else: sp = self.url[1].split(':') hostname, port = sp[0], sp[1] port = int(port) if hostname is None: if hasattr(self.url, 'hostname'): hostname = self.url.hostname if self.url[0] == 'http': if port is None: port = httplib.HTTP_PORT self.connection = httplib.HTTPConnection(hostname, port) elif self.url[0] == 'https': if port is None: port = httplib.HTTPS_PORT self.connection = httplib.HTTPSConnection(hostname, port) else: raise ValueError('Unknown scheme') location = '%s://%s:%s%s' % (self.url[0], hostname, port, self.url[2]) if self.logger: self.logger.info('Connecting to %s' % location) self.logger.debug('Referer: %s' % self.referer) self.logger.debug('User-Agent: %s' % self.user_agent) def addHeader(self, name, value, must_understand=False): """ Sets a persistent header to send with each request. @param name: Header name. @type name: C{str} @param must_understand: Default is C{False}. @type must_understand: C{bool} """ self.headers[name] = value self.headers.set_required(name, must_understand) def addHTTPHeader(self, name, value): """ Adds a header to the underlying HTTP connection. """ self.http_headers[name] = value def removeHTTPHeader(self, name): """ Deletes an HTTP header. """ del self.http_headers[name] def getService(self, name, auto_execute=True): """ Returns a L{ServiceProxy} for the supplied name. Sets up an object that can have method calls made to it that build the AMF requests. @param auto_execute: Default is C{True}. @type auto_execute: C{bool} @raise TypeError: C{string} type required for C{name}. @rtype: L{ServiceProxy} """ if not isinstance(name, basestring): raise TypeError('string type required') return ServiceProxy(self, name, auto_execute) def getRequest(self, id_): """ Gets a request based on the id. @raise LookupError: Request not found. """ for request in self.requests: if request.id == id_: return request raise LookupError("Request %s not found" % id_) def addRequest(self, service, *args): """ Adds a request to be sent to the remoting gateway. """ wrapper = RequestWrapper(self, '/%d' % self.request_number, service, *args) self.request_number += 1 self.requests.append(wrapper) if self.logger: self.logger.debug('Adding request %s%r' % (wrapper.service, args)) return wrapper def removeRequest(self, service, *args): """ Removes a request from the pending request list. @raise LookupError: Request not found. """ if isinstance(service, RequestWrapper): if self.logger: self.logger.debug('Removing request: %s' % ( self.requests[self.requests.index(service)])) del self.requests[self.requests.index(service)] return for request in self.requests: if request.service == service and request.args == args: if self.logger: self.logger.debug('Removing request: %s' % ( self.requests[self.requests.index(request)])) del self.requests[self.requests.index(request)] return raise LookupError("Request not found") def getAMFRequest(self, requests): """ Builds an AMF request L{Envelope} from a supplied list of requests. @param requests: List of requests @type requests: C{list} @rtype: L{Envelope} """ envelope = remoting.Envelope(self.amf_version, self.client_type) if self.logger: self.logger.debug('AMF version: %s' % self.amf_version) self.logger.debug('Client type: %s' % self.client_type) for request in requests: service = request.service args = list(request.args) envelope[request.id] = remoting.Request(str(service), args) envelope.headers = self.headers return envelope def _get_execute_headers(self): headers = self.http_headers.copy() headers.update({ 'Content-Type': remoting.CONTENT_TYPE, 'User-Agent': self.user_agent }) if self.referer is not None: headers['Referer'] = self.referer return headers def execute_single(self, request): """ Builds, sends and handles the response to a single request, returning the response. @param request: @type request: @rtype: """ if self.logger: self.logger.debug('Executing single request: %s' % request) body = remoting.encode(self.getAMFRequest([request]), strict=self.strict) if self.logger: self.logger.debug('Sending POST request to %s' % self._root_url) self.connection.request('POST', self._root_url, body.getvalue(), self._get_execute_headers() ) envelope = self._getResponse() self.removeRequest(request) return envelope[request.id] def execute(self): """ Builds, sends and handles the responses to all requests listed in C{self.requests}. """ body = remoting.encode(self.getAMFRequest(self.requests), strict=self.strict) if self.logger: self.logger.debug('Sending POST request to %s' % self._root_url) self.connection.request('POST', self._root_url, body.getvalue(), self._get_execute_headers() ) envelope = self._getResponse() for response in envelope: request = self.getRequest(response[0]) response = response[1] request.setResponse(response) self.removeRequest(request) def _getResponse(self): """ Gets and handles the HTTP response from the remote gateway. @raise RemotingError: HTTP Gateway reported error status. @raise RemotingError: Incorrect MIME type received. """ if self.logger: self.logger.debug('Waiting for response...') http_response = self.connection.getresponse() if self.logger: self.logger.debug('Got response status: %s' % http_response.status) self.logger.debug('Content-Type: %s' % http_response.getheader('Content-Type')) if http_response.status != HTTP_OK: if self.logger: self.logger.debug('Body: %s' % http_response.read()) if hasattr(httplib, 'responses'): raise remoting.RemotingError("HTTP Gateway reported status %d %s" % ( http_response.status, httplib.responses[http_response.status])) raise remoting.RemotingError("HTTP Gateway reported status %d" % ( http_response.status,)) content_type = http_response.getheader('Content-Type') if content_type != remoting.CONTENT_TYPE: if self.logger: self.logger.debug('Body = %s' % http_response.read()) raise remoting.RemotingError("Incorrect MIME type received. (got: %s)" % content_type) content_length = http_response.getheader('Content-Length') bytes = '' if self.logger: self.logger.debug('Content-Length: %s' % content_length) self.logger.debug('Server: %s' % http_response.getheader('Server')) if content_length in (None, ''): bytes = http_response.read() else: bytes = http_response.read(int(content_length)) if self.logger: self.logger.debug('Read %d bytes for the response' % len(bytes)) response = remoting.decode(bytes, strict=self.strict) if self.logger: self.logger.debug('Response: %s' % response) if remoting.APPEND_TO_GATEWAY_URL in response.headers: self.original_url += response.headers[remoting.APPEND_TO_GATEWAY_URL] self._setUrl(self.original_url) elif remoting.REPLACE_GATEWAY_URL in response.headers: self.original_url = response.headers[remoting.REPLACE_GATEWAY_URL] self._setUrl(self.original_url) if remoting.REQUEST_PERSISTENT_HEADER in response.headers: data = response.headers[remoting.REQUEST_PERSISTENT_HEADER] for k, v in data.iteritems(): self.headers[k] = v http_response.close() return response def setCredentials(self, username, password): """ Sets authentication credentials for accessing the remote gateway. """ self.addHeader('Credentials', dict(userid=unicode(username), password=unicode(password)), True) PK:u3;lSS"pyamf/remoting/client/__init__.pyc; VJc@sdZdkZdkZdkZdklZeiiZddie dei Z dZ dZ defd YZd efd YZd efd YZdefdYZdS(s0 Remoting client implementation. @since: 0.1.0 N(sremotingsPyAMF/%ss.cCs t|S(N(sstrsx(sx((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pyssicCsD|tfjogSn&gi}|D]}||q)~SdS(N(sargsstuplesappends_[1]sx(sargss_[1]sx((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys convert_argsssServiceMethodProxycBs)tZdZdZdZdZRS(s Serves as a proxy for calling a service method. @ivar service: The parent service. @type service: L{ServiceProxy} @ivar name: The name of the method. @type name: C{str} or C{None} @see: L{ServiceProxy.__getattr__} cCs||_||_dS(N(sservicesselfsname(sselfsservicesname((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys__init__.s cGs|ii||SdS(sP Inform the proxied service that this function has been called. N(sselfsservices_callsargs(sselfsargs((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys__call__2scCs>t|i}|itj od||if}n|SdS(sc Returns the full service name, including the method name if there is one. s%s.%sN(sstrsselfsservices service_namesnamesNone(sselfs service_name((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys__str__9s (s__name__s __module__s__doc__s__init__s__call__s__str__(((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pysServiceMethodProxy"s   s ServiceProxycBs>tZdZedZdZdZdZdZRS(s| Serves as a service object proxy for RPC calls. Generates L{ServiceMethodProxy} objects for method calls. @see: L{RequestWrapper} for more info. @ivar _gw: The parent gateway @type _gw: L{RemotingService} @ivar _name: The name of the service @type _name: C{str} @ivar _auto_execute: If set to C{True}, when a service method is called, the AMF request is immediately sent to the remote gateway and a response is returned. If set to C{False}, a L{RequestWrapper} is returned, waiting for the underlying gateway to fire the L{execute} method. cCs||_||_||_dS(N(sgwsselfs_gwsnames_names auto_executes _auto_execute(sselfsgwsnames auto_execute((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys__init__Xs  cCst||SdS(N(sServiceMethodProxysselfsname(sselfsname((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys __getattr__]scGsD|ii||}|io|ii|}|i Sn|SdS(s Executed when a L{ServiceMethodProxy} is called. Adds a request to the underlying gateway. If C{_auto_execute} is set to C{True}, then the request is immediately called on the remote gateway. N( sselfs_gws addRequests method_proxysargssrequests _auto_executesexecute_singlesresponsesbody(sselfs method_proxysargssrequestsresponse((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys_call`s   cGs|it|t|SdS(sL This allows services to be 'called' without a method name. N(sselfs_callsServiceMethodProxysNonesargs(sselfsargs((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys__call__pscCs |iSdS(sM Returns a string representation of the name of the service. N(sselfs_name(sself((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys__str__vs( s__name__s __module__s__doc__sTrues__init__s __getattr__s_calls__call__s__str__(((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys ServiceProxyFs     sRequestWrappercBsJtZdZdZdZdZdZdZeeeZ RS(sV A container object that wraps a service method request. @ivar gw: The underlying gateway. @type gw: L{RemotingService} @ivar id: The id of the request. @type id: C{str} @ivar service: The service proxy. @type service: L{ServiceProxy} @ivar args: The args used to invoke the call. @type args: C{list} cGs(||_||_||_||_dS(N(sgwsselfsid_sidsservicesargs(sselfsgwsid_sservicesargs((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys__init__s   cCst|iSdS(N(sstrsselfsid(sself((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys__str__scCsC||_|ii|_t|itio|iindS(s= A response has been received by the gateway N(sresponsesselfsbodysresults isinstancesremotings ErrorFaultsraiseException(sselfsresponse((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys setResponses  cCs,t|d otdn|iSdS(s Returns the result of the called remote request. If the request has not yet been called, an C{AttributeError} exception is raised. s_results1'RequestWrapper' object has no attribute 'result'N(shasattrsselfsAttributeErrors_result(sself((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys _get_resultscCs ||_dS(N(sresultsselfs_result(sselfsresult((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys _set_results( s__name__s __module__s__doc__s__init__s__str__s setResponses _get_results _set_resultspropertysresult(((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pysRequestWrapper}s    sRemotingServicecBstZdZeieeeeedZ dZ edZ dZ dZ edZdZdZd Zd Zd Zd Zd ZdZdZRS(s| Acts as a client for AMF calls. @ivar url: The url of the remote gateway. Accepts C{http} or C{https} as valid schemes. @type url: C{str} @ivar requests: The list of pending requests to process. @type requests: C{list} @ivar request_number: A unique identifier for tracking the number of requests. @ivar amf_version: The AMF version to use. See L{ENCODING_TYPES}. @type amf_version: C{int} @ivar referer: The referer, or HTTP referer, identifies the address of the client. Ignored by default. @type referer: C{str} @ivar client_type: The client type. See L{ClientTypes}. @type client_type: C{int} @ivar user_agent: Contains information about the user agent (client) originating the request. See L{DEFAULT_USER_AGENT}. @type user_agent: C{str} @ivar connection: The underlying connection to the remoting server. @type connection: C{httplib.HTTPConnection} or C{httplib.HTTPSConnection} @ivar headers: A list of persistent headers to send with each request. @type headers: L{HeaderCollection} @ivar http_headers: A dict of HTTP headers to apply to the underlying HTTP connection. @type http_headers: L{dict} @ivar strict: Whether to use strict AMF en/decoding or not. @type strict: C{bool} cCsz||_||_g|_d|_||_||_||_||_ t i |_ h|_ ||_|i|dS(Ni(sloggersselfsurls original_urlsrequestssrequest_numbers user_agentsreferers amf_versions client_typesremotingsHeaderCollectionsheaderss http_headerssstricts_setUrl(sselfsurls amf_versions client_typesreferers user_agentsstrictslogger((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys__init__s          cCs.ti||_tiddgt|id|_t}t}t |ido'|iitj o|ii}qnhd|idjo|id}t}n=|idi d}|d|df\}}t |}|tjo't |ido|ii}qn|iddjo3|tjo t i}nt i|||_nT|idd jo3|tjo t i}nt i|||_n td d |id|||idf}|ioF|iid ||iid |i|iid|indS(so @param url: Gateway URL. @type url: C{str} @raise ValueError: Unknown scheme. sisports:iishostnameshttpshttpssUnknown schemes %s://%s:%s%ssConnecting to %ss Referer: %ssUser-Agent: %sN(surlparsesurlsselfs urlunparseslists _root_urlsNonesportshostnameshasattrssplitsspsintshttplibs HTTP_PORTsHTTPConnections connections HTTPS_PORTsHTTPSConnections ValueErrorslocationsloggersinfosdebugsreferers user_agent(sselfsurlsspshostnameslocationsport((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys_setUrls>)         $ cCs$||i|<|ii||dS(s Sets a persistent header to send with each request. @param name: Header name. @type name: C{str} @param must_understand: Default is C{False}. @type must_understand: C{bool} N(svaluesselfsheaderssnames set_requiredsmust_understand(sselfsnamesvaluesmust_understand((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys addHeaders cCs||i|build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys addHTTPHeaderscCs|i|=dS(s) Deletes an HTTP header. N(sselfs http_headerssname(sselfsname((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pysremoveHTTPHeader%scCs5t|t otdnt|||SdS(sT Returns a L{ServiceProxy} for the supplied name. Sets up an object that can have method calls made to it that build the AMF requests. @param auto_execute: Default is C{True}. @type auto_execute: C{bool} @raise TypeError: C{string} type required for C{name}. @rtype: L{ServiceProxy} sstring type requiredN(s isinstancesnames basestrings TypeErrors ServiceProxysselfs auto_execute(sselfsnames auto_execute((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys getService+s cCs@x)|iD]}|i|jo|Sq q Wtd|dS(sa Gets a request based on the id. @raise LookupError: Request not found. sRequest %s not foundN(sselfsrequestssrequestsidsid_s LookupError(sselfsid_srequest((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys getRequest:s   cGsnt|d|i||}|id7_|ii||io!|ii d|i|fn|SdS(sD Adds a request to be sent to the remoting gateway. s/%disAdding request %s%rN( sRequestWrappersselfsrequest_numbersservicesargsswrappersrequestssappendsloggersdebug(sselfsservicesargsswrapper((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys addRequestFs  !cGst|toS|io+|iid|i|ii|n|i|ii|=dSnx|iD]y}|i|jo |i |joS|io+|iid|i|ii|n|i|ii|=dSqmqmWt ddS(sr Removes a request from the pending request list. @raise LookupError: Request not found. sRemoving request: %sNsRequest not found( s isinstancesservicesRequestWrappersselfsloggersdebugsrequestssindexsrequestsargss LookupError(sselfsservicesargssrequest((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys removeRequestUs +   + cCsti|i|i}|io2|iid|i|iid|inxE|D]=}|i }t |i }ti t||||i} from a supplied list of requests. @param requests: List of requests @type requests: C{list} @rtype: L{Envelope} sAMF version: %ssClient type: %sN(sremotingsEnvelopesselfs amf_versions client_typesenvelopesloggersdebugsrequestssrequestsserviceslistsargssRequestsstrsidsheaders(sselfsrequestssservicesenvelopesargssrequest((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys getAMFRequestns  # cCs]|ii}|ihdti<d|i<|it j o|i|dbuild/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys_get_execute_headerss %cCs|io|iid|nti|i|gd|i}|io|iid|i n|i id|i |i |i |i }|i|||iSdS(s Builds, sends and handles the response to a single request, returning the response. @param request: @type request: @rtype: sExecuting single request: %ssstrictsSending POST request to %ssPOSTN(sselfsloggersdebugsrequestsremotingsencodes getAMFRequestsstrictsbodys _root_urls connectionsgetvalues_get_execute_headerss _getResponsesenvelopes removeRequestsid(sselfsrequestsbodysenvelope((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pysexecute_singles $     cCsti|i|id|i}|io|iid|i n|i i d|i |i |i |i}xE|D]=}|i|d}|d}|i||i|qWdS(sm Builds, sends and handles the responses to all requests listed in C{self.requests}. sstrictsSending POST request to %ssPOSTiiN(sremotingsencodesselfs getAMFRequestsrequestssstrictsbodysloggersdebugs _root_urls connectionsrequestsgetvalues_get_execute_headerss _getResponsesenvelopesresponses getRequests setResponses removeRequest(sselfsbodysenvelopesrequestsresponse((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pysexecutes$      c Cs'|io|iidn|ii}|io8|iid|i|iid|idn|itjo|io|iid|i nt t do*t i d|it i|ifnt i d|ifn|id}|t ijo?|io|iid |i nt i d |n|id }d }|io5|iid ||iid|idn|td fjo|i }n|i t|}|io|iidt|nt i|d|i}|io|iid|nt i|ijo-|i|it i7_|i|in;t i|ijo'|it i|_|i|int i|ijo>|it i}x+|i D]\}}||i|build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys _getResponsesX  ! *  !    cCs2|idtdt|dt|tdS(sS Sets authentication credentials for accessing the remote gateway. s CredentialssuseridspasswordN(sselfs addHeadersdictsunicodesusernamespasswordsTrue(sselfsusernamespassword((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pyssetCredentialss(s__name__s __module__s__doc__spyamfsAMF0sDEFAULT_CLIENT_TYPEsNonesDEFAULT_USER_AGENTsFalses__init__s_setUrls addHeaders addHTTPHeadersremoveHTTPHeadersTrues getServices getRequests addRequests removeRequests getAMFRequests_get_execute_headerssexecute_singlesexecutes _getResponsessetCredentials(((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pysRemotingServices  1         J(s__doc__shttplibsurlparsespyamfsremotings ClientTypessFlash6sDEFAULT_CLIENT_TYPEsjoinsmaps __version__sDEFAULT_USER_AGENTsHTTP_OKs convert_argssobjectsServiceMethodProxys ServiceProxysRequestWrappersRemotingService( shttplibsremotingspyamfsurlparses convert_argssRequestWrappersServiceMethodProxysDEFAULT_CLIENT_TYPEsHTTP_OKsRemotingServices ServiceProxysDEFAULT_USER_AGENT((s>build/bdist.linux-x86_64/egg/pyamf/remoting/client/__init__.pys?s      $72PKm; pyamf/util/imports.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Tools for doing dynamic imports. @since: 0.3 """ import sys __all__ = ['when_imported'] #: A list of callables to be executed when the module is imported. post_load_hooks = {} #: List of modules that have already been loaded. loaded_modules = [] class ModuleFinder(object): """ This is a special module finder object that executes a collection of callables when a specific module has been imported. An instance of this is placed in C{sys.meta_path}, which is consulted before C{sys.modules} - allowing us to provide this functionality. @see: L{when_imported} @since: 0.5 """ def find_module(self, name, path): """ Called when an import is made. If there are hooks waiting for this module to be imported then we stop the normal import process and manually load the module. @param name: The name of the module being imported. @param path The root path of the module (if a package). We ignore this. @return: If we want to hook this module, we return a C{loader} interface (which is this instance again). If not we return C{None} to allow the standard import process to continue. """ if name in loaded_modules or name not in post_load_hooks: return None return self def load_module(self, name): """ If we get this far, then there are hooks waiting to be called on import of this module. We manually load the module and then run the hooks. @param name: The name of the module to import. """ loaded_modules.append(name) parent, child = split_module(name) __import__(name, {}, {}, []) mod = sys.modules[name] run_hooks(name, mod) return mod def run_hooks(name, module): """ Run all hooks for a module. Load an unactivated "lazy" module object. """ try: for hook in post_load_hooks[name]: hook(module) finally: del post_load_hooks[name] def split_module(name): """ Splits a module name into its parent and child parts. >>> split_module('foo.bar.baz') 'foo.bar', 'baz' >>> split_module('foo') None, 'foo' """ try: splitpos = name.rindex('.') + 1 return name[:splitpos - 1], name[splitpos:] except ValueError: return None, name def when_imported(name, hook): """ Call C{hook(module)} when module named C{name} is first used. 'hook' must accept one argument: the module object named by 'name', which must be a fully qualified (i.e. absolute) module name. The hook should not raise any exceptions, or it will prevent later hooks from running. If the module has already been imported normally, 'hook(module)' is called immediately, and the module object is returned from this function. If the module has not been imported, then the hook is called when the module is first imported. """ if name in loaded_modules or name in sys.modules: hook(sys.modules[name]) return if name not in post_load_hooks: post_load_hooks[name] = [] post_load_hooks[name].append(hook) # this is required for reloading this module for obj in sys.meta_path: if obj.__class__ is ModuleFinder: break else: sys.meta_path.insert(0, ModuleFinder()) PK֮+; o{o{pyamf/util/__init__.py# -*- coding: utf-8 -*- # # Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ AMF Utilities. @since: 0.1.0 """ import struct import calendar import datetime import types import inspect import pyamf try: from cStringIO import StringIO except ImportError: from StringIO import StringIO try: set except NameError: from sets import Set as set #: XML types. xml_types = None ET = None #: On some Python versions retrieving a negative timestamp, like #: C{datetime.datetime.utcfromtimestamp(-31536000.0)} is broken. negative_timestamp_broken = False int_types = [int] str_types = [str] # py3k support try: int_types.append(long) except NameError: pass try: str_types.append(unicode) except NameError: pass #: Numeric types. int_types = tuple(int_types) #: String types. str_types = tuple(str_types) PosInf = 1e300000 NegInf = -1e300000 # we do this instead of float('nan') because windows throws a wobbler. NaN = PosInf / PosInf def find_xml_lib(): """ Run through a predefined order looking through the various C{ElementTree} implementations so that any type can be encoded but PyAMF will return elements as the first implementation found. We work through the C implementations first - then the pure Python versions. The downside to this is that a possible of three libraries will be loaded into memory that are not used but the libs are small (relatively) and the flexibility that this gives seems to outweigh the cost. Time will tell. @since: 0.4 """ global xml_types, ET xml_types = [] try: import xml.etree.cElementTree as cET ET = cET xml_types.append(type(cET.Element('foo'))) except ImportError: pass try: import cElementTree as cET if ET is None: ET = cET xml_types.append(type(cET.Element('foo'))) except ImportError: pass try: import xml.etree.ElementTree as pET if ET is None: ET = pET xml_types.append(pET._ElementInterface) except ImportError: pass try: import elementtree.ElementTree as pET if ET is None: ET = pET xml_types.append(pET._ElementInterface) except ImportError: pass for x in xml_types[:]: # hack for jython if x.__name__ == 'instance': xml_types.remove(x) xml_types = tuple(xml_types) return xml_types class StringIOProxy(object): """ I am a C{StringIO} type object containing byte data from the AMF stream. @see: U{ByteArray on OSFlash (external) } @see: U{Parsing ByteArrays on OSFlash (external) } """ _wrapped_class = StringIO def __init__(self, buf=None): """ @raise TypeError: Unable to coerce C{buf} to C{StringIO}. """ self._buffer = StringIOProxy._wrapped_class() if isinstance(buf, (str, unicode)): self._buffer.write(buf) elif hasattr(buf, 'getvalue'): self._buffer.write(buf.getvalue()) elif hasattr(buf, 'read') and hasattr(buf, 'seek') and hasattr(buf, 'tell'): old_pos = buf.tell() buf.seek(0) self._buffer.write(buf.read()) buf.seek(old_pos) elif buf is None: pass else: raise TypeError("Unable to coerce buf->StringIO") self._get_len() self._len_changed = False self._buffer.seek(0, 0) def getvalue(self): """ Get raw data from buffer. """ return self._buffer.getvalue() def read(self, n=-1): """ Reads C{n} bytes from the stream. """ bytes = self._buffer.read(n) return bytes def seek(self, pos, mode=0): """ Sets the file-pointer offset, measured from the beginning of this stream, at which the next write operation will occur. @param pos: @type pos: C{int} @param mode: @type mode: C{int} """ return self._buffer.seek(pos, mode) def tell(self): """ Returns the position of the stream pointer. """ return self._buffer.tell() def truncate(self, size=0): """ Truncates the stream to the specified length. @param size: The length of the stream, in bytes. @type size: C{int} """ if size == 0: self._buffer = StringIOProxy._wrapped_class() self._len_changed = True return cur_pos = self.tell() self.seek(0) buf = self.read(size) self._buffer = StringIOProxy._wrapped_class() self._buffer.write(buf) self.seek(cur_pos) self._len_changed = True def write(self, s): """ Writes the content of the specified C{s} into this buffer. @param s: @type s: """ self._buffer.write(s) self._len_changed = True def _get_len(self): """ Return total number of bytes in buffer. """ if hasattr(self._buffer, 'len'): self._len = self._buffer.len return old_pos = self._buffer.tell() self._buffer.seek(0, 2) self._len = self._buffer.tell() self._buffer.seek(old_pos) def __len__(self): if not self._len_changed: return self._len self._get_len() self._len_changed = False return self._len def consume(self): """ Chops the tail off the stream starting at 0 and ending at C{tell()}. The stream pointer is set to 0 at the end of this function. @since: 0.4 """ try: bytes = self.read() except IOError: bytes = '' self.truncate() if len(bytes) > 0: self.write(bytes) self.seek(0) class DataTypeMixIn(object): """ Provides methods for reading and writing basic data types for file-like objects. @ivar endian: Byte ordering used to represent the data. Default byte order is L{ENDIAN_NETWORK}. @type endian: C{str} """ #: Network byte order ENDIAN_NETWORK = "!" #: Native byte order ENDIAN_NATIVE = "@" #: Little endian ENDIAN_LITTLE = "<" #: Big endian ENDIAN_BIG = ">" endian = ENDIAN_NETWORK def _read(self, length): """ Reads C{length} bytes from the stream. If an attempt to read past the end of the buffer is made, L{IOError} is raised. """ bytes = self.read(length) if len(bytes) != length: self.seek(0 - len(bytes), 1) raise IOError("Tried to read %d byte(s) from the stream" % length) return bytes def _is_big_endian(self): """ Whether this system is big endian or not. @rtype: C{bool} """ if self.endian == DataTypeMixIn.ENDIAN_NATIVE: return DataTypeMixIn._system_endian == DataTypeMixIn.ENDIAN_BIG return self.endian in (DataTypeMixIn.ENDIAN_BIG, DataTypeMixIn.ENDIAN_NETWORK) def read_uchar(self): """ Reads an C{unsigned char} from the stream. """ return struct.unpack("B", self._read(1))[0] def write_uchar(self, c): """ Writes an C{unsigned char} to the stream. @param c: Unsigned char @type c: C{int} @raise TypeError: Unexpected type for int C{c}. @raise OverflowError: Not in range. """ if type(c) not in int_types: raise TypeError('expected an int (got:%r)' % (type(c),)) if not 0 <= c <= 255: raise OverflowError("Not in range, %d" % c) self.write(struct.pack("B", c)) def read_char(self): """ Reads a C{char} from the stream. """ return struct.unpack("b", self._read(1))[0] def write_char(self, c): """ Write a C{char} to the stream. @param c: char @type c: C{int} @raise TypeError: Unexpected type for int C{c}. @raise OverflowError: Not in range. """ if type(c) not in int_types: raise TypeError('expected an int (got:%r)' % (type(c),)) if not -128 <= c <= 127: raise OverflowError("Not in range, %d" % c) self.write(struct.pack("b", c)) def read_ushort(self): """ Reads a 2 byte unsigned integer from the stream. """ return struct.unpack("%sH" % self.endian, self._read(2))[0] def write_ushort(self, s): """ Writes a 2 byte unsigned integer to the stream. @param s: 2 byte unsigned integer @type s: C{int} @raise TypeError: Unexpected type for int C{s}. @raise OverflowError: Not in range. """ if type(s) not in int_types: raise TypeError('expected an int (got:%r)' % (type(s),)) if not 0 <= s <= 65535: raise OverflowError("Not in range, %d" % s) self.write(struct.pack("%sH" % self.endian, s)) def read_short(self): """ Reads a 2 byte integer from the stream. """ return struct.unpack("%sh" % self.endian, self._read(2))[0] def write_short(self, s): """ Writes a 2 byte integer to the stream. @param s: 2 byte integer @type s: C{int} @raise TypeError: Unexpected type for int C{s}. @raise OverflowError: Not in range. """ if type(s) not in int_types: raise TypeError('expected an int (got:%r)' % (type(s),)) if not -32768 <= s <= 32767: raise OverflowError("Not in range, %d" % s) self.write(struct.pack("%sh" % self.endian, s)) def read_ulong(self): """ Reads a 4 byte unsigned integer from the stream. """ return struct.unpack("%sL" % self.endian, self._read(4))[0] def write_ulong(self, l): """ Writes a 4 byte unsigned integer to the stream. @param l: 4 byte unsigned integer @type l: C{int} @raise TypeError: Unexpected type for int C{l}. @raise OverflowError: Not in range. """ if type(l) not in int_types: raise TypeError('expected an int (got:%r)' % (type(l),)) if not 0 <= l <= 4294967295: raise OverflowError("Not in range, %d" % l) self.write(struct.pack("%sL" % self.endian, l)) def read_long(self): """ Reads a 4 byte integer from the stream. """ return struct.unpack("%sl" % self.endian, self._read(4))[0] def write_long(self, l): """ Writes a 4 byte integer to the stream. @param l: 4 byte integer @type l: C{int} @raise TypeError: Unexpected type for int C{l}. @raise OverflowError: Not in range. """ if type(l) not in int_types: raise TypeError('expected an int (got:%r)' % (type(l),)) if not -2147483648 <= l <= 2147483647: raise OverflowError("Not in range, %d" % l) self.write(struct.pack("%sl" % self.endian, l)) def read_24bit_uint(self): """ Reads a 24 bit unsigned integer from the stream. @since: 0.4 """ order = None if not self._is_big_endian(): order = [0, 8, 16] else: order = [16, 8, 0] n = 0 for x in order: n += (self.read_uchar() << x) return n def write_24bit_uint(self, n): """ Writes a 24 bit unsigned integer to the stream. @since: 0.4 @param n: 24 bit unsigned integer @type n: C{int} @raise TypeError: Unexpected type for int C{n}. @raise OverflowError: Not in range. """ if type(n) not in int_types: raise TypeError('expected an int (got:%r)' % (type(n),)) if not 0 <= n <= 0xffffff: raise OverflowError("n is out of range") order = None if not self._is_big_endian(): order = [0, 8, 16] else: order = [16, 8, 0] for x in order: self.write_uchar((n >> x) & 0xff) def read_24bit_int(self): """ Reads a 24 bit integer from the stream. @since: 0.4 """ n = self.read_24bit_uint() if n & 0x800000 != 0: # the int is signed n -= 0x1000000 return n def write_24bit_int(self, n): """ Writes a 24 bit integer to the stream. @since: 0.4 @param n: 24 bit integer @type n: C{int} @raise TypeError: Unexpected type for int C{n}. @raise OverflowError: Not in range. """ if type(n) not in int_types: raise TypeError('expected an int (got:%r)' % (type(n),)) if not -8388608 <= n <= 8388607: raise OverflowError("n is out of range") order = None if not self._is_big_endian(): order = [0, 8, 16] else: order = [16, 8, 0] if n < 0: n += 0x1000000 for x in order: self.write_uchar((n >> x) & 0xff) def read_double(self): """ Reads an 8 byte float from the stream. """ return struct.unpack("%sd" % self.endian, self._read(8))[0] def write_double(self, d): """ Writes an 8 byte float to the stream. @param d: 8 byte float @type d: C{float} @raise TypeError: Unexpected type for float C{d}. """ if not type(d) is float: raise TypeError('expected a float (got:%r)' % (type(d),)) self.write(struct.pack("%sd" % self.endian, d)) def read_float(self): """ Reads a 4 byte float from the stream. """ return struct.unpack("%sf" % self.endian, self._read(4))[0] def write_float(self, f): """ Writes a 4 byte float to the stream. @param f: 4 byte float @type f: C{float} @raise TypeError: Unexpected type for float C{f}. """ if type(f) is not float: raise TypeError('expected a float (got:%r)' % (type(f),)) self.write(struct.pack("%sf" % self.endian, f)) def read_utf8_string(self, length): """ Reads a UTF-8 string from the stream. @rtype: C{unicode} """ str = struct.unpack("%s%ds" % (self.endian, length), self.read(length))[0] return unicode(str, "utf8") def write_utf8_string(self, u): """ Writes a unicode object to the stream in UTF-8. @param u: unicode object @raise TypeError: Unexpected type for str C{u}. """ if type(u) not in str_types: raise TypeError('expected a str (got:%r)' % (type(u),)) bytes = u.encode("utf8") self.write(struct.pack("%s%ds" % (self.endian, len(bytes)), bytes)) if struct.pack('@H', 1)[0] == '\x01': DataTypeMixIn._system_endian = DataTypeMixIn.ENDIAN_LITTLE else: DataTypeMixIn._system_endian = DataTypeMixIn.ENDIAN_BIG class BufferedByteStream(StringIOProxy, DataTypeMixIn): """ An extension of C{StringIO}. Features: - Raises L{IOError} if reading past end. - Allows you to C{peek()} at the next byte. @see: L{cBufferedByteStream} """ def __init__(self, buf=None): """ @param buf: Initial byte stream. @type buf: C{str} or C{StringIO} instance """ StringIOProxy.__init__(self, buf=buf) self.seek(0) def read(self, length=-1): """ Reads up to the specified number of bytes from the stream into the specified byte array of specified length. @raise IOError: Attempted to read past the end of the buffer. """ if length == -1 and self.at_eof(): raise IOError('Attempted to read from the buffer but already at ' 'the end') elif length > 0 and self.tell() + length > len(self): raise IOError('Attempted to read %d bytes from the buffer but ' 'only %d remain' % (length, len(self) - self.tell())) return StringIOProxy.read(self, length) def peek(self, size=1): """ Looks C{size} bytes ahead in the stream, returning what it finds, returning the stream pointer to its initial position. @param size: Default is 1. @type size: C{int} @raise ValueError: Trying to peek backwards. @rtype: @return: Bytes. """ if size == -1: return self.peek(len(self) - self.tell()) if size < -1: raise ValueError("Cannot peek backwards") bytes = '' pos = self.tell() while not self.at_eof() and len(bytes) != size: bytes += self.read(1) self.seek(pos) return bytes def remaining(self): """ Returns number of remaining bytes. @rtype: C{number} @return: Number of remaining bytes. """ return len(self) - self.tell() def at_eof(self): """ Returns C{True} if the internal pointer is at the end of the stream. @rtype: C{bool} """ return self.tell() == len(self) def append(self, data): """ Append data to the end of the stream. The pointer will not move if this operation is successful. @param data: The data to append to the stream. @type data: C{str} or C{unicode} @raise TypeError: data is not C{str} or C{unicode} """ t = self.tell() # seek to the end of the stream self.seek(0, 2) if hasattr(data, 'getvalue'): self.write_utf8_string(data.getvalue()) else: self.write_utf8_string(data) self.seek(t) def __add__(self, other): old_pos = self.tell() old_other_pos = other.tell() new = BufferedByteStream(self) other.seek(0) new.seek(0, 2) new.write(other.read()) self.seek(old_pos) other.seek(old_other_pos) new.seek(0) return new def hexdump(data): """ Get hexadecimal representation of C{StringIO} data. @type data: @param data: @rtype: C{str} @return: Hexadecimal string. """ import string hex = ascii = buf = "" index = 0 for c in data: hex += "%02x " % ord(c) if c in string.printable and c not in string.whitespace: ascii += c else: ascii += "." if len(ascii) == 16: buf += "%04x: %s %s %s\n" % (index, hex[:24], hex[24:], ascii) hex = ascii = "" index += 16 if len(ascii): buf += "%04x: %-24s %-24s %s\n" % (index, hex[:24], hex[24:], ascii) return buf def get_timestamp(d): """ Returns a UTC timestamp for a C{datetime.datetime} object. @type d: C{datetime.datetime} @param d: The date object. @return: UTC timestamp. @rtype: C{str} @note: Inspiration taken from the U{Intertwingly blog }. """ if isinstance(d, datetime.date) and not isinstance(d, datetime.datetime): d = datetime.datetime.combine(d, datetime.time(0, 0, 0, 0)) msec = str(d.microsecond).rjust(6).replace(' ', '0') return float('%s.%s' % (calendar.timegm(d.utctimetuple()), msec)) def get_datetime(secs): """ Return a UTC date from a timestamp. @type secs: C{long} @param secs: Seconds since 1970. @return: UTC timestamp. @rtype: C{datetime.datetime} """ if secs < 0 and negative_timestamp_broken: return datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=secs) return datetime.datetime.utcfromtimestamp(secs) def get_properties(obj): """ @since: 0.5 """ if hasattr(obj, 'keys'): return set(obj.keys()) elif hasattr(obj, '__dict__'): return obj.__dict__.keys() return [] def get_attrs(obj): """ Gets a C{dict} of the attrs of an object in a predefined resolution order. @raise AttributeError: A duplicate attribute was already found in this collection, are you mixing different key types? """ if hasattr(obj, 'iteritems'): attrs = {} for k, v in obj.iteritems(): sk = str(k) if sk in attrs.keys(): raise AttributeError('A duplicate attribute (%s) was ' 'already found in this collection, are you mixing ' 'different key types?' % (sk,)) attrs[sk] = v return attrs elif hasattr(obj, '__dict__'): return obj.__dict__.copy() elif hasattr(obj, '__slots__'): attrs = {} for k in obj.__slots__: attrs[k] = getattr(obj, k) return attrs return None def set_attrs(obj, attrs): """ A generic function which applies a collection of attributes C{attrs} to object C{obj}. @param obj: An instance implementing the C{__setattr__} function @param attrs: A collection implementing the C{iteritems} function @type attrs: Usually a dict """ if isinstance(obj, (list, dict)): for k, v in attrs.iteritems(): obj[k] = v return for k, v in attrs.iteritems(): setattr(obj, k, v) def get_class_alias(klass): """ Returns a alias class suitable for klass. Defaults to L{pyamf.ClassAlias} """ for k, v in pyamf.ALIAS_TYPES.iteritems(): for kl in v: if isinstance(kl, types.FunctionType): if kl(klass) is True: return k elif isinstance(kl, (type, (types.ClassType, types.ObjectType))): if issubclass(klass, kl): return k return pyamf.ClassAlias def is_class_sealed(klass): """ Returns a C{boolean} whether or not the supplied class can accept dynamic properties. @rtype: C{bool} @since: 0.5 """ mro = inspect.getmro(klass) new = False if mro[-1] is object: mro = mro[:-1] new = True for kls in mro: if new and '__dict__' in kls.__dict__: return False if not hasattr(kls, '__slots__'): return False return True def get_class_meta(klass): """ Returns a C{dict} containing meta data based on the supplied class, useful for class aliasing. @rtype: C{dict} @since: 0.5 """ if not isinstance(klass, (type, types.ClassType)) or klass is object: raise TypeError('klass must be a class object, got %r' % type(klass)) meta = { 'static_attrs': None, 'exclude_attrs': None, 'readonly_attrs': None, 'amf3': None, 'dynamic': None, 'alias': None, 'external': None } if not hasattr(klass, '__amf__'): return meta a = klass.__amf__ if type(a) is dict: in_func = lambda x: x in a get_func = a.__getitem__ else: in_func = lambda x: hasattr(a, x) get_func = lambda x: getattr(a, x) for prop in ['alias', 'amf3', 'dynamic', 'external']: if in_func(prop): meta[prop] = get_func(prop) for prop in ['static', 'exclude', 'readonly']: if in_func(prop): meta[prop + '_attrs'] = list(get_func(prop)) return meta class IndexedCollection(object): """ A class that provides a quick and clean way to store references and referenced objects. @note: All attributes on the instance are private. @ivar exceptions: If C{True} then L{ReferenceError} will be raised, otherwise C{None} will be returned. """ def __init__(self, use_hash=False, exceptions=True): if use_hash is True: self.func = hash else: self.func = id self.exceptions = exceptions self.clear() def clear(self): """ Clears the index. """ self.list = [] self.dict = {} def getByReference(self, ref): """ Returns an object based on the reference. @raise TypeError: Bad reference type. @raise pyamf.ReferenceError: Reference not found. """ if not isinstance(ref, (int, long)): raise TypeError("Bad reference type") try: return self.list[ref] except IndexError: if self.exceptions is False: return None raise pyamf.ReferenceError("Reference %r not found" % (ref,)) def getReferenceTo(self, obj): """ Returns a reference to C{obj} if it is contained within this index. @raise pyamf.ReferenceError: Value not found. """ try: return self.dict[self.func(obj)] except KeyError: if self.exceptions is False: return None raise pyamf.ReferenceError("Value %r not found" % (obj,)) def append(self, obj): """ Appends C{obj} to this index. @note: Uniqueness is not checked @return: The reference to C{obj} in this index. """ h = self.func(obj) self.list.append(obj) idx = len(self.list) - 1 self.dict[h] = idx return idx def __eq__(self, other): if isinstance(other, list): return self.list == other elif isinstance(other, dict): return self.dict == other return False def __len__(self): return len(self.list) def __getitem__(self, idx): return self.getByReference(idx) def __contains__(self, obj): try: r = self.getReferenceTo(obj) except pyamf.ReferenceError: r = None return r is not None def __repr__(self): return '<%s list=%r dict=%r>' % (self.__class__.__name__, self.list, self.dict) def __iter__(self): return iter(self.list) class IndexedMap(IndexedCollection): """ Like L{IndexedCollection}, but also maps to another object. @since: 0.4 """ def __init__(self, use_hash=False, exceptions=True): IndexedCollection.__init__(self, use_hash, exceptions) def clear(self): """ Clears the index and mapping. """ IndexedCollection.clear(self) self.mapped = [] def getMappedByReference(self, ref): """ Returns the mapped object by reference. @raise TypeError: Bad reference type. @raise pyamf.ReferenceError: Reference not found. """ if not isinstance(ref, (int, long)): raise TypeError("Bad reference type.") try: return self.mapped[ref] except IndexError: if self.exceptions is False: return None raise pyamf.ReferenceError("Reference %r not found" % ref) def append(self, obj): """ Appends C{obj} to this index. @return: The reference to C{obj} in this index. """ idx = IndexedCollection.append(self, obj) diff = (idx + 1) - len(self.mapped) for i in range(0, diff): self.mapped.append(None) return idx def map(self, obj, mapped_obj): """ Maps an object. """ idx = self.append(obj) self.mapped[idx] = mapped_obj return idx def is_ET_element(obj): """ Determines if the supplied C{obj} param is a valid ElementTree element. """ return isinstance(obj, xml_types) def is_float_broken(): """ Older versions of Python (<=2.5) and the Windows platform are renowned for mixing up 'special' floats. This function determines whether this is the case. @since: 0.4 @rtype: C{bool} """ global NaN return str(NaN) != str(struct.unpack("!d", '\xff\xf8\x00\x00\x00\x00\x00\x00')[0]) def isNaN(val): """ @since: 0.5 """ return str(float(val)) == str(NaN) def isPosInf(val): """ @since: 0.5 """ return str(float(val)) == str(PosInf) def isNegInf(val): """ @since: 0.5 """ return str(float(val)) == str(NegInf) # init the module from here .. find_xml_lib() try: datetime.datetime.utcfromtimestamp(-31536000.0) except ValueError: negative_timestamp_broken = True if is_float_broken(): def read_double_workaround(self): global PosInf, NegInf, NaN """ Override the L{DataTypeMixIn.read_double} method to fix problems with doubles by using the third-party C{fpconst} library. """ bytes = self.read(8) if self._is_big_endian(): if bytes == '\xff\xf8\x00\x00\x00\x00\x00\x00': return NaN if bytes == '\xff\xf0\x00\x00\x00\x00\x00\x00': return NegInf if bytes == '\x7f\xf0\x00\x00\x00\x00\x00\x00': return PosInf else: if bytes == '\x00\x00\x00\x00\x00\x00\xf8\xff': return NaN if bytes == '\x00\x00\x00\x00\x00\x00\xf0\xff': return NegInf if bytes == '\x00\x00\x00\x00\x00\x00\xf0\x7f': return PosInf return struct.unpack("%sd" % self.endian, bytes)[0] DataTypeMixIn.read_double = read_double_workaround def write_double_workaround(self, d): """ Override the L{DataTypeMixIn.write_double} method to fix problems with doubles by using the third-party C{fpconst} library. """ if type(d) is not float: raise TypeError('expected a float (got:%r)' % (type(d),)) if isNaN(d): if self._is_big_endian(): self.write('\xff\xf8\x00\x00\x00\x00\x00\x00') else: self.write('\x00\x00\x00\x00\x00\x00\xf8\xff') elif isNegInf(d): if self._is_big_endian(): self.write('\xff\xf0\x00\x00\x00\x00\x00\x00') else: self.write('\x00\x00\x00\x00\x00\x00\xf0\xff') elif isPosInf(d): if self._is_big_endian(): self.write('\x7f\xf0\x00\x00\x00\x00\x00\x00') else: self.write('\x00\x00\x00\x00\x00\x00\xf0\x7f') else: write_double_workaround.old_func(self, d) x = DataTypeMixIn.write_double DataTypeMixIn.write_double = write_double_workaround write_double_workaround.old_func = x try: from cpyamf.util import BufferedByteStream, IndexedCollection, IndexedMap class StringIOProxy(BufferedByteStream): _wrapped_class = None def __init__(self, *args, **kwargs): BufferedByteStream.__init__(self, *args, **kwargs) self._buffer = self class DataTypeMixIn(BufferedByteStream): #: Network byte order ENDIAN_NETWORK = "!" #: Native byte order ENDIAN_NATIVE = "@" #: Little endian ENDIAN_LITTLE = "<" #: Big endian ENDIAN_BIG = ">" except ImportError: pass PK:u3;QYpyamf/util/imports.pyc; -xJc@sdZdkZdgZhZgZdefdYZdZdZdZ x<ei D]Z e i ejoPq_q_Wei i dedS( s/ Tools for doing dynamic imports. @since: 0.3 Ns when_importeds ModuleFindercBs tZdZdZdZRS(sC This is a special module finder object that executes a collection of callables when a specific module has been imported. An instance of this is placed in C{sys.meta_path}, which is consulted before C{sys.modules} - allowing us to provide this functionality. @see: L{when_imported} @since: 0.5 cCs*|tjp |tjotSn|SdS(s  Called when an import is made. If there are hooks waiting for this module to be imported then we stop the normal import process and manually load the module. @param name: The name of the module being imported. @param path The root path of the module (if a package). We ignore this. @return: If we want to hook this module, we return a C{loader} interface (which is this instance again). If not we return C{None} to allow the standard import process to continue. N(snamesloaded_modulesspost_load_hookssNonesself(sselfsnamespath((s2build/bdist.linux-x86_64/egg/pyamf/util/imports.pys find_module s cCsTti|t|\}}t|hhgti|}t |||SdS(s If we get this far, then there are hooks waiting to be called on import of this module. We manually load the module and then run the hooks. @param name: The name of the module to import. N( sloaded_modulessappendsnames split_modulesparentschilds __import__ssyssmodulessmods run_hooks(sselfsnamesparentschildsmod((s2build/bdist.linux-x86_64/egg/pyamf/util/imports.pys load_module1s   (s__name__s __module__s__doc__s find_modules load_module(((s2build/bdist.linux-x86_64/egg/pyamf/util/imports.pys ModuleFinders  cCs2z#xt|D]}||qWWdt|=XdS(sS Run all hooks for a module. Load an unactivated "lazy" module object. N(spost_load_hookssnameshooksmodule(snamesmoduleshook((s2build/bdist.linux-x86_64/egg/pyamf/util/imports.pys run_hooksEs cCsQy-|idd}||d ||fSWntj ot|fSnXdS(s Splits a module name into its parent and child parts. >>> split_module('foo.bar.baz') 'foo.bar', 'baz' >>> split_module('foo') None, 'foo' s.iN(snamesrindexssplitposs ValueErrorsNone(snamessplitpos((s2build/bdist.linux-x86_64/egg/pyamf/util/imports.pys split_moduleQs cCsf|tjp |tijo|ti|dSn|tjogt|e<e!_=e>e<_?nyId&k@l&Z&l0Z0l1Z1de&fd'YZ d e&fd(YZ!Wne j onXdS()s AMF Utilities. @since: 0.1.0 N(sStringIO(sSetfinff-infcCsgay5dkii}|atit|idWnt j onXy@dk}tt jo |antit|idWnt j onXy:dk ii }tt jo |anti|iWnt j onXy7dki }tt jo |anti|iWnt j onXx0tD]'}|idjoti|qLqLWttatSdS(s Run through a predefined order looking through the various C{ElementTree} implementations so that any type can be encoded but PyAMF will return elements as the first implementation found. We work through the C implementations first - then the pure Python versions. The downside to this is that a possible of three libraries will be loaded into memory that are not used but the libs are small (relatively) and the flexibility that this gives seems to outweigh the cost. Time will tell. @since: 0.4 Nsfoosinstance(s xml_typessxml.etree.cElementTreesetrees cElementTreescETsETsappendstypesElements ImportErrorsNonesxml.etree.ElementTrees ElementTreespETs_ElementInterfaceselementtree.ElementTreesxs__name__sremovestuple(spETscETsx((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys find_xml_lib?sH            s StringIOProxycBsztZdZeZedZdZddZddZ dZ ddZ d Z d Z d Zd ZRS( s2 I am a C{StringIO} type object containing byte data from the AMF stream. @see: U{ByteArray on OSFlash (external) } @see: U{Parsing ByteArrays on OSFlash (external) } cCsti|_t|ttfo|ii|nt |do|ii|i nt |dot |do t |do@|i }|i d|ii|i|i |n|tjon td|it|_|ii dddS(sK @raise TypeError: Unable to coerce C{buf} to C{StringIO}. sgetvaluesreadsseekstellisUnable to coerce buf->StringION(s StringIOProxys_wrapped_classsselfs_buffers isinstancesbufsstrsunicodeswriteshasattrsgetvaluestellsold_possseeksreadsNones TypeErrors_get_lensFalses _len_changed(sselfsbufsold_pos((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys__init__s"0      cCs|iiSdS(s+ Get raw data from buffer. N(sselfs_buffersgetvalue(sself((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysgetvaluesicCs|ii|}|SdS(s3 Reads C{n} bytes from the stream. N(sselfs_buffersreadsnsbytes(sselfsnsbytes((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysreadsicCs|ii||SdS(s Sets the file-pointer offset, measured from the beginning of this stream, at which the next write operation will occur. @param pos: @type pos: C{int} @param mode: @type mode: C{int} N(sselfs_buffersseekspossmode(sselfspossmode((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysseeks cCs|iiSdS(s= Returns the position of the stream pointer. N(sselfs_bufferstell(sself((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pystellscCs|djo ti|_t|_dSn|i}|i d|i |}ti|_|ii ||i |t|_dS(s Truncates the stream to the specified length. @param size: The length of the stream, in bytes. @type size: C{int} iN( ssizes StringIOProxys_wrapped_classsselfs_buffersTrues _len_changedstellscur_possseeksreadsbufswrite(sselfssizesbufscur_pos((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pystruncates     cCs|ii|t|_dS(sp Writes the content of the specified C{s} into this buffer. @param s: @type s: N(sselfs_bufferswritesssTrues _len_changed(sselfss((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pyswritescCsrt|ido|ii|_dSn|ii}|iidd|ii|_|ii|dS(s9 Return total number of bytes in buffer. slenNii(shasattrsselfs_bufferslens_lenstellsold_possseek(sselfsold_pos((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys_get_lenscCs4|i o |iSn|it|_|iSdS(N(sselfs _len_changeds_lens_get_lensFalse(sself((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys__len__s     cCsky|i}Wntj o d}nX|it|djo|i||idndS(s Chops the tail off the stream starting at 0 and ending at C{tell()}. The stream pointer is set to 0 at the end of this function. @since: 0.4 siN(sselfsreadsbytessIOErrorstruncateslenswritesseek(sselfsbytes((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysconsumes   (s__name__s __module__s__doc__sStringIOs_wrapped_classsNones__init__sgetvaluesreadsseekstellstruncateswrites_get_lens__len__sconsume(((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys StringIOProxys        s DataTypeMixIncBstZdZdZdZdZdZeZdZdZ dZ dZ d Z d Z d Zd Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZRS(s Provides methods for reading and writing basic data types for file-like objects. @ivar endian: Byte ordering used to represent the data. Default byte order is L{ENDIAN_NETWORK}. @type endian: C{str} s!s@scCsX|i|}t||jo.|idt|dtd|n|SdS(s Reads C{length} bytes from the stream. If an attempt to read past the end of the buffer is made, L{IOError} is raised. iis(Tried to read %d byte(s) from the streamN(sselfsreadslengthsbytesslensseeksIOError(sselfslengthsbytes((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys_read%s cCsD|itijotitijSn|ititifjSdS(sT Whether this system is big endian or not. @rtype: C{bool} N(sselfsendians DataTypeMixIns ENDIAN_NATIVEs_system_endians ENDIAN_BIGsENDIAN_NETWORK(sself((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys_is_big_endian3scCs!tid|iddSdS(s< Reads an C{unsigned char} from the stream. sBiiN(sstructsunpacksselfs_read(sself((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys read_uchar>scCst|tjotdt|fnd|jo djn otd|n|itid|dS(s Writes an C{unsigned char} to the stream. @param c: Unsigned char @type c: C{int} @raise TypeError: Unexpected type for int C{c}. @raise OverflowError: Not in range. sexpected an int (got:%r)iisNot in range, %dsBN( stypescs int_typess TypeErrors OverflowErrorsselfswritesstructspack(sselfsc((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys write_ucharDs cCs!tid|iddSdS(s2 Reads a C{char} from the stream. sbiiN(sstructsunpacksselfs_read(sself((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys read_charUscCst|tjotdt|fnd|jo djn otd|n|itid|dS(s Write a C{char} to the stream. @param c: char @type c: C{int} @raise TypeError: Unexpected type for int C{c}. @raise OverflowError: Not in range. sexpected an int (got:%r)iisNot in range, %dsbN( stypescs int_typess TypeErrors OverflowErrorsselfswritesstructspack(sselfsc((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys write_char[s cCs(tid|i|iddSdS(sB Reads a 2 byte unsigned integer from the stream. s%sHiiN(sstructsunpacksselfsendians_read(sself((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys read_ushortlscCst|tjotdt|fnd|jo djn otd|n|itid|i |dS(s Writes a 2 byte unsigned integer to the stream. @param s: 2 byte unsigned integer @type s: C{int} @raise TypeError: Unexpected type for int C{s}. @raise OverflowError: Not in range. sexpected an int (got:%r)iisNot in range, %ds%sHN( stypesss int_typess TypeErrors OverflowErrorsselfswritesstructspacksendian(sselfss((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys write_ushortrs cCs(tid|i|iddSdS(s9 Reads a 2 byte integer from the stream. s%shiiN(sstructsunpacksselfsendians_read(sself((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys read_shortscCst|tjotdt|fnd|jo djn otd|n|itid|i |dS(s Writes a 2 byte integer to the stream. @param s: 2 byte integer @type s: C{int} @raise TypeError: Unexpected type for int C{s}. @raise OverflowError: Not in range. sexpected an int (got:%r)iisNot in range, %ds%shN( stypesss int_typess TypeErrors OverflowErrorsselfswritesstructspacksendian(sselfss((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys write_shorts cCs(tid|i|iddSdS(sB Reads a 4 byte unsigned integer from the stream. s%sLiiN(sstructsunpacksselfsendians_read(sself((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys read_ulongscCst|tjotdt|fnd|jo djn otd|n|itid|i |dS(s Writes a 4 byte unsigned integer to the stream. @param l: 4 byte unsigned integer @type l: C{int} @raise TypeError: Unexpected type for int C{l}. @raise OverflowError: Not in range. sexpected an int (got:%r)iIsNot in range, %ds%sLN( stypesls int_typess TypeErrors OverflowErrorsselfswritesstructspacksendian(sselfsl((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys write_ulongs cCs(tid|i|iddSdS(s9 Reads a 4 byte integer from the stream. s%sliiN(sstructsunpacksselfsendians_read(sself((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys read_longscCst|tjotdt|fnd|jo djn otd|n|itid|i |dS(s Writes a 4 byte integer to the stream. @param l: 4 byte integer @type l: C{int} @raise TypeError: Unexpected type for int C{l}. @raise OverflowError: Not in range. sexpected an int (got:%r)iisNot in range, %ds%slN( stypesls int_typess TypeErrors OverflowErrorsselfswritesstructspacksendian(sselfsl((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys write_longs cCsit}|i odddg}ndddg}d}x"|D]}||i|>7}qCW|SdS(sW Reads a 24 bit unsigned integer from the stream. @since: 0.4 iiiN(sNonesordersselfs_is_big_endiansnsxs read_uchar(sselfsxsordersn((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysread_24bit_uintscCst|tjotdt|fnd|jo djn otdnt}|i odddg}ndddg}x#|D]}|i ||?d@qWdS( s Writes a 24 bit unsigned integer to the stream. @since: 0.4 @param n: 24 bit unsigned integer @type n: C{int} @raise TypeError: Unexpected type for int C{n}. @raise OverflowError: Not in range. sexpected an int (got:%r)iisn is out of rangeiiiN( stypesns int_typess TypeErrors OverflowErrorsNonesordersselfs_is_big_endiansxs write_uchar(sselfsnsxsorder((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pyswrite_24bit_uints cCs3|i}|d@djo|d8}n|SdS(sN Reads a 24 bit integer from the stream. @since: 0.4 iiiN(sselfsread_24bit_uintsn(sselfsn((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysread_24bit_ints  cCst|tjotdt|fnd|jo djn otdnt}|i odddg}ndddg}|djo|d7}nx#|D]}|i ||?d @qWd S( s Writes a 24 bit integer to the stream. @since: 0.4 @param n: 24 bit integer @type n: C{int} @raise TypeError: Unexpected type for int C{n}. @raise OverflowError: Not in range. sexpected an int (got:%r)iisn is out of rangeiiiiiN( stypesns int_typess TypeErrors OverflowErrorsNonesordersselfs_is_big_endiansxs write_uchar(sselfsnsxsorder((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pyswrite_24bit_ints  cCs(tid|i|iddSdS(s8 Reads an 8 byte float from the stream. s%sdiiN(sstructsunpacksselfsendians_read(sself((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys read_double!scCsUt|tj otdt|fn|itid|i|dS(s Writes an 8 byte float to the stream. @param d: 8 byte float @type d: C{float} @raise TypeError: Unexpected type for float C{d}. sexpected a float (got:%r)s%sdN( stypesdsfloats TypeErrorsselfswritesstructspacksendian(sselfsd((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys write_double'scCs(tid|i|iddSdS(s7 Reads a 4 byte float from the stream. s%sfiiN(sstructsunpacksselfsendians_read(sself((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys read_float4scCsTt|tj otdt|fn|itid|i|dS(s Writes a 4 byte float to the stream. @param f: 4 byte float @type f: C{float} @raise TypeError: Unexpected type for float C{f}. sexpected a float (got:%r)s%sfN( stypesfsfloats TypeErrorsselfswritesstructspacksendian(sselfsf((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys write_float:scCs=tid|i|f|i|d}t|dSdS(sS Reads a UTF-8 string from the stream. @rtype: C{unicode} s%s%dsisutf8N(sstructsunpacksselfsendianslengthsreadsstrsunicode(sselfslengthsstr((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysread_utf8_stringGs,cCsot|tjotdt|fn|id}|iti d|i t |f|dS(s Writes a unicode object to the stream in UTF-8. @param u: unicode object @raise TypeError: Unexpected type for str C{u}. sexpected a str (got:%r)sutf8s%s%dsN( stypesus str_typess TypeErrorsencodesbytessselfswritesstructspacksendianslen(sselfsusbytes((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pyswrite_utf8_stringQs ( s__name__s __module__s__doc__sENDIAN_NETWORKs ENDIAN_NATIVEs ENDIAN_LITTLEs ENDIAN_BIGsendians_reads_is_big_endians read_uchars write_uchars read_chars write_chars read_ushorts write_ushorts read_shorts write_shorts read_ulongs write_ulongs read_longs write_longsread_24bit_uintswrite_24bit_uintsread_24bit_intswrite_24bit_ints read_doubles write_doubles read_floats write_floatsread_utf8_stringswrite_utf8_string(((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys DataTypeMixIns<                     s@HiissBufferedByteStreamcBsVtZdZedZddZddZdZdZdZ d Z RS( s An extension of C{StringIO}. Features: - Raises L{IOError} if reading past end. - Allows you to C{peek()} at the next byte. @see: L{cBufferedByteStream} cCs$ti|d||iddS(sd @param buf: Initial byte stream. @type buf: C{str} or C{StringIO} instance sbufiN(s StringIOProxys__init__sselfsbufsseek(sselfsbuf((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys__init__qsicCs|djo |iotdnU|djo|i|t|jo*td|t||ifnti||SdS(s Reads up to the specified number of bytes from the stream into the specified byte array of specified length. @raise IOError: Attempted to read past the end of the buffer. is8Attempted to read from the buffer but already at the endis=Attempted to read %d bytes from the buffer but only %d remainN(slengthsselfsat_eofsIOErrorstellslens StringIOProxysread(sselfslength((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysreadzs **icCs|djo!|it||iSn|djotdnd}|i}x9|i ot||jo||i d7}q`W|i ||SdS(s. Looks C{size} bytes ahead in the stream, returning what it finds, returning the stream pointer to its initial position. @param size: Default is 1. @type size: C{int} @raise ValueError: Trying to peek backwards. @rtype: @return: Bytes. isCannot peek backwardssiN( ssizesselfspeekslenstells ValueErrorsbytesspossat_eofsreadsseek(sselfssizesbytesspos((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pyspeeks  !  ! cCst||iSdS(s{ Returns number of remaining bytes. @rtype: C{number} @return: Number of remaining bytes. N(slensselfstell(sself((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys remainingscCs|it|jSdS(so Returns C{True} if the internal pointer is at the end of the stream. @rtype: C{bool} N(sselfstellslen(sself((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysat_eofscCsa|i}|iddt|do|i|in|i||i|dS(s Append data to the end of the stream. The pointer will not move if this operation is successful. @param data: The data to append to the stream. @type data: C{str} or C{unicode} @raise TypeError: data is not C{str} or C{unicode} iisgetvalueN(sselfstellstsseekshasattrsdataswrite_utf8_stringsgetvalue(sselfsdatast((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysappends  cCs|i}|i}t|}|id|idd|i|i |i||i||id|SdS(Nii( sselfstellsold_possothers old_other_possBufferedByteStreamsnewsseekswritesread(sselfsothers old_other_possnewsold_pos((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys__add__s       ( s__name__s __module__s__doc__sNones__init__sreadspeeks remainingsat_eofsappends__add__(((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysBufferedByteStreamfs     cCsdk}d}}}d}x|D]}|dt|7}||ijo ||i jo||7}n |d7}t |djo:|d||d |d|f7}d}}|d7}q$q$Wt |o&|d ||d |d|f7}n|SdS( s Get hexadecimal representation of C{StringIO} data. @type data: @param data: @rtype: C{str} @return: Hexadecimal string. Nsis%02x s.is%04x: %s %s %s is%04x: %-24s %-24s %s ( sstringshexsasciisbufsindexsdatascsords printables whitespaceslen(sdatasindexscsstringsasciishexsbuf((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pyshexdumps"   "  &cCst|tiot|ti o+tii|tidddd}nt|iidi dd}t dt i |i|fSdS(s3 Returns a UTC timestamp for a C{datetime.datetime} object. @type d: C{datetime.datetime} @param d: The date object. @return: UTC timestamp. @rtype: C{str} @note: Inspiration taken from the U{Intertwingly blog }. iis s0s%s.%sN(s isinstancesdsdatetimesdatescombinestimesstrs microsecondsrjustsreplacesmsecsfloatscalendarstimegms utctimetuple(sdsmsec((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys get_timestamps '+$cCsO|djoto'tidddtid|Sntii|SdS(s Return a UTC date from a timestamp. @type secs: C{long} @param secs: Seconds since 1970. @return: UTC timestamp. @rtype: C{datetime.datetime} iiissecondsN(ssecssnegative_timestamp_brokensdatetimes timedeltasutcfromtimestamp(ssecs((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys get_datetimes'cCsMt|dot|iSn"t|do|iiSngSdS(s @since: 0.5 skeyss__dict__N(shasattrsobjssetskeyss__dict__(sobj((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysget_properties s cCst|dokh}xZ|iD]L\}}t|}||ijot d|fn|||}|o d|i jotSnt |d otSqAqAWtSdS(s Returns a C{boolean} whether or not the supplied class can accept dynamic properties. @rtype: C{bool} @since: 0.5 is__dict__s __slots__N( sinspectsgetmrosklasssmrosFalsesnewsobjectsTruesklss__dict__shasattr(sklasssmrosklssnew((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysis_class_sealedqs   cswt|ttif p |tjotdt|nhdt<dt<dt<dt<dt<dt<dt<}t |d  o|Sn|i tt jod }i}nd }d }x;ddddgD]'}||o||||scs t|S(N(shasattrsasx(sx(sa(s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysscs t|S(N(sgetattrsasx(sx(sa(s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysssstaticsexcludesreadonlys_attrsN(s isinstancesklassstypestypess ClassTypesobjects TypeErrorsNonesmetashasattrs__amf__sasdictsin_funcs __getitem__sget_funcspropslist(sklasssasget_funcspropsmetasin_func((sas3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysget_class_metas*'E        "sIndexedCollectioncBswtZdZeedZdZdZdZdZ dZ dZ dZ d Z d Zd ZRS( s' A class that provides a quick and clean way to store references and referenced objects. @note: All attributes on the instance are private. @ivar exceptions: If C{True} then L{ReferenceError} will be raised, otherwise C{None} will be returned. cCs:|tjo t|_n t|_||_|idS(N(suse_hashsTrueshashsselfsfuncsids exceptionssclear(sselfsuse_hashs exceptions((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys__init__s     cCsg|_h|_dS(s# Clears the index. N(sselfslistsdict(sself((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysclears cCs~t|ttf otdny|i|SWnAtj o5|it jot Snt i d|fnXdS(s Returns an object based on the reference. @raise TypeError: Bad reference type. @raise pyamf.ReferenceError: Reference not found. sBad reference typesReference %r not foundN( s isinstancesrefsintslongs TypeErrorsselfslists IndexErrors exceptionssFalsesNonespyamfsReferenceError(sselfsref((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysgetByReferencescCs`y|i|i|SWnAtj o5|itjotSnti d|fnXdS(s Returns a reference to C{obj} if it is contained within this index. @raise pyamf.ReferenceError: Value not found. sValue %r not foundN( sselfsdictsfuncsobjsKeyErrors exceptionssFalsesNonespyamfsReferenceError(sselfsobj((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysgetReferenceToscCsG|i|}|ii|t|id}||i|<|SdS(s Appends C{obj} to this index. @note: Uniqueness is not checked @return: The reference to C{obj} in this index. iN( sselfsfuncsobjshslistsappendslensidxsdict(sselfsobjshsidx((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysappends  cCsJt|to|i|jSn"t|to|i|jSntSdS(N(s isinstancesotherslistsselfsdictsFalse(sselfsother((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys__eq__s cCst|iSdS(N(slensselfslist(sself((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys__len__scCs|i|SdS(N(sselfsgetByReferencesidx(sselfsidx((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys __getitem__ scCs@y|i|}Wntij o t}nX|tj SdS(N(sselfsgetReferenceTosobjsrspyamfsReferenceErrorsNone(sselfsobjsr((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys __contains__s  cCs!d|ii|i|ifSdS(Ns<%s list=%r dict=%r>(sselfs __class__s__name__slistsdict(sself((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys__repr__scCst|iSdS(N(sitersselfslist(sself((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys__iter__s(s__name__s __module__s__doc__sFalsesTrues__init__sclearsgetByReferencesgetReferenceTosappends__eq__s__len__s __getitem__s __contains__s__repr__s__iter__(((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysIndexedCollections          s IndexedMapcBsAtZdZeedZdZdZdZdZ RS(sV Like L{IndexedCollection}, but also maps to another object. @since: 0.4 cCsti|||dS(N(sIndexedCollections__init__sselfsuse_hashs exceptions(sselfsuse_hashs exceptions((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys__init__$scCsti|g|_dS(s/ Clears the index and mapping. N(sIndexedCollectionsclearsselfsmapped(sself((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysclear's cCs{t|ttf otdny|i|SWn>tj o2|it jot Snt i d|nXdS(s Returns the mapped object by reference. @raise TypeError: Bad reference type. @raise pyamf.ReferenceError: Reference not found. sBad reference type.sReference %r not foundN( s isinstancesrefsintslongs TypeErrorsselfsmappeds IndexErrors exceptionssFalsesNonespyamfsReferenceError(sselfsref((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysgetMappedByReference/scCs[ti||}|dt|i}x'td|D]}|iit q9W|SdS(sh Appends C{obj} to this index. @return: The reference to C{obj} in this index. iiN( sIndexedCollectionsappendsselfsobjsidxslensmappedsdiffsrangesisNone(sselfsobjsidxsisdiff((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysappendAscCs$|i|}||i|<|SdS(s! Maps an object. N(sselfsappendsobjsidxs mapped_objsmapped(sselfsobjs mapped_objsidx((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysmapOs ( s__name__s __module__s__doc__sFalsesTrues__init__sclearsgetMappedByReferencesappendsmap(((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys IndexedMaps    cCst|tSdS(sQ Determines if the supplied C{obj} param is a valid ElementTree element. N(s isinstancesobjs xml_types(sobj((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys is_ET_elementYscCs*ttttidddjSdS(s Older versions of Python (<=2.5) and the Windows platform are renowned for mixing up 'special' floats. This function determines whether this is the case. @since: 0.4 @rtype: C{bool} s!dsiN(sstrsNaNsstructsunpack(((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysis_float_broken`scCs tt|ttjSdS(s @since: 0.5 N(sstrsfloatsvalsNaN(sval((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysisNaNnscCs tt|ttjSdS(s @since: 0.5 N(sstrsfloatsvalsPosInf(sval((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysisPosInfuscCs tt|ttjSdS(s @since: 0.5 N(sstrsfloatsvalsNegInf(sval((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysisNegInf|sf -31536000.0cCs|id}|ioC|djotSn|djotSn|djotSqn@|djotSn|djotSn|djotSntid|i |d SdS( Nisssssss%sdi( sselfsreadsbytess_is_big_endiansNaNsNegInfsPosInfsstructsunpacksendian(sselfsbytes((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pysread_double_workarounds"        cCst|tj otdt|fnt|o/|io|idq|idnt|o/|io|idq|idnMt |o/|io|idq|idnt i ||dS( s Override the L{DataTypeMixIn.write_double} method to fix problems with doubles by using the third-party C{fpconst} library. sexpected a float (got:%r)ssssssN( stypesdsfloats TypeErrorsisNaNsselfs_is_big_endianswritesisNegInfsisPosInfswrite_double_workaroundsold_func(sselfsd((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pyswrite_double_workarounds       (sBufferedByteStreamsIndexedCollections IndexedMapcBstZeZdZRS(NcOs ti|||||_dS(N(sBufferedByteStreams__init__sselfsargsskwargss_buffer(sselfsargsskwargs((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys__init__s(s__name__s __module__sNones_wrapped_classs__init__(((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys StringIOProxyscBs tZdZdZdZdZRS(Ns!s@s(s__name__s __module__sENDIAN_NETWORKs ENDIAN_NATIVEs ENDIAN_LITTLEs ENDIAN_BIG(((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys DataTypeMixIns(As__doc__sstructscalendarsdatetimestypessinspectspyamfs cStringIOsStringIOs ImportErrorssets NameErrorssetssSetsNones xml_typessETsFalsesnegative_timestamp_brokensints int_typessstrs str_typessappendslongsunicodestuplesPosInfsNegInfsNaNs find_xml_libsobjects StringIOProxys DataTypeMixInspacks ENDIAN_LITTLEs_system_endians ENDIAN_BIGsBufferedByteStreamshexdumps get_timestamps get_datetimesget_propertiess get_attrss set_attrssget_class_aliassis_class_sealedsget_class_metasIndexedCollections IndexedMaps is_ET_elementsis_float_brokensisNaNsisPosInfsisNegInfsutcfromtimestamps ValueErrorsTruesread_double_workarounds read_doubleswrite_double_workarounds write_doublesxsold_funcs cpyamf.util("ssets is_ET_elementsBufferedByteStreamspyamfs get_datetimesdatetimes str_typessisNaNsisPosInfsget_propertiesscalendarshexdumpsstructsis_class_sealeds IndexedMaps find_xml_libs DataTypeMixIns int_typessread_double_workaroundsinspectsIndexedCollections get_timestampsis_float_brokensisNegInfs StringIOProxystypess set_attrssnegative_timestamp_brokensStringIOs get_attrssget_class_aliassget_class_metasxswrite_double_workaround((s3build/bdist.linux-x86_64/egg/pyamf/util/__init__.pys? s            BQ w   "    ,g<              PKm;h-pyamf/flex/data.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Flex Data Management Service implementation. This module contains the message classes used with Flex Data Management Service. @since: 0.1.0 """ import pyamf from pyamf.flex.messaging import AsyncMessage, AcknowledgeMessage, ErrorMessage __all__ = [ 'DataMessage', 'SequencedMessage', 'PagedMessage', 'DataErrorMessage' ] class DataMessage(AsyncMessage): """ I am used to transport an operation that occured on a managed object or collection. This class of message is transmitted between clients subscribed to a remote destination as well as between server nodes within a cluster. The payload of this message describes all of the relevant details of the operation. This information is used to replicate updates and detect conflicts. @see: U{DataMessage on Livedocs (external) } """ def __init__(self): AsyncMessage.__init__(self) #: Provides access to the identity map which defines the #: unique identity of the item affected by this DataMessage #: (relevant for create/update/delete but not fill operations). self.identity = None #: Provides access to the operation/command of this DataMessage. #: #: Operations indicate how the remote destination should process #: this message. self.operation = None class SequencedMessage(AcknowledgeMessage): """ Response to L{DataMessage} requests. @see: U{SequencedMessage on Livedocs (external) } """ def __init__(self): AcknowledgeMessage.__init__(self) #: Provides access to the sequence id for this message. #: #: The sequence id is a unique identifier for a sequence #: within a remote destination. This value is only unique for #: the endpoint and destination contacted. self.sequenceId = None #: self.sequenceProxies = None #: Provides access to the sequence size for this message. #: #: The sequence size indicates how many items reside in the #: remote sequence. self.sequenceSize = None #: self.dataMessage = None class PagedMessage(SequencedMessage): """ This messsage provides information about a partial sequence result. @see: U{PagedMessage on Livedocs (external) } """ def __init__(self): SequencedMessage.__init__(self) #: Provides access to the number of total pages in a sequence #: based on the current page size. self.pageCount = None #: Provides access to the index of the current page in a sequence. self.pageIndex = None class DataErrorMessage(ErrorMessage): """ Special cases of ErrorMessage will be sent when a data conflict occurs. This message provides the conflict information in addition to the L{ErrorMessage} information. @see: U{DataErrorMessage on Livedocs (external) } """ def __init__(self): ErrorMessage.__init__(self) #: The client oringinated message which caused the conflict. self.cause = None #: An array of properties that were found to be conflicting #: between the client and server objects. self.propertyNames = None #: The value that the server had for the object with the #: conflicting properties. self.serverObject = None #: Namespace for C{flex.data} messages. MESSAGES_NS = 'flex.data.messages' pyamf.register_package(globals(), MESSAGES_NS) PKd#;N?AApyamf/flex/messaging.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Flex Messaging implementation. This module contains the message classes used with Flex Data Services. @see: U{RemoteObject on OSFlash (external) } @since: 0.1 """ import uuid import pyamf.util from pyamf import amf3 __all__ = [ 'RemotingMessage', 'CommandMessage', 'AcknowledgeMessage', 'ErrorMessage' ] NAMESPACE = 'flex.messaging.messages' SMALL_FLAG_MORE = 0x80 class AbstractMessage(object): """ Abstract base class for all Flex messages. Messages have two customizable sections; headers and data. The headers property provides access to specialized meta information for a specific message instance. The data property contains the instance specific data that needs to be delivered and processed by the decoder. @see: U{AbstractMessage on Livedocs (external) } @ivar body: Specific data that needs to be delivered to the remote destination. @type body: C{mixed} @ivar clientId: Indicates which client sent the message. @type clientId: C{str} @ivar destination: Message destination. @type destination: C{str} @ivar headers: Message headers. Core header names start with DS. @type headers: C{dict} @ivar messageId: Unique Message ID. @type messageId: C{str} @ivar timeToLive: How long the message should be considered valid and deliverable. @type timeToLive: C{int} @ivar timestamp: Timestamp when the message was generated. @type timestamp: C{int} """ class __amf__: amf3 = True static = ('body', 'clientId', 'destination', 'headers', 'messageId', 'timestamp', 'timeToLive') dynamic = False #: Each message pushed from the server will contain this header identifying #: the client that will receive the message. DESTINATION_CLIENT_ID_HEADER = "DSDstClientId" #: Messages are tagged with the endpoint id for the channel they are sent #: over. ENDPOINT_HEADER = "DSEndpoint" #: Messages that need to set remote credentials for a destination carry the #: C{Base64} encoded credentials in this header. REMOTE_CREDENTIALS_HEADER = "DSRemoteCredentials" #: The request timeout value is set on outbound messages by services or #: channels and the value controls how long the responder will wait for an #: acknowledgement, result or fault response for the message before timing #: out the request. REQUEST_TIMEOUT_HEADER = "DSRequestTimeout" SMALL_ATTRIBUTE_FLAGS = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40] SMALL_ATTRIBUTES = dict(zip( SMALL_ATTRIBUTE_FLAGS, __amf__.static )) SMALL_UUID_FLAGS = [0x01, 0x02] SMALL_UUIDS = dict(zip( SMALL_UUID_FLAGS, ['clientId', 'messageId'] )) def __init__(self, *args, **kwargs): self.body = kwargs.get('body', None) self.clientId = kwargs.get('clientId', None) self.destination = kwargs.get('destination', None) self.headers = kwargs.get('headers', {}) self.messageId = kwargs.get('messageId', None) self.timestamp = kwargs.get('timestamp', None) self.timeToLive = kwargs.get('timeToLive', None) def __repr__(self): m = '<%s ' % self.__class__.__name__ for k in self.__dict__: m += ' %s=%r' % (k, getattr(self, k)) return m + " />" def decodeSmallAttribute(self, attr, input): """ @since: 0.5 """ obj = input.readObject() if attr in ['timestamp', 'timeToLive']: return pyamf.util.get_datetime(obj / 1000.0) return obj def encodeSmallAttribute(self, attr): """ @since: 0.5 """ obj = getattr(self, attr) if not obj: return obj if attr in ['timestamp', 'timeToLive']: return pyamf.util.get_timestamp(obj) * 1000.0 elif attr in ['clientId', 'messageId']: if isinstance(obj, uuid.UUID): return None return obj def __readamf__(self, input): flags = read_flags(input) if len(flags) > 2: raise pyamf.DecodeError('Expected <=2 (got %d) flags for the ' 'AbstractMessage portion of the small message for %r' % ( len(flags), self.__class__)) for index, byte in enumerate(flags): if index == 0: for flag in self.SMALL_ATTRIBUTE_FLAGS: if flag & byte: attr = self.SMALL_ATTRIBUTES[flag] setattr(self, attr, self.decodeSmallAttribute(attr, input)) elif index == 1: for flag in self.SMALL_UUID_FLAGS: if flag & byte: attr = self.SMALL_UUIDS[flag] setattr(self, attr, decode_uuid(input.readObject())) def __writeamf__(self, output): flag_attrs = [] uuid_attrs = [] byte = 0 for flag in self.SMALL_ATTRIBUTE_FLAGS: value = self.encodeSmallAttribute(self.SMALL_ATTRIBUTES[flag]) if value: byte |= flag flag_attrs.append(value) flags = byte byte = 0 for flag in self.SMALL_UUID_FLAGS: attr = self.SMALL_UUIDS[flag] value = getattr(self, attr) if not value: continue byte |= flag uuid_attrs.append(amf3.ByteArray(value.bytes)) if not byte: output.writeUnsignedByte(flags) else: output.writeUnsignedByte(flags | SMALL_FLAG_MORE) output.writeUnsignedByte(byte) [output.writeObject(attr) for attr in flag_attrs] [output.writeObject(attr) for attr in uuid_attrs] def getSmallMessage(self): """ Return a ISmallMessage representation of this object. If one is not available, L{NotImplementedError} will be raised. @since: 0.5 """ raise NotImplementedError class AsyncMessage(AbstractMessage): """ I am the base class for all asynchronous Flex messages. @see: U{AsyncMessage on Livedocs (external) } @ivar correlationId: Correlation id of the message. @type correlationId: C{str} """ #: Messages that were sent with a defined subtopic property indicate their #: target subtopic in this header. SUBTOPIC_HEADER = "DSSubtopic" class __amf__: static = ('correlationId',) def __init__(self, *args, **kwargs): AbstractMessage.__init__(self, *args, **kwargs) self.correlationId = kwargs.get('correlationId', None) def __readamf__(self, input): AbstractMessage.__readamf__(self, input) flags = read_flags(input) if len(flags) > 1: raise pyamf.DecodeError('Expected <=1 (got %d) flags for the ' 'AsyncMessage portion of the small message for %r' % ( len(flags), self.__class__)) byte = flags[0] if byte & 0x01: self.correlationId = input.readObject() if byte & 0x02: self.correlationId = decode_uuid(input.readObject()) def __writeamf__(self, output): AbstractMessage.__writeamf__(self, output) if not isinstance(self.correlationId, uuid.UUID): output.writeUnsignedByte(0x01) output.writeObject(self.correlationId) else: output.writeUnsignedByte(0x02) output.writeObject(pyamf.amf3.ByteArray(self.correlationId.bytes)) def getSmallMessage(self): """ Return a ISmallMessage representation of this async message. @since: 0.5 """ return AsyncMessageExt(**self.__dict__) class AcknowledgeMessage(AsyncMessage): """ I acknowledge the receipt of a message that was sent previously. Every message sent within the messaging system must receive an acknowledgement. @see: U{AcknowledgeMessage on Livedocs (external) } """ #: Used to indicate that the acknowledgement is for a message that #: generated an error. ERROR_HINT_HEADER = "DSErrorHint" def __readamf__(self, input): AsyncMessage.__readamf__(self, input) flags = read_flags(input) if len(flags) > 1: raise pyamf.DecodeError('Expected <=1 (got %d) flags for the ' 'AcknowledgeMessage portion of the small message for %r' % ( len(flags), self.__class__)) def __writeamf__(self, output): AsyncMessage.__writeamf__(self, output) output.writeUnsignedByte(0) def getSmallMessage(self): """ Return a ISmallMessage representation of this acknowledge message. @since: 0.5 """ return AcknowledgeMessageExt(**self.__dict__) class CommandMessage(AsyncMessage): """ Provides a mechanism for sending commands related to publish/subscribe messaging, ping, and cluster operations. @see: U{CommandMessage on Livedocs (external) } @ivar operation: The command @type operation: C{int} @ivar messageRefType: hmm, not sure about this one. @type messageRefType: C{str} """ #: The server message type for authentication commands. AUTHENTICATION_MESSAGE_REF_TYPE = "flex.messaging.messages.AuthenticationMessage" #: This is used to test connectivity over the current channel to the remote #: endpoint. PING_OPERATION = 5 #: This is used by a remote destination to sync missed or cached messages #: back to a client as a result of a client issued poll command. SYNC_OPERATION = 4 #: This is used to request a list of failover endpoint URIs for the remote #: destination based on cluster membership. CLUSTER_REQUEST_OPERATION = 7 #: This is used to send credentials to the endpoint so that the user can be #: logged in over the current channel. The credentials need to be C{Base64} #: encoded and stored in the body of the message. LOGIN_OPERATION = 8 #: This is used to log the user out of the current channel, and will #: invalidate the server session if the channel is HTTP based. LOGOUT_OPERATION = 9 #: This is used to poll a remote destination for pending, undelivered #: messages. POLL_OPERATION = 2 #: Subscribe commands issued by a consumer pass the consumer's C{selector} #: expression in this header. SELECTOR_HEADER = "DSSelector" #: This is used to indicate that the client's session with a remote #: destination has timed out. SESSION_INVALIDATE_OPERATION = 10 #: This is used to subscribe to a remote destination. SUBSCRIBE_OPERATION = 0 #: This is the default operation for new L{CommandMessage} instances. UNKNOWN_OPERATION = 1000 #: This is used to unsubscribe from a remote destination. UNSUBSCRIBE_OPERATION = 1 #: This operation is used to indicate that a channel has disconnected. DISCONNECT_OPERATION = 12 class __amf__: static = ('operation',) def __init__(self, *args, **kwargs): AsyncMessage.__init__(self, *args, **kwargs) self.operation = kwargs.get('operation', None) #: Remote destination belonging to a specific service, based upon #: whether this message type matches the message type the service #: handles. self.messageRefType = kwargs.get('messageRefType', None) def __readamf__(self, input): AsyncMessage.__readamf__(self, input) flags = read_flags(input) if not flags: return if len(flags) > 1: raise pyamf.DecodeError('Expected <=1 (got %d) flags for the ' 'CommandMessage portion of the small message for %r' % ( len(flags), self.__class__)) byte = flags[0] if byte & 0x01: self.operation = input.readObject() def __writeamf__(self, output): AsyncMessage.__writeamf__(self, output) if self.operation: output.writeUnsignedByte(0x01) output.writeObject(self.operation) else: output.writeUnsignedByte(0) def getSmallMessage(self): """ Return a ISmallMessage representation of this command message. @since: 0.5 """ return CommandMessageExt(**self.__dict__) class ErrorMessage(AcknowledgeMessage): """ I am the Flex error message to be returned to the client. This class is used to report errors within the messaging system. @see: U{ErrorMessage on Livedocs (external) } """ #: If a message may not have been delivered, the faultCode will contain #: this constant. MESSAGE_DELIVERY_IN_DOUBT = "Client.Error.DeliveryInDoubt" #: Header name for the retryable hint header. #: #: This is used to indicate that the operation that generated the error may #: be retryable rather than fatal. RETRYABLE_HINT_HEADER = "DSRetryableErrorHint" class __amf__: static = ('extendedData', 'faultCode', 'faultDetail', 'faultString', 'rootCause') def __init__(self, *args, **kwargs): AcknowledgeMessage.__init__(self, *args, **kwargs) #: Extended data that the remote destination has chosen to associate #: with this error to facilitate custom error processing on the client. self.extendedData = kwargs.get('extendedData', {}) #: Fault code for the error. self.faultCode = kwargs.get('faultCode', None) #: Detailed description of what caused the error. self.faultDetail = kwargs.get('faultDetail', None) #: A simple description of the error. self.faultString = kwargs.get('faultString', None) #: Should a traceback exist for the error, this property contains the #: message. self.rootCause = kwargs.get('rootCause', {}) def getSmallMessage(self): """ Return a ISmallMessage representation of this error message. @since: 0.5 """ raise NotImplementedError class RemotingMessage(AbstractMessage): """ I am used to send RPC requests to a remote endpoint. @see: U{RemotingMessage on Livedocs (external) } """ class __amf__: static = ('operation', 'source') def __init__(self, *args, **kwargs): AbstractMessage.__init__(self, *args, **kwargs) #: Name of the remote method/operation that should be called. self.operation = kwargs.get('operation', None) #: Name of the service to be called including package name. #: This property is provided for backwards compatibility. self.source = kwargs.get('source', None) class AcknowledgeMessageExt(AcknowledgeMessage): """ An L{AcknowledgeMessage}, but implementing C{ISmallMessage}. @since: 0.5 """ class __amf__: external = True class CommandMessageExt(CommandMessage): """ A L{CommandMessage}, but implementing C{ISmallMessage}. @since: 0.5 """ class __amf__: external = True class AsyncMessageExt(AsyncMessage): """ A L{AsyncMessage}, but implementing C{ISmallMessage}. @since: 0.5 """ class __amf__: external = True def read_flags(input): """ @since: 0.5 """ flags = [] done = False while not done: byte = input.readUnsignedByte() if not byte & SMALL_FLAG_MORE: done = True else: byte = byte ^ SMALL_FLAG_MORE flags.append(byte) return flags def decode_uuid(obj): """ Decode a L{ByteArray} contents to a C{uuid.UUID} instance. @since: 0.5 """ return uuid.UUID(bytes=str(obj)) pyamf.register_package(globals(), package=NAMESPACE) pyamf.register_class(AcknowledgeMessageExt, 'DSK') pyamf.register_class(CommandMessageExt, 'DSC') pyamf.register_class(AsyncMessageExt, 'DSA') PK!;>;=2##pyamf/flex/__init__.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Compatibility classes/functions for Flex. @note: Not available in ActionScript 1.0 and 2.0. @see: U{Flex on Wikipedia (external) } @since: 0.1.0 """ import pyamf __all__ = ['ArrayCollection', 'ObjectProxy'] class ArrayCollection(list): """ I represent the ActionScript 3 based class C{flex.messaging.io.ArrayCollection} used in the Flex framework. The C{ArrayCollection} class is a wrapper class that exposes an Array as a collection that can be accessed and manipulated using the methods and properties of the C{ICollectionView} or C{IList} interfaces in the Flex framework. @see: U{ArrayCollection on Livedocs (external) } @note: This class does not implement the RemoteObject part of the documentation. @ivar length: [read-only] The number of items in this collection. Introduced in 0.4. @type length: C{int} """ class __amf__: external = True amf3 = True exclude = ('length',) def __init__(self, source=None): if source is not None: if isinstance(source, dict): raise TypeError('Cannot convert dicts to ArrayCollection') if hasattr(source, '__iter__'): self.extend(source) def __repr__(self): return "" % list.__repr__(self) def __readamf__(self, input): data = input.readObject() if hasattr(data, 'source'): data = data.source else: if not hasattr(data, '__iter__'): raise pyamf.DecodeError('Unable to read a list when decoding ' 'ArrayCollection') self.extend(data) def __writeamf__(self, output): output.encoder.writeList( list(self), use_references=True, use_proxies=False) def _get_length(self): return len(self) def _set_length(self, length): raise RuntimeError("Property length is read-only") length = property(_get_length, _set_length) def addItem(self, item): """ Adds the specified item to the end of the list. @param item: The object to add to the collection. @type item: C{mixed}. @since: 0.4 """ self.append(item) def addItemAt(self, item, index): """ Adds the item at the specified index. @param item: The object to add to the collection. @type item: C{mixed}. @param index: The index at which to place the item. @raise IndexError: If index is less than 0 or greater than the length of the list. @since: 0.4 """ if index < 0: raise IndexError if index > len(self): raise IndexError self.insert(index, item) def getItemAt(self, index, prefetch=0): """ Gets the item at the specified index. @param index: The index in the list from which to retrieve the item. @type index: C{int} @param prefetch: This param is ignored and is only here as part of the interface. @raise IndexError: if C{index < 0} or C{index >= length} @return: The item at index C{index}. @rtype: C{mixed}. @since: 0.4 """ if index < 0: raise IndexError if index > len(self): raise IndexError return self.__getitem__(index) def getItemIndex(self, item): """ Returns the index of the item if it is in the list such that C{getItemAt(index) == item}. @param item: The item to find. @type item: C{mixed}. @return: The index of the item or -1 if the item is not in the list. @rtype: C{int} @since: 0.4 """ try: return self.index(item) except ValueError: return -1 def removeAll(self): """ Removes all items from the list. @since: 0.4 """ while len(self) > 0: self.pop() def removeItemAt(self, index): """ Removes the item at the specified index and returns it. Any items that were after this index are now one index earlier. @param index: The index from which to remove the item. @return: The item that was removed. @rtype: C{mixed}. @raise IndexError: If index is less than 0 or greater than length. @since: 0.4 """ if index < 0: raise IndexError if index > len(self): raise IndexError x = self[index] del self[index] return x def setItemAt(self, item, index): """ Places the item at the specified index. If an item was already at that index the new item will replace it and it will be returned. @param item: The new item to be placed at the specified index. @type item: C{mixed}. @param index: The index at which to place the item. @type index: C{int} @return: The item that was replaced, or C{None}. @rtype: C{mixed} or C{None}. @raise IndexError: If index is less than 0 or greater than length. @since: 0.4 """ if index < 0: raise IndexError if index > len(self): raise IndexError tmp = self.__getitem__(index) self.__setitem__(index, item) return tmp def toArray(self): """ Returns an Array that is populated in the same order as the C{IList} implementation. @return: The array. @rtype: C{list} """ return self class ObjectProxy(object): """ I represent the ActionScript 3 based class C{flex.messaging.io.ObjectProxy} used in the Flex framework. Flex's C{ObjectProxy} class allows an anonymous, dynamic ActionScript Object to be bindable and report change events. @see: U{ObjectProxy on Livedocs (external) } """ class __amf__: external = True amf3 = True def __init__(self, object=None): if object is None: self._amf_object = pyamf.ASObject() else: self._amf_object = object def __repr__(self): return "" % self._amf_object def __getattr__(self, name): if name == '_amf_object': return self.__dict__['_amf_object'] return getattr(self.__dict__['_amf_object'], name) def __setattr__(self, name, value): if name == '_amf_object': self.__dict__['_amf_object'] = value else: setattr(self._amf_object, name, value) def __readamf__(self, input): self._amf_object = input.readObject() def __writeamf__(self, output): output.writeObject(self._amf_object, use_proxies=False) def unproxy_object(obj): """ Returns the unproxied version of the object. """ if isinstance(obj, ArrayCollection): return list(obj) elif isinstance(obj, ObjectProxy): return obj._amf_object return obj pyamf.register_package(globals(), package='flex.messaging.io') PK:u3;' pyamf/flex/data.pyc; -xJc@sdZdkZdklZlZlZddddgZdefdYZdefdYZdefd YZ defd YZ d Z ei e e dS( s Flex Data Management Service implementation. This module contains the message classes used with Flex Data Management Service. @since: 0.1.0 N(s AsyncMessagesAcknowledgeMessages ErrorMessages DataMessagesSequencedMessages PagedMessagesDataErrorMessagecBstZdZdZRS(s I am used to transport an operation that occured on a managed object or collection. This class of message is transmitted between clients subscribed to a remote destination as well as between server nodes within a cluster. The payload of this message describes all of the relevant details of the operation. This information is used to replicate updates and detect conflicts. @see: U{DataMessage on Livedocs (external) } cCs#ti|t|_t|_dS(N(s AsyncMessages__init__sselfsNonesidentitys operation(sself((s/build/bdist.linux-x86_64/egg/pyamf/flex/data.pys__init__'s  (s__name__s __module__s__doc__s__init__(((s/build/bdist.linux-x86_64/egg/pyamf/flex/data.pys DataMessages cBstZdZdZRS(s Response to L{DataMessage} requests. @see: U{SequencedMessage on Livedocs (external) } cCs5ti|t|_t|_t|_t|_dS(N(sAcknowledgeMessages__init__sselfsNones sequenceIdssequenceProxiess sequenceSizes dataMessage(sself((s/build/bdist.linux-x86_64/egg/pyamf/flex/data.pys__init__<s     (s__name__s __module__s__doc__s__init__(((s/build/bdist.linux-x86_64/egg/pyamf/flex/data.pysSequencedMessage4s cBstZdZdZRS(s This messsage provides information about a partial sequence result. @see: U{PagedMessage on Livedocs (external) } cCs#ti|t|_t|_dS(N(sSequencedMessages__init__sselfsNones pageCounts pageIndex(sself((s/build/bdist.linux-x86_64/egg/pyamf/flex/data.pys__init__Ws  (s__name__s __module__s__doc__s__init__(((s/build/bdist.linux-x86_64/egg/pyamf/flex/data.pys PagedMessageOs cBstZdZdZRS(sn Special cases of ErrorMessage will be sent when a data conflict occurs. This message provides the conflict information in addition to the L{ErrorMessage} information. @see: U{DataErrorMessage on Livedocs (external) } cCs,ti|t|_t|_t|_dS(N(s ErrorMessages__init__sselfsNonescauses propertyNamess serverObject(sself((s/build/bdist.linux-x86_64/egg/pyamf/flex/data.pys__init__ls   (s__name__s __module__s__doc__s__init__(((s/build/bdist.linux-x86_64/egg/pyamf/flex/data.pysDataErrorMessage`s sflex.data.messages(s__doc__spyamfspyamf.flex.messagings AsyncMessagesAcknowledgeMessages ErrorMessages__all__s DataMessagesSequencedMessages PagedMessagesDataErrorMessages MESSAGES_NSsregister_packagesglobals( s__all__s MESSAGES_NSspyamfs ErrorMessagesDataErrorMessagesAcknowledgeMessagesSequencedMessages PagedMessages AsyncMessages DataMessage((s/build/bdist.linux-x86_64/egg/pyamf/flex/data.pys? s PK:u3;7٤QQpyamf/flex/messaging.pyc; hJc@sedZdkZdkZdklZddddgZdZdZd efd YZ d e fd YZ de fd YZ de fdYZ de fdYZ de fdYZde fdYZde fdYZde fdYZdZdZeiedeeiedeiedeieddS(s Flex Messaging implementation. This module contains the message classes used with Flex Data Services. @see: U{RemoteObject on OSFlash (external) } @since: 0.1 N(samf3sRemotingMessagesCommandMessagesAcknowledgeMessages ErrorMessagesflex.messaging.messagesisAbstractMessagecBstZdZdfdYZdZdZdZdZddd d d d d gZe e eei Z ddgZ e e e ddgZdZdZdZdZdZdZdZRS(sy Abstract base class for all Flex messages. Messages have two customizable sections; headers and data. The headers property provides access to specialized meta information for a specific message instance. The data property contains the instance specific data that needs to be delivered and processed by the decoder. @see: U{AbstractMessage on Livedocs (external) } @ivar body: Specific data that needs to be delivered to the remote destination. @type body: C{mixed} @ivar clientId: Indicates which client sent the message. @type clientId: C{str} @ivar destination: Message destination. @type destination: C{str} @ivar headers: Message headers. Core header names start with DS. @type headers: C{dict} @ivar messageId: Unique Message ID. @type messageId: C{str} @ivar timeToLive: How long the message should be considered valid and deliverable. @type timeToLive: C{int} @ivar timestamp: Timestamp when the message was generated. @type timestamp: C{int} s__amf__cBs/tZeZdddddddfZeZRS(NsbodysclientIds destinationsheaderss messageIds timestamps timeToLive(s__name__s __module__sTruesamf3sstaticsFalsesdynamic(((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys__amf__?ss DSDstClientIds DSEndpointsDSRemoteCredentialssDSRequestTimeoutiiiiii i@sclientIds messageIdcOs|idt|_|idt|_|idt|_|idh|_|idt|_|idt|_ |idt|_ dS(NsbodysclientIds destinationsheaderss messageIds timestamps timeToLive( skwargssgetsNonesselfsbodysclientIds destinationsheaderss messageIds timestamps timeToLive(sselfsargsskwargs((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys__init__`scCsMd|ii}x.|iD]#}|d|t||f7}qW|dSdS(Ns<%s s %s=%rs />(sselfs __class__s__name__sms__dict__sksgetattr(sselfsmsk((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys__repr__is  !cCs?|i}|ddgjotii|dSn|SdS(s @since: 0.5 s timestamps timeToLivef1000.0N(sinputs readObjectsobjsattrspyamfsutils get_datetime(sselfsattrsinputsobj((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pysdecodeSmallAttributeqs  cCst||}| o|Sn|ddgjotii|dSn3|ddgjot|ti ot Sq|n|SdS(s @since: 0.5 s timestamps timeToLivef1000.0sclientIds messageIdN( sgetattrsselfsattrsobjspyamfsutils get_timestamps isinstancesuuidsUUIDsNone(sselfsattrsobj((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pysencodeSmallAttribute|s cCs t|}t|djo&tidt||ifnxt|D]\}}|djoPx|i D]>}||@o-|i |}t|||i||ququWqR|djoPxM|iD]>}||@o-|i|}t||t|iqqWqRqRWdS(NisWExpected <=2 (got %d) flags for the AbstractMessage portion of the small message for %rii(s read_flagssinputsflagsslenspyamfs DecodeErrorsselfs __class__s enumeratesindexsbytesSMALL_ATTRIBUTE_FLAGSsflagsSMALL_ATTRIBUTESsattrssetattrsdecodeSmallAttributesSMALL_UUID_FLAGSs SMALL_UUIDSs decode_uuids readObject(sselfsinputsindexsattrsflagsflagssbyte((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys __readamf__s" &     (    c Cscg}g} d}xI|iD]>}|i|i|}|o||O}|i |qqW|}d}x_|i D]T}|i |}t||}| oqtn||O}| i ti|iqtW| o|i|n|i|tB|i|gi }|D]}||i|q~gi }| D]}||i|q?~dS(Ni(s flag_attrss uuid_attrssbytesselfsSMALL_ATTRIBUTE_FLAGSsflagsencodeSmallAttributesSMALL_ATTRIBUTESsvaluesappendsflagssSMALL_UUID_FLAGSs SMALL_UUIDSsattrsgetattrsamf3s ByteArraysbytessoutputswriteUnsignedBytesSMALL_FLAG_MOREs_[1]s writeObject( sselfsoutputsattrs flag_attrssvalues_[1]sflagsflagssbytes uuid_attrs((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys __writeamf__s2      .cCs tdS(s Return a ISmallMessage representation of this object. If one is not available, L{NotImplementedError} will be raised. @since: 0.5 N(sNotImplementedError(sself((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pysgetSmallMessages(s__name__s __module__s__doc__s__amf__sDESTINATION_CLIENT_ID_HEADERsENDPOINT_HEADERsREMOTE_CREDENTIALS_HEADERsREQUEST_TIMEOUT_HEADERsSMALL_ATTRIBUTE_FLAGSsdictszipsstaticsSMALL_ATTRIBUTESsSMALL_UUID_FLAGSs SMALL_UUIDSs__init__s__repr__sdecodeSmallAttributesencodeSmallAttributes __readamf__s __writeamf__sgetSmallMessage(((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pysAbstractMessage!s&        "s AsyncMessagecBsKtZdZdZdfdYZdZdZdZdZRS(s% I am the base class for all asynchronous Flex messages. @see: U{AsyncMessage on Livedocs (external) } @ivar correlationId: Correlation id of the message. @type correlationId: C{str} s DSSubtopics__amf__cBstZdfZRS(Ns correlationId(s__name__s __module__sstatic(((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys__amf__scOs,ti||||idt|_dS(Ns correlationId(sAbstractMessages__init__sselfsargsskwargssgetsNones correlationId(sselfsargsskwargs((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys__init__scCsti||t|}t|djo&tidt||i fn|d}|d@o|i |_ n|d@ot |i |_ ndS(NisTExpected <=1 (got %d) flags for the AsyncMessage portion of the small message for %rii(sAbstractMessages __readamf__sselfsinputs read_flagssflagsslenspyamfs DecodeErrors __class__sbytes readObjects correlationIds decode_uuid(sselfsinputsflagssbyte((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys __readamf__s &   cCsxti||t|iti o!|id|i |in-|id|i t i i |ii dS(Nii(sAbstractMessages __writeamf__sselfsoutputs isinstances correlationIdsuuidsUUIDswriteUnsignedBytes writeObjectspyamfsamf3s ByteArraysbytes(sselfsoutput((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys __writeamf__s   cCst|iSdS(sc Return a ISmallMessage representation of this async message. @since: 0.5 N(sAsyncMessageExtsselfs__dict__(sself((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pysgetSmallMessages( s__name__s __module__s__doc__sSUBTOPIC_HEADERs__amf__s__init__s __readamf__s __writeamf__sgetSmallMessage(((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys AsyncMessages    cBs/tZdZdZdZdZdZRS(s: I acknowledge the receipt of a message that was sent previously. Every message sent within the messaging system must receive an acknowledgement. @see: U{AcknowledgeMessage on Livedocs (external) } s DSErrorHintcCsYti||t|}t|djo&tidt||i fndS(NisZExpected <=1 (got %d) flags for the AcknowledgeMessage portion of the small message for %r( s AsyncMessages __readamf__sselfsinputs read_flagssflagsslenspyamfs DecodeErrors __class__(sselfsinputsflags((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys __readamf__s cCs!ti|||iddS(Ni(s AsyncMessages __writeamf__sselfsoutputswriteUnsignedByte(sselfsoutput((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys __writeamf__"scCst|iSdS(si Return a ISmallMessage representation of this acknowledge message. @since: 0.5 N(sAcknowledgeMessageExtsselfs__dict__(sself((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pysgetSmallMessage's(s__name__s __module__s__doc__sERROR_HINT_HEADERs __readamf__s __writeamf__sgetSmallMessage(((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pysAcknowledgeMessage s  cBstZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdfdYZdZdZdZdZRS(s Provides a mechanism for sending commands related to publish/subscribe messaging, ping, and cluster operations. @see: U{CommandMessage on Livedocs (external) } @ivar operation: The command @type operation: C{int} @ivar messageRefType: hmm, not sure about this one. @type messageRefType: C{str} s-flex.messaging.messages.AuthenticationMessageiiiii is DSSelectori iiii s__amf__cBstZdfZRS(Ns operation(s__name__s __module__sstatic(((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys__amf__bscOsAti||||idt|_|idt|_dS(Ns operationsmessageRefType( s AsyncMessages__init__sselfsargsskwargssgetsNones operationsmessageRefType(sselfsargsskwargs((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys__init__escCsti||t|}| odSnt|djo&tidt||i fn|d}|d@o|i |_ ndS(NisVExpected <=1 (got %d) flags for the CommandMessage portion of the small message for %ri( s AsyncMessages __readamf__sselfsinputs read_flagssflagsslenspyamfs DecodeErrors __class__sbytes readObjects operation(sselfsinputsflagssbyte((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys __readamf__ns &  cCsLti|||io!|id|i|in|iddS(Nii(s AsyncMessages __writeamf__sselfsoutputs operationswriteUnsignedBytes writeObject(sselfsoutput((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys __writeamf__s   cCst|iSdS(se Return a ISmallMessage representation of this command message. @since: 0.5 N(sCommandMessageExtsselfs__dict__(sself((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pysgetSmallMessages(s__name__s __module__s__doc__sAUTHENTICATION_MESSAGE_REF_TYPEsPING_OPERATIONsSYNC_OPERATIONsCLUSTER_REQUEST_OPERATIONsLOGIN_OPERATIONsLOGOUT_OPERATIONsPOLL_OPERATIONsSELECTOR_HEADERsSESSION_INVALIDATE_OPERATIONsSUBSCRIBE_OPERATIONsUNKNOWN_OPERATIONsUNSUBSCRIBE_OPERATIONsDISCONNECT_OPERATIONs__amf__s__init__s __readamf__s __writeamf__sgetSmallMessage(((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pysCommandMessage0s&   cBs?tZdZdZdZdfdYZdZdZRS(s I am the Flex error message to be returned to the client. This class is used to report errors within the messaging system. @see: U{ErrorMessage on Livedocs (external) } sClient.Error.DeliveryInDoubtsDSRetryableErrorHints__amf__cBstZdddddfZRS(Ns extendedDatas faultCodes faultDetails faultStrings rootCause(s__name__s __module__sstatic(((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys__amf__scOsti||||idh|_|idt|_|idt|_ |idt|_ |idh|_ dS(Ns extendedDatas faultCodes faultDetails faultStrings rootCause( sAcknowledgeMessages__init__sselfsargsskwargssgets extendedDatasNones faultCodes faultDetails faultStrings rootCause(sselfsargsskwargs((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys__init__s cCs tdS(sc Return a ISmallMessage representation of this error message. @since: 0.5 N(sNotImplementedError(sself((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pysgetSmallMessages(s__name__s __module__s__doc__sMESSAGE_DELIVERY_IN_DOUBTsRETRYABLE_HINT_HEADERs__amf__s__init__sgetSmallMessage(((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys ErrorMessages  cBs*tZdZdfdYZdZRS(s I am used to send RPC requests to a remote endpoint. @see: U{RemotingMessage on Livedocs (external) } s__amf__cBstZddfZRS(Ns operationssource(s__name__s __module__sstatic(((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys__amf__scOsAti||||idt|_|idt|_dS(Ns operationssource( sAbstractMessages__init__sselfsargsskwargssgetsNones operationssource(sselfsargsskwargs((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys__init__s(s__name__s __module__s__doc__s__amf__s__init__(((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pysRemotingMessages sAcknowledgeMessageExtcBs!tZdZdfdYZRS(sW An L{AcknowledgeMessage}, but implementing C{ISmallMessage}. @since: 0.5 s__amf__cBstZeZRS(N(s__name__s __module__sTruesexternal(((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys__amf__s(s__name__s __module__s__doc__s__amf__(((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pysAcknowledgeMessageExts sCommandMessageExtcBs!tZdZdfdYZRS(sR A L{CommandMessage}, but implementing C{ISmallMessage}. @since: 0.5 s__amf__cBstZeZRS(N(s__name__s __module__sTruesexternal(((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys__amf__s(s__name__s __module__s__doc__s__amf__(((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pysCommandMessageExts sAsyncMessageExtcBs!tZdZdfdYZRS(sP A L{AsyncMessage}, but implementing C{ISmallMessage}. @since: 0.5 s__amf__cBstZeZRS(N(s__name__s __module__sTruesexternal(((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys__amf__s(s__name__s __module__s__doc__s__amf__(((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pysAsyncMessageExts cCs]g}t}xF| o=|i}|t@ o t}n |tA}|i|qW|SdS(s @since: 0.5 N( sflagssFalsesdonesinputsreadUnsignedBytesbytesSMALL_FLAG_MOREsTruesappend(sinputsflagssdonesbyte((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys read_flagss    cCstidt|SdS(sU Decode a L{ByteArray} contents to a C{uuid.UUID} instance. @since: 0.5 sbytesN(suuidsUUIDsstrsobj(sobj((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys decode_uuid sspackagesDSKsDSCsDSA(s__doc__suuids pyamf.utilspyamfsamf3s__all__s NAMESPACEsSMALL_FLAG_MOREsobjectsAbstractMessages AsyncMessagesAcknowledgeMessagesCommandMessages ErrorMessagesRemotingMessagesAcknowledgeMessageExtsCommandMessageExtsAsyncMessageExts read_flagss decode_uuidsregister_packagesglobalssregister_class(sCommandMessageExtsSMALL_FLAG_MOREsAcknowledgeMessages ErrorMessagesuuids__all__spyamfs NAMESPACEs read_flagssCommandMessagesamf3sAsyncMessageExtsRemotingMessagesAbstractMessages decode_uuids AsyncMessagesAcknowledgeMessageExt((s4build/bdist.linux-x86_64/egg/pyamf/flex/messaging.pys? s*   <'b/    PK:u3;M/,,,pyamf/flex/__init__.pyc; rJc@sjdZdkZddgZdefdYZdefdYZdZeie dddS( s Compatibility classes/functions for Flex. @note: Not available in ActionScript 1.0 and 2.0. @see: U{Flex on Wikipedia (external) } @since: 0.1.0 NsArrayCollections ObjectProxycBstZdZdfdYZedZdZdZdZdZ dZ e e e Z d Z d Zd d Zd ZdZdZdZdZRS(s I represent the ActionScript 3 based class C{flex.messaging.io.ArrayCollection} used in the Flex framework. The C{ArrayCollection} class is a wrapper class that exposes an Array as a collection that can be accessed and manipulated using the methods and properties of the C{ICollectionView} or C{IList} interfaces in the Flex framework. @see: U{ArrayCollection on Livedocs (external) } @note: This class does not implement the RemoteObject part of the documentation. @ivar length: [read-only] The number of items in this collection. Introduced in 0.4. @type length: C{int} s__amf__cBstZeZeZdfZRS(Nslength(s__name__s __module__sTruesexternalsamf3sexclude(((s3build/bdist.linux-x86_64/egg/pyamf/flex/__init__.pys__amf__(scCsV|tj oEt|totdnt|do|i|qRndS(Ns'Cannot convert dicts to ArrayCollections__iter__(ssourcesNones isinstancesdicts TypeErrorshasattrsselfsextend(sselfssource((s3build/bdist.linux-x86_64/egg/pyamf/flex/__init__.pys__init__.s  cCsdti|SdS(Ns&(slists__repr__sself(sself((s3build/bdist.linux-x86_64/egg/pyamf/flex/__init__.pys__repr__6scCs^|i}t|do |i}n%t|d otidn|i|dS(Nssources__iter__s3Unable to read a list when decoding ArrayCollection( sinputs readObjectsdatashasattrssourcespyamfs DecodeErrorsselfsextend(sselfsinputsdata((s3build/bdist.linux-x86_64/egg/pyamf/flex/__init__.pys __readamf__9s   cCs&|iit|dtdtdS(Nsuse_referencess use_proxies(soutputsencoders writeListslistsselfsTruesFalse(sselfsoutput((s3build/bdist.linux-x86_64/egg/pyamf/flex/__init__.pys __writeamf__EscCst|SdS(N(slensself(sself((s3build/bdist.linux-x86_64/egg/pyamf/flex/__init__.pys _get_lengthIscCstddS(NsProperty length is read-only(s RuntimeError(sselfslength((s3build/bdist.linux-x86_64/egg/pyamf/flex/__init__.pys _set_lengthLscCs|i|dS(s Adds the specified item to the end of the list. @param item: The object to add to the collection. @type item: C{mixed}. @since: 0.4 N(sselfsappendsitem(sselfsitem((s3build/bdist.linux-x86_64/egg/pyamf/flex/__init__.pysaddItemQscCsH|djo tn|t|jo tn|i||dS(sG Adds the item at the specified index. @param item: The object to add to the collection. @type item: C{mixed}. @param index: The index at which to place the item. @raise IndexError: If index is less than 0 or greater than the length of the list. @since: 0.4 iN(sindexs IndexErrorslensselfsinsertsitem(sselfsitemsindex((s3build/bdist.linux-x86_64/egg/pyamf/flex/__init__.pys addItemAt[s    icCsE|djo tn|t|jo tn|i|SdS(s Gets the item at the specified index. @param index: The index in the list from which to retrieve the item. @type index: C{int} @param prefetch: This param is ignored and is only here as part of the interface. @raise IndexError: if C{index < 0} or C{index >= length} @return: The item at index C{index}. @rtype: C{mixed}. @since: 0.4 iN(sindexs IndexErrorslensselfs __getitem__(sselfsindexsprefetch((s3build/bdist.linux-x86_64/egg/pyamf/flex/__init__.pys getItemAtns    cCs/y|i|SWntj o dSnXdS(s1 Returns the index of the item if it is in the list such that C{getItemAt(index) == item}. @param item: The item to find. @type item: C{mixed}. @return: The index of the item or -1 if the item is not in the list. @rtype: C{int} @since: 0.4 iN(sselfsindexsitems ValueError(sselfsitem((s3build/bdist.linux-x86_64/egg/pyamf/flex/__init__.pys getItemIndexs cCs)x"t|djo|iqWdS(sG Removes all items from the list. @since: 0.4 iN(slensselfspop(sself((s3build/bdist.linux-x86_64/egg/pyamf/flex/__init__.pys removeAllscCsM|djo tn|t|jo tn||}||=|SdS(sv Removes the item at the specified index and returns it. Any items that were after this index are now one index earlier. @param index: The index from which to remove the item. @return: The item that was removed. @rtype: C{mixed}. @raise IndexError: If index is less than 0 or greater than length. @since: 0.4 iN(sindexs IndexErrorslensselfsx(sselfsindexsx((s3build/bdist.linux-x86_64/egg/pyamf/flex/__init__.pys removeItemAts     cCs[|djo tn|t|jo tn|i|}|i|||SdS(s Places the item at the specified index. If an item was already at that index the new item will replace it and it will be returned. @param item: The new item to be placed at the specified index. @type item: C{mixed}. @param index: The index at which to place the item. @type index: C{int} @return: The item that was replaced, or C{None}. @rtype: C{mixed} or C{None}. @raise IndexError: If index is less than 0 or greater than length. @since: 0.4 iN(sindexs IndexErrorslensselfs __getitem__stmps __setitem__sitem(sselfsitemsindexstmp((s3build/bdist.linux-x86_64/egg/pyamf/flex/__init__.pys setItemAts    cCs|SdS(s Returns an Array that is populated in the same order as the C{IList} implementation. @return: The array. @rtype: C{list} N(sself(sself((s3build/bdist.linux-x86_64/egg/pyamf/flex/__init__.pystoArrays(s__name__s __module__s__doc__s__amf__sNones__init__s__repr__s __readamf__s __writeamf__s _get_lengths _set_lengthspropertyslengthsaddItems addItemAts getItemAts getItemIndexs removeAlls removeItemAts setItemAtstoArray(((s3build/bdist.linux-x86_64/egg/pyamf/flex/__init__.pysArrayCollections"           cBsZtZdZdfdYZedZdZdZdZdZ dZ RS( sk I represent the ActionScript 3 based class C{flex.messaging.io.ObjectProxy} used in the Flex framework. Flex's C{ObjectProxy} class allows an anonymous, dynamic ActionScript Object to be bindable and report change events. @see: U{ObjectProxy on Livedocs (external) } s__amf__cBstZeZeZRS(N(s__name__s __module__sTruesexternalsamf3(((s3build/bdist.linux-x86_64/egg/pyamf/flex/__init__.pys__amf__scCs-|tjoti|_n ||_dS(N(sobjectsNonespyamfsASObjectsselfs _amf_object(sselfsobject((s3build/bdist.linux-x86_64/egg/pyamf/flex/__init__.pys__init__s cCsd|iSdS(Ns"(sselfs _amf_object(sself((s3build/bdist.linux-x86_64/egg/pyamf/flex/__init__.pys__repr__scCs4|djo|idSnt|id|SdS(Ns _amf_object(snamesselfs__dict__sgetattr(sselfsname((s3build/bdist.linux-x86_64/egg/pyamf/flex/__init__.pys __getattr__s cCs5|djo||idtZdZdZdZdZdZdZRS(NcCstidd}|i|id|i|id|i|ittiddt}|i|id|i|id|i|ittit t t }|i|it |i|it |i|it dS(Nsspamseggsshellosworld( sclients ServiceProxysxsselfs assertEqualss_gws_names _auto_executesTruesordschrsFalse(sselfsx((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pys test_create5scCsKtitt}|i}|it|ti |i |i ddS(Nsspam( sclients ServiceProxysNonesxsspamsysselfs assertTrues isinstancesServiceMethodProxys assertEqualssname(sselfsysx((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pys test_getattrHs cCs|dtfdY}||}ti|d}|i}||_ f|_ |dddf|_ |ddddS(Ns DummyGatewaycBs#tZdZdZdZRS(NcCs ||_dS(N(stcsself(sselfstc((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pys__init__QscGsR|ii||i|ii||ihd|<d|<|_|iSdS(Ns method_proxysargs(sselfstcs assertEqualss method_proxysargssrequest(sselfs method_proxysargs((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pys addRequestTscCs*|ii||itidtSdS(Nsbody(sselfstcs assertEqualssrequestspyamfsASObjectsNone(sselfsrequest((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pysexecute_single[s(s__name__s __module__s__init__s addRequestsexecute_single(((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pys DummyGatewayPs  stestiii( sobjects DummyGatewaysselfsgwsclients ServiceProxysxsspamsys method_proxysargs(sselfsgwsysxs DummyGateway((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pys test_callOs    cCsHdtfdY}||}ti|d}||_|dS(Ns DummyGatewaycBs#tZdZdZdZRS(NcCs ||_dS(N(stcsself(sselfstc((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pys__init__nscGsI|ii|i|i|ii|itti d|d|SdS(Ns method_proxysargs( sselfstcs assertEqualss method_proxysservicesxsnamesNonespyamfsASObjectsargs(sselfs method_proxysargs((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pys addRequestqscCstidtSdS(Nsbody(spyamfsASObjectsNone(sselfsrequest((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pysexecute_singlews(s__name__s __module__s__init__s addRequestsexecute_single(((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pys DummyGatewayms  stest(sobjects DummyGatewaysselfsgwsclients ServiceProxysx(sselfsgwsxs DummyGateway((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pystest_service_callls   cCs~dtfdY}||}ti|dt}|i}||_ f|_ |}|i t|it|dS(Ns DummyGatewaycBstZdZdZRS(NcCs ||_dS(N(stcsself(sselfstc((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pys__init__scGsR|ii||i|ii||itid|d||_|iSdS(Ns method_proxysargs(sselfstcs assertEqualss method_proxysargsspyamfsASObjectsrequest(sselfs method_proxysargs((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pys addRequests(s__name__s __module__s__init__s addRequest(((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pys DummyGateways stest(sobjects DummyGatewaysselfsgwsclients ServiceProxysFalsesxseggssys method_proxysargssress assertEqualssidsrequest(sselfsgwsressysxs DummyGateway((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pystest_pending_calls     cCs,titd}|it|ddS(Nstest(sclients ServiceProxysNonesxsselfs assertEqualssstr(sselfsx((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pystest_strs(s__name__s __module__s test_creates test_getattrs test_callstest_service_callstest_pending_callstest_str(((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pysServiceProxyTestCase4s      sRequestWrapperTestCasecBs,tZdZdZdZdZRS(NcCsktidddd}|i|id|i|id|i|id|i|idfdS(Niiii( sclientsRequestWrappersxsselfs assertEqualssgwsidsservicesargs(sselfsx((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pys test_creates cCs2titdtt}|it|ddS(Ns/1(sclientsRequestWrappersNonesxsselfs assertEqualssstr(sselfsx((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pystest_strscCs2titttt}|itt|ddS(Nsresult(sclientsRequestWrappersNonesxsselfs assertRaisessAttributeErrorsgetattr(sselfsx((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pystest_null_responsescCsatitttt}tidd}|i||i |i ||i |i ddS(Nsbodys spam.eggs( sclientsRequestWrappersNonesxspyamfsASObjectsys setResponsesselfs assertEqualssresponsesresult(sselfsysx((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pystest_set_responses  (s__name__s __module__s test_createstest_strstest_null_responsestest_set_response(((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pysRequestWrapperTestCases   s DummyResponsecBs>tZeZeZfdZdZedZdZ RS(NcCs||_||_||_dS(N(sstatussselfsbodysheaders(sselfsstatussbodysheaders((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pys__init__s  cCs'||ijo|i|SntSdS(N(sheadersselfsheaderssNone(sselfsheader((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pys getheaderscCs'|tjo |iSn|i| SdS(N(sxsNonesselfsbody(sselfsx((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pysreads  cCs t|_dS(N(sTruesselfsclosed(sself((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pyscloses( s__name__s __module__sNonestcsFalsescloseds__init__s getheadersreadsclose(((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pys DummyResponses    sDummyConnectioncBs;tZeZeZeZeZeZedZdZ RS(NcCsY|ii|d|ii||i|ii||i|ii||i dS(NsPOST( sselfstcs assertEqualssmethodsurls expected_urlsvaluesexpected_valuesheaderssexpected_headers(sselfsmethodsurlsvaluesheaders((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pysrequestscCs |iSdS(N(sselfsresponse(sself((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pys getresponses( s__name__s __module__sNonestcsexpected_values expected_urlsexpected_headerssresponsesrequests getresponse(((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pysDummyConnections sRemotingServiceTestCasecBstZdZdZdZdZdZdZdZdZ d Z d Z d Z d Z d ZdZdZdZdZdZdZdZRS(NcCs|ittitid}|i|iddddddf|i|ii d|i|ii dtidt i }|i|i t i tidt i t ii}|i|it iidS(Nshttp://example.orgshttps example.orgsiP(sselfs assertRaisess TypeErrorsclientsRemotingServicesxs assertEqualssurls connectionshostsportspyamfsAMF3s amf_versions ClientTypessFlashComs client_type(sselfsx((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pys test_creates%cCsdtid}|i|iidtid}|i|iid|ittiddS(Nshttp://example.orgiPshttps://example.orgisftp://example.org( sclientsRemotingServicesxsselfs assertEqualss connectionsports assertRaisess ValueError(sselfsx((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pys test_schemess cCs?tid}|i|iid|i|iiddS(Nshttp://example.org:8080s example.orgi(sclientsRemotingServicesxsselfs assertEqualss connectionshostsport(sselfsx((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pys test_portscCswtid}|id}|it|ti|i |i d|i |i ||i t |iddS(Nshttp://example.orgsspami(sclientsRemotingServicesxs getServicesysselfs assertTrues isinstances ServiceProxys assertEqualss_names_gws assertRaisess TypeError(sselfsysx((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pystest_get_service s cCstid}|i|id|i|ig|id}|i |ddd}|i|i|g|i|i||i|id|i|i d|i|i||i|i dddf|i |t }|i|i||g|i|i||i|id|i|i d|i|i||i|i t f|i |}|i|i|||g|i|i||i|id|i|i d |i|i||i|i tdS( Nshttp://spameggs.netisbaziis/1s/2is/3(sclientsRemotingServicesgwsselfs assertEqualssrequest_numbersrequestss getServicesservices addRequestswrappersidsargssNoneswrapper2swrapper3stuple(sselfsgwswrapper2sserviceswrapperswrapper3((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pystest_add_requests2cCstid}|i|ig|id}|i|ddd}|i|i|g|i ||i|ig|i|ddd}|i|i|g|i |ddd|i|ig|i t |i |ddddS(Nshttp://spameggs.netsbaziii( sclientsRemotingServicesgwsselfs assertEqualssrequestss getServicesservices addRequestswrappers removeRequests assertRaisess LookupError(sselfsgwsserviceswrapper((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pystest_remove_request7s cCstid}|id}|i|ddd}|it|}|i |||id}|i |||i|i }|i ||dS(Nshttp://spameggs.netsbaziiis/1( sclientsRemotingServicesgws getServicesservices addRequestswrappers getRequestsstrswrapper2sselfs assertEqualssid(sselfsgwswrapper2sserviceswrapper((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pystest_get_requestJscCsxtidtitii}|id}|i }|i |ddd}|i |g}|i|iti|i|itii|i|idg|d}|i|id|i|idddg|i |i}|i|iti|i|itii|i|idg|d}|i|id|i|idddgdS(Nshttp://example.orgsbaziiis/1sbaz.gak(sclientsRemotingServicespyamfsAMF3s ClientTypessFlashComsgws getServicesservicesgaks method_proxys addRequestswrappers getAMFRequestsenvelopesselfs assertEqualss amfVersions clientTypeskeyssrequeststargetsbodysrequestss envelope2(sselfsgwsservicesrequestsenvelopes method_proxyswrappers envelope2((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pystest_get_amf_requestYs&   cCs8tid}t}||_||_hdti <dti <|_ |i ddt }|i}tddhdd<d d <}||_d |_d d |_||_|i||i|ig|i}tddhdd<}||_d |_d d|_||_|i|dS(Nshttp://example.org/x/y/zs Content-Types User-Agentsbazs auto_executeis& /1/onResultnullhellosapplication/x-amfsContent-Lengthi2s/x/y/zsbaz.gaks /1 s& /2/onResultnullhellos /2 (sclientsRemotingServicesgwsDummyConnectionsdcs connectionsselfstcsremotings CONTENT_TYPEsDEFAULT_USER_AGENTsexpected_headerss getServicesFalsesservicesgakswrappers DummyResponsesresponses expected_urlsexpected_valuesexecute_singles assertEqualssrequests(sselfsgwsservicesdcswrappersresponse((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pystest_execute_singleus.   !             cCstid}t}||_||_hdd<dti<|_ |i ddt }|i ddt }|i}|i}tdd hdd<}||_d |_d d d |_||_|i|i|igdS(Nshttp://example.org/x/y/zs Content-Typesapplication/x-amfs User-Agentsbazs auto_executesspamisF /1/onResultnullhello /2/onResultnullhellos/x/y/zsbaz.gaks/1 spam.eggs/2s (sclientsRemotingServicesgwsDummyConnectionsdcs connectionsselfstcsDEFAULT_USER_AGENTsexpected_headerss getServicesFalsesbazsspamsgakswrapperseggsswrapper2s DummyResponsesresponses expected_urlsexpected_valuesexecutes assertEqualssrequests(sselfsgwswrapper2sspamsbazsdcswrappersresponse((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pys test_executes"          cCstid}t}||_tddhdd<}||_|itddh}||_|i t i |itddhdd<}||_|i t i |idS( Nshttp://example.org/amf-gatewayiss Content-Typesapplication/x-amfiss text/html( sclientsRemotingServicesgwsDummyConnectionsdcs connections DummyResponsesresponses _getResponsesselfs assertRaisessremotings RemotingError(sselfsgwsdcsresponse((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pystest_get_responses       cCstid}|id|ij|idd|id|ij|i|idhdd<dd<|i g}|id|ij|id}|i||iddS( Nshttp://example.org/amf-gateways Credentialssspamseggssuseriduspamspasswordueggs( sclientsRemotingServicesgwsselfs assertFalsesheadersssetCredentialss assertTrues assertEqualss getAMFRequestsenvelopescred(sselfsgwscredsenvelope((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pystest_credentialss cCshtid}t}||_tddhdd<}||_|i}|i |i ddS(Nshttp://example.org/amf-gatewayis'AppendToGatewayUrlhellos Content-Typesapplication/x-amfs#http://example.org/amf-gatewayhello( sclientsRemotingServicesgwsDummyConnectionsdcs connections DummyResponsesresponses _getResponsesselfs assertEqualss original_url(sselfsgwsdcsresponse((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pystest_append_url_headers     cCshtid}t}||_tddhdd<}||_|i}|i |i ddS(Nshttp://example.org/amf-gatewayis1ReplaceGatewayUrlhttp://spam.eggss Content-Typesapplication/x-amfshttp://spam.eggs( sclientsRemotingServicesgwsDummyConnectionsdcs connections DummyResponsesresponses _getResponsesselfs assertEqualss original_url(sselfsgwsdcsresponse((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pystest_replace_url_headers     cCsctid}t}||_tddhdd<|_|i|i |ii t dS(Nshttp://example.org/amf-gatewayis1ReplaceGatewayUrlhttp://spam.eggss Content-Typesapplication/x-amf( sclientsRemotingServicesgwsDummyConnectionsdcs connections DummyResponsesresponses _getResponsesselfs assertTruesclosedsTrue(sselfsgwsdc((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pystest_close_http_responses    cCsRtid}|i|ih|idd|i|ihdd<dS(Nshttp://example.org/amf-gatewaysETags29083457239804752309485(sclientsRemotingServicesgwsselfs assertEqualss http_headerss addHTTPHeader(sselfsgw((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pystest_add_http_header scCs[tid}hdd<|_|id|i|ih|it|iddS(Nshttp://example.org/amf-gateways Set-Cookiesfoo-bar( sclientsRemotingServicesgws http_headerssremoveHTTPHeadersselfs assertEqualss assertRaisessKeyError(sselfsgw((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pystest_remove_http_headers  cCstid}t}||_||_d|_d|_ |i ddhdd<dd<d|i <|_ t d d hdd<|_|i|i|iitdS( Nshttp://example.org/amf-gateways /amf-gatewayssETags29083457239804752309485s Content-Typesapplication/x-amfs User-Agentis1ReplaceGatewayUrlhttp://spam.eggs(sclientsRemotingServicesgwsDummyConnectionsdcs connectionsselfstcs expected_urlsexpected_values addHTTPHeaders user_agentsexpected_headerss DummyResponsesresponsesexecutes assertTruesclosedsTrue(sselfsgwsdc((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pystest_http_request_headers s     '  cCsltid}t}||_tddhdd<dd<}||_|i |i |i dS(Nshttp://example.org/amf-gatewayis1ReplaceGatewayUrlhttp://spam.eggss Content-Typesapplication/x-amfsContent-Lengths( sclientsRemotingServicesgwsDummyConnectionsdcs connections DummyResponses http_responsesresponses _getResponsesselfs assertTruesclosed(sselfsgwsdcs http_response((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pystest_empty_content_length7s     cCsetid}t}||_tddhdd<dd<}||_|i t |i dS(Nshttp://example.org/amf-gatewayis1ReplaceGatewayUrlhttp://spam.eggss Content-Typesapplication/x-amfsContent-Lengthsasdfasdf( sclientsRemotingServicesgwsDummyConnectionsdcs connections DummyResponses http_responsesresponsesselfs assertRaisess ValueErrors _getResponse(sselfsgwsdcs http_response((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pystest_bad_content_lengthGs    (s__name__s __module__s test_creates test_schemess test_portstest_get_servicestest_add_requeststest_remove_requeststest_get_requeststest_get_amf_requeststest_execute_singles test_executestest_get_responsestest_credentialsstest_append_url_headerstest_replace_url_headerstest_close_http_responsestest_add_http_headerstest_remove_http_headerstest_http_request_headersstest_empty_content_lengthstest_bad_content_length(((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pysRemotingServiceTestCases(   #    '       cCslti}|itit|itit|itit|itit|SdS(N( sunittests TestSuitessuitesaddTests makeSuitesServiceMethodProxyTestCasesServiceProxyTestCasesRequestWrapperTestCasesRemotingServiceTestCase(ssuite((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pyssuiteWs  s__main__s defaultTestssuite(s__doc__sunittestspyamfsremotingspyamf.remotingsclientsTestCasesServiceMethodProxyTestCasesServiceProxyTestCasesRequestWrapperTestCasesobjects DummyResponsesDummyConnectionsRemotingServiceTestCasessuites__name__smain( sremotingsServiceMethodProxyTestCasesRequestWrapperTestCasesunittestsDummyConnectionsclients DummyResponsesServiceProxyTestCasessuitespyamfsRemotingServiceTestCase((s@build/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_client.pys? s    !jr PK:u3;܄!pyamf/tests/remoting/__init__.pyc; VJc@s dZdS(s Remoting tests. @since: 0.1.0 N(s__doc__(((s=build/bdist.linux-x86_64/egg/pyamf/tests/remoting/__init__.pys?sPK:u3;]{7{7*pyamf/tests/remoting/test_remoteobject.pyc; Jc@sdZdkZdkZdklZdklZlZdklZdei fdYZ dei fdYZ d ei fd YZ d Z ed joeid dndS(s" RemoteObject Tests. @since: 0.1 N(sremoting(samf3sgateway(s messagingsRandomIdGeneratorTestCasecBstZdZRS(NcCsMg}x@tdD]2}ti}|i||j|i|qWdS(Ni( sxsrangesisamf3sgenerate_random_idsid_sselfs assertTruesappend(sselfsid_sisx((sFbuild/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_remoteobject.pys test_generates   (s__name__s __module__s test_generate(((sFbuild/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_remoteobject.pysRandomIdGeneratorTestCasess AcknowlegdementGeneratorTestCasecBstZdZdZRS(NcCskti}|it|ti|i|it j |i|i t j |i|i t j dS(N( samf3sgenerate_acknowledgementsacksselfs assertTrues isinstances messagingsAcknowledgeMessages messageIdsNonesclientIds timestamp(sselfsack((sFbuild/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_remoteobject.pys test_generates  cCstitidd}|it|ti |i|i t j |i|i t j |i|i t j |i|iddS(Ns messageIds123123(samf3sgenerate_acknowledgementspyamfsASObjectsacksselfs assertTrues isinstances messagingsAcknowledgeMessages messageIdsNonesclientIds timestamps assertEqualss correlationId(sselfsack((sFbuild/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_remoteobject.pys test_request&s (s__name__s __module__s test_generates test_request(((sFbuild/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_remoteobject.pys AcknowlegdementGeneratorTestCases sRequestProcessorTestCasecBsktZdZdZdZdZdZdZdZdZ d Z d Z d Z RS( NcCs&tid}|i|iddS(Nsxyz(samf3sRequestProcessorsrpsselfs assertEqualssgateway(sselfsrp((sFbuild/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_remoteobject.pys test_create2scCstidd}tit}tidd|g}||}|i }|it|ti|i|iti|it|ti|i|i tdS(Ns operationisnullsbody(s messagingsCommandMessagesmessagesamf3sRequestProcessorsNonesrpsremotingsRequestsrequestsresponsesbodysacksselfs assertTrues isinstancesResponses assertEqualssstatuss STATUS_OKsAcknowledgeMessagesTrue(sselfsrpsacksrequestsmessagesresponse((sFbuild/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_remoteobject.pys test_ping6s  cCsd}tihd|<}ti|}tiddgdd}t i dd|g}||}|i}|it|t i|i|it i|it|ti|i|iddS(NcCs|SdS(N(sx(sx((sFbuild/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_remoteobject.pysechoDssechosbodys spam.eggss operationsnull(sechosgateways BaseGatewaysgwsamf3sRequestProcessorsrps messagingsRemotingMessagesmessagesremotingsRequestsrequestsresponsesbodysacksselfs assertTrues isinstancesResponses assertEqualssstatuss STATUS_OKsAcknowledgeMessage(sselfsgwsrpsacksrequestsechosresponsesmessage((sFbuild/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_remoteobject.pys test_requestCs   cCsd}tihd|<}ti|}tiddgdd}t i dd|g}||}|i}|i|i|it|t i|i|it i|it|ti|i|iddS(NcCs tdS(N(s TypeError(sx((sFbuild/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_remoteobject.pysechoUssechosbodys spam.eggss operationsnulls TypeError(sechosgateways BaseGatewaysgwsamf3sRequestProcessorsrps messagingsRemotingMessagesmessagesremotingsRequestsrequestsresponsesbodysacksselfs assertFalsesdebugs assertTrues isinstancesResponses assertEqualssstatuss STATUS_ERRORs ErrorMessages faultCode(sselfsgwsrpsacksrequestsechosresponsesmessage((sFbuild/bdist.linux-x86_64/egg/pyamf/tests/remoting/test_remoteobject.pys test_errorTs   cCsd}tihd|\ pyamf/tests/gateway/test_wsgi.py# -*- coding: utf-8 -*- # # Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ WSGI gateway tests. @since: 0.1.0 """ import unittest import pyamf from pyamf import remoting, util from pyamf.remoting.gateway.wsgi import WSGIGateway class WSGIServerTestCase(unittest.TestCase): def setUp(self): self.gw = WSGIGateway() self.executed = False def test_request_method(self): def bad_response(status, headers): self.executed = True self.assertEquals(status, '400 Bad Request') self.gw({'REQUEST_METHOD': 'GET'}, bad_response) self.assertTrue(self.executed) self.assertRaises(KeyError, self.gw, {'REQUEST_METHOD': 'POST'}, lambda *args: None) def test_bad_request(self): request = util.BufferedByteStream() request.write('Bad request') request.seek(0, 0) env = { 'REQUEST_METHOD': 'POST', 'CONTENT_LENGTH': str(len(request)), 'wsgi.input': request } def start_response(status, headers): self.assertEquals(status, '400 Bad Request') self.executed = True self.gw(env, start_response) self.assertTrue(self.executed) def test_unknown_request(self): request = util.BufferedByteStream() request.write('\x00\x00\x00\x00\x00\x01\x00\x09test.test\x00' '\x02/1\x00\x00\x00\x14\x0a\x00\x00\x00\x01\x08\x00\x00\x00\x00' '\x00\x01\x61\x02\x00\x01\x61\x00\x00\x09') request.seek(0, 0) env = { 'REQUEST_METHOD': 'POST', 'CONTENT_LENGTH': str(len(request)), 'wsgi.input': request } def start_response(status, headers): self.executed = True self.assertEquals(status, '200 OK') self.assertTrue(('Content-Type', 'application/x-amf') in headers) response = self.gw(env, start_response) envelope = remoting.decode(''.join(response)) message = envelope['/1'] self.assertEquals(message.status, remoting.STATUS_ERROR) body = message.body self.assertTrue(isinstance(body, remoting.ErrorFault)) self.assertEquals(body.code, 'Service.ResourceNotFound') self.assertTrue(self.executed) def test_eof_decode(self): request = util.BufferedByteStream() env = { 'REQUEST_METHOD': 'POST', 'CONTENT_LENGTH': str(len(request)), 'wsgi.input': request } def start_response(status, headers): self.executed = True self.assertEquals(status, '400 Bad Request') self.assertTrue(('Content-Type', 'text/plain') in headers) response = self.gw(env, start_response) self.assertEquals(response, ['400 Bad Request\n\nThe request body was unable to be successfully decoded.']) self.assertTrue(self.executed) def _raiseException(self, e, *args, **kwargs): raise e() def test_really_bad_decode(self): self.old_method = remoting.decode remoting.decode = lambda *args, **kwargs: self._raiseException(Exception, *args, **kwargs) request = util.BufferedByteStream() env = { 'REQUEST_METHOD': 'POST', 'CONTENT_LENGTH': str(len(request)), 'wsgi.input': request } def start_response(status, headers): self.executed = True self.assertEquals(status, '500 Internal Server Error') self.assertTrue(('Content-Type', 'text/plain') in headers) try: response = self.gw(env, start_response) except: remoting.decode = self.old_method raise remoting.decode = self.old_method self.assertEquals(response, ['500 Internal Server Error\n\nAn unexpec' 'ted error occurred whilst decoding.']) self.assertTrue(self.executed) def test_expected_exceptions_decode(self): self.old_method = remoting.decode env = { 'REQUEST_METHOD': 'POST', 'CONTENT_LENGTH': '0', 'wsgi.input': util.BufferedByteStream() } try: for x in (KeyboardInterrupt, SystemExit): remoting.decode = lambda *args, **kwargs: self._raiseException(x, *args, **kwargs) self.assertRaises(x, self.gw, env, lambda *args: args) except: remoting.decode = self.old_method raise remoting.decode = self.old_method def test_expose_request(self): self.gw.expose_request = True self.executed = False env = remoting.Envelope(pyamf.AMF0, pyamf.ClientTypes.Flash9) request = remoting.Request('echo', body=['hello']) env['/1'] = request request = remoting.encode(env) env = { 'REQUEST_METHOD': 'POST', 'CONTENT_LENGTH': str(len(request)), 'wsgi.input': request } def echo(http_request, data): self.assertTrue('pyamf.request' in http_request) request = http_request['pyamf.request'] self.assertTrue(isinstance(request, remoting.Request)) self.assertEquals(request.target, 'echo') self.assertEquals(request.body, ['hello']) self.executed = True return data self.gw.addService(echo) response = self.gw(env, lambda *args: None) self.assertTrue(self.executed) def test_timezone(self): import datetime self.executed = False td = datetime.timedelta(hours=-5) now = datetime.datetime.utcnow() def echo(d): self.assertEquals(d, now + td) self.executed = True return d self.gw.addService(echo) self.gw.timezone_offset = -18000 msg = remoting.Envelope(amfVersion=pyamf.AMF0, clientType=0) msg['/1'] = remoting.Request(target='echo', body=[now]) stream = remoting.encode(msg) env = { 'REQUEST_METHOD': 'POST', 'CONTENT_LENGTH': str(len(stream)), 'wsgi.input': stream } response = self.gw(env, lambda *args: None) envelope = remoting.decode(''.join(response)) message = envelope['/1'] self.assertEquals(message.body, now) def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(WSGIServerTestCase)) return suite if __name__ == '__main__': unittest.main(defaultTest='suite') PKG$;%mm m "pyamf/tests/gateway/test_google.py# -*- coding: utf-8 -*- # # Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Google Web App gateway tests. @since: 0.3.1 """ import unittest from StringIO import StringIO from google.appengine.ext import webapp import pyamf from pyamf import remoting from pyamf.remoting.gateway import google as _google class WebAppGatewayTestCase(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) self.gw = _google.WebAppGateway() self.environ = { 'wsgi.input': StringIO(), 'wsgi.output': StringIO() } self.request = webapp.Request(self.environ) self.response = webapp.Response() self.gw.initialize(self.request, self.response) def test_get(self): self.gw.get() self.assertEquals(self.response.__dict__['_Response__status'][0], 405) def test_bad_request(self): self.environ['wsgi.input'].write('Bad request') self.environ['wsgi.input'].seek(0, 0) self.gw.post() self.assertEquals(self.response.__dict__['_Response__status'][0], 400) def test_unknown_request(self): self.environ['wsgi.input'].write( '\x00\x00\x00\x00\x00\x01\x00\x09test.test\x00\x02/1\x00\x00\x00' '\x14\x0a\x00\x00\x00\x01\x08\x00\x00\x00\x00\x00\x01\x61\x02\x00' '\x01\x61\x00\x00\x09') self.environ['wsgi.input'].seek(0, 0) self.gw.post() self.assertEquals(self.response.__dict__['_Response__status'][0], 200) envelope = remoting.decode(self.response.out.getvalue()) message = envelope['/1'] self.assertEquals(message.status, remoting.STATUS_ERROR) body = message.body self.assertTrue(isinstance(body, remoting.ErrorFault)) self.assertEquals(body.code, 'Service.ResourceNotFound') def test_expose_request(self): self.executed = False def test(request): self.assertEquals(self.request, request) self.assertTrue(hasattr(self.request, 'amf_request')) self.executed = True self.gw.expose_request = True self.gw.addService(test, 'test.test') self.environ['wsgi.input'].write('\x00\x00\x00\x00\x00\x01\x00\x09' 'test.test\x00\x02/1\x00\x00\x00\x05\x0a\x00\x00\x00\x00') self.environ['wsgi.input'].seek(0, 0) self.gw.post() self.assertTrue(self.executed) def test_timezone(self): import datetime self.executed = False td = datetime.timedelta(hours=-5) now = datetime.datetime.utcnow() def echo(d): self.assertEquals(d, now + td) self.executed = True return d self.gw.addService(echo) self.gw.timezone_offset = -18000 msg = remoting.Envelope(amfVersion=pyamf.AMF0, clientType=0) msg['/1'] = remoting.Request(target='echo', body=[now]) stream = remoting.encode(msg) self.environ['wsgi.input'] = stream self.gw.post() envelope = remoting.decode(self.response.out.getvalue()) message = envelope['/1'] self.assertEquals(message.body, now) self.assertTrue(self.executed) def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(WebAppGatewayTestCase)) return suite if __name__ == '__main__': unittest.main(defaultTest='suite') PK:wpyamf/tests/gateway/__init__.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Unit tests for Remoting gateways. @since: 0.1.0 """ PKG$;26Q"pyamf/tests/gateway/test_django.py# -*- coding: utf-8 -*- # # Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Django gateway tests. @since: 0.1.0 """ import unittest import sys import os from django import http import pyamf from pyamf import remoting, util from pyamf.remoting.gateway import django as _django class HttpRequest(http.HttpRequest): """ Custom C{HttpRequest} to support raw_post_data provided by C{django.core.handlers.*} """ def __init__(self, *args, **kwargs): http.HttpRequest.__init__(self, *args, **kwargs) self.raw_post_data = '' class DjangoGatewayTestCase(unittest.TestCase): def setUp(self): import new self.mod_name = '%s.%s' % (__name__, 'settings') sys.modules[self.mod_name] = new.module(self.mod_name) self.old_env = os.environ.get('DJANGO_SETTINGS_MODULE', None) os.environ['DJANGO_SETTINGS_MODULE'] = self.mod_name def tearDown(self): if self.old_env is not None: os.environ['DJANGO_SETTINGS_MODULE'] = self.old_env del sys.modules[self.mod_name] def test_settings(self): from django import conf settings_mod = sys.modules[self.mod_name] settings_mod.DEBUG = True settings_mod.AMF_TIME_OFFSET = 1000 conf.settings = conf.Settings(self.mod_name) gw = _django.DjangoGateway() self.assertTrue(gw.debug) self.assertEquals(gw.timezone_offset, 1000) def test_request_method(self): gw = _django.DjangoGateway() http_request = HttpRequest() http_request.method = 'GET' http_response = gw(http_request) self.assertEquals(http_response.status_code, 405) def test_bad_request(self): gw = _django.DjangoGateway() request = util.BufferedByteStream() request.write('Bad request') request.seek(0, 0) http_request = HttpRequest() http_request.method = 'POST' http_request.raw_post_data = request.getvalue() http_response = gw(http_request) self.assertEquals(http_response.status_code, 400) def test_unknown_request(self): gw = _django.DjangoGateway() request = util.BufferedByteStream() request.write('\x00\x00\x00\x00\x00\x01\x00\x09test.test\x00' '\x02/1\x00\x00\x00\x14\x0a\x00\x00\x00\x01\x08\x00\x00\x00\x00' '\x00\x01\x61\x02\x00\x01\x61\x00\x00\x09') request.seek(0, 0) http_request = HttpRequest() http_request.method = 'POST' http_request.raw_post_data = request.getvalue() http_response = gw(http_request) envelope = remoting.decode(http_response.content) message = envelope['/1'] self.assertEquals(message.status, remoting.STATUS_ERROR) body = message.body self.assertTrue(isinstance(body, remoting.ErrorFault)) self.assertEquals(body.code, 'Service.ResourceNotFound') def test_expose_request(self): http_request = HttpRequest() self.executed = False def test(request): self.assertEquals(http_request, request) self.assertTrue(hasattr(request, 'amf_request')) self.executed = True gw = _django.DjangoGateway({'test.test': test}, expose_request=True) request = util.BufferedByteStream() request.write('\x00\x00\x00\x00\x00\x01\x00\x09test.test\x00' '\x02/1\x00\x00\x00\x05\x0a\x00\x00\x00\x00') request.seek(0, 0) http_request.method = 'POST' http_request.raw_post_data = request.getvalue() gw(http_request) self.assertTrue(self.executed) def _raiseException(self, e, *args, **kwargs): raise e() def test_really_bad_decode(self): self.old_method = remoting.decode remoting.decode = lambda *args, **kwargs: self._raiseException(Exception, *args, **kwargs) http_request = HttpRequest() http_request.method = 'POST' http_request.raw_post_data = '' gw = _django.DjangoGateway() try: http_response = gw(http_request) except: remoting.decode = self.old_method raise remoting.decode = self.old_method self.assertTrue(isinstance(http_response, http.HttpResponseServerError)) self.assertEquals(http_response.status_code, 500) self.assertEquals(http_response.content, '500 Internal Server Error\n\nAn unexpected error occurred.') def test_expected_exceptions_decode(self): self.old_method = remoting.decode gw = _django.DjangoGateway() http_request = HttpRequest() http_request.method = 'POST' http_request.raw_post_data = '' try: for x in (KeyboardInterrupt, SystemExit): remoting.decode = lambda *args, **kwargs: self._raiseException(x, *args, **kwargs) self.assertRaises(x, gw, http_request) except: remoting.decode = self.old_method raise remoting.decode = self.old_method def test_timezone(self): import datetime http_request = HttpRequest() self.executed = False td = datetime.timedelta(hours=-5) now = datetime.datetime.utcnow() def echo(d): self.assertEquals(d, now + td) self.executed = True return d gw = _django.DjangoGateway({'test.test': echo}, timezone_offset=-18000, expose_request=False) msg = remoting.Envelope(amfVersion=pyamf.AMF0, clientType=0) msg['/1'] = remoting.Request(target='test.test', body=[now]) http_request.method = 'POST' http_request.raw_post_data = remoting.encode(msg).getvalue() res = remoting.decode(gw(http_request).content) self.assertTrue(self.executed) self.assertEquals(res['/1'].body, now) def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(DjangoGatewayTestCase)) return suite if __name__ == '__main__': unittest.main(defaultTest='suite') PK,;$dd#pyamf/tests/gateway/test_twisted.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Twisted gateway tests. @since: 0.1.0 """ from twisted.internet import reactor, defer from twisted.python import failure from twisted.web import http, server, client, error, resource from twisted.trial import unittest import pyamf from pyamf import remoting from pyamf.remoting import gateway from pyamf.flex import messaging from pyamf.remoting.gateway import twisted as _twisted class TestService(object): def spam(self): return 'spam' def echo(self, x): return x class TwistedServerTestCase(unittest.TestCase): def setUp(self): self.gw = _twisted.TwistedGateway(expose_request=False) root = resource.Resource() root.putChild('', self.gw) self.p = reactor.listenTCP(0, server.Site(root), interface="127.0.0.1") self.port = self.p.getHost().port def tearDown(self): self.p.stopListening() def test_invalid_method(self): """ A classic GET on the xml server should return a NOT_ALLOWED. """ d = client.getPage("http://127.0.0.1:%d/" % (self.port,)) d = self.assertFailure(d, error.Error) d.addCallback( lambda exc: self.assertEquals(int(exc.args[0]), http.NOT_ALLOWED)) return d def test_bad_content(self): d = client.getPage("http://127.0.0.1:%d/" % (self.port,), method="POST", postdata="spamandeggs") d = self.assertFailure(d, error.Error) d.addCallback( lambda exc: self.assertEquals(int(exc.args[0]), http.BAD_REQUEST)) return d def test_process_request(self): def echo(data): return data self.gw.addService(echo) env = remoting.Envelope(pyamf.AMF0, pyamf.ClientTypes.Flash9) request = remoting.Request('echo', body=['hello']) env['/1'] = request d = client.getPage("http://127.0.0.1:%d/" % (self.port,), method="POST", postdata=remoting.encode(env).getvalue()) def cb(result): response = remoting.decode(result) self.assertEquals(response.amfVersion, pyamf.AMF0) self.assertEquals(response.clientType, pyamf.ClientTypes.Flash9) self.assertTrue('/1' in response) body_response = response['/1'] self.assertEquals(body_response.status, remoting.STATUS_OK) self.assertEquals(body_response.body, 'hello') return d.addCallback(cb) def test_deferred_service(self): def echo(data): x = defer.Deferred() reactor.callLater(0, x.callback, data) return x self.gw.addService(echo) env = remoting.Envelope(pyamf.AMF0, pyamf.ClientTypes.Flash9) request = remoting.Request('echo', body=['hello']) env['/1'] = request d = client.getPage("http://127.0.0.1:%d/" % (self.port,), method="POST", postdata=remoting.encode(env).getvalue()) def cb(result): response = remoting.decode(result) self.assertEquals(response.amfVersion, pyamf.AMF0) self.assertEquals(response.clientType, pyamf.ClientTypes.Flash9) self.assertTrue('/1' in response) body_response = response['/1'] self.assertEquals(body_response.status, remoting.STATUS_OK) self.assertEquals(body_response.body, 'hello') return d.addCallback(cb) def test_unknown_request(self): env = remoting.Envelope(pyamf.AMF0, pyamf.ClientTypes.Flash9) request = remoting.Request('echo', body=['hello']) env['/1'] = request d = client.getPage("http://127.0.0.1:%d/" % (self.port,), method="POST", postdata=remoting.encode(env).getvalue()) def cb(result): response = remoting.decode(result) message = response['/1'] self.assertEquals(message.status, remoting.STATUS_ERROR) body = message.body self.assertTrue(isinstance(body, remoting.ErrorFault)) self.assertEquals(body.code, 'Service.ResourceNotFound') return d.addCallback(cb) def test_expose_request(self): self.gw.expose_request = True self.executed = False env = remoting.Envelope(pyamf.AMF0, pyamf.ClientTypes.Flash9) request = remoting.Request('echo', body=['hello']) env['/1'] = request def echo(http_request, data): self.assertTrue(isinstance(http_request, http.Request)) self.assertTrue(hasattr(http_request, 'amf_request')) amf_request = http_request.amf_request self.assertEquals(request.target, 'echo') self.assertEquals(request.body, ['hello']) self.executed = True return data self.gw.addService(echo) d = client.getPage("http://127.0.0.1:%d/" % (self.port,), method="POST", postdata=remoting.encode(env).getvalue()) return d.addCallback(lambda x: self.assertTrue(self.executed)) def test_preprocessor(self): d = defer.Deferred() def pp(sr): self.assertIdentical(sr, self.service_request) d.callback(None) gw = _twisted.TwistedGateway({'echo': lambda x: x}, preprocessor=pp) self.service_request = gateway.ServiceRequest(None, gw.services['echo'], None) gw.preprocessRequest(self.service_request) return d def test_exposed_preprocessor(self): d = defer.Deferred() def pp(hr, sr): self.assertEquals(hr, 'hello') self.assertIdentical(sr, self.service_request) d.callback(None) pp = gateway.expose_request(pp) gw = _twisted.TwistedGateway({'echo': lambda x: x}, preprocessor=pp) self.service_request = gateway.ServiceRequest(None, gw.services['echo'], None) gw.preprocessRequest(self.service_request, http_request='hello') return d def test_exposed_preprocessor_no_request(self): d = defer.Deferred() def pp(hr, sr): self.assertEquals(hr, None) self.assertIdentical(sr, self.service_request) d.callback(None) pp = gateway.expose_request(pp) gw = _twisted.TwistedGateway({'echo': lambda x: x}, preprocessor=pp) self.service_request = gateway.ServiceRequest(None, gw.services['echo'], None) gw.preprocessRequest(self.service_request) return d def test_authenticate(self): d = defer.Deferred() def auth(u, p): try: self.assertEquals(u, 'u') self.assertEquals(p, 'p') except: d.errback(failure.Failure()) else: d.callback(None) gw = _twisted.TwistedGateway({'echo': lambda x: x}, authenticator=auth) self.service_request = gateway.ServiceRequest(None, gw.services['echo'], None) gw.authenticateRequest(self.service_request, 'u', 'p') return d def test_exposed_authenticate(self): d = defer.Deferred() def auth(request, u, p): try: self.assertEquals(request, 'foo') self.assertEquals(u, 'u') self.assertEquals(p, 'p') except: d.errback(failure.Failure()) else: d.callback(None) auth = gateway.expose_request(auth) gw = _twisted.TwistedGateway({'echo': lambda x: x}, authenticator=auth) self.service_request = gateway.ServiceRequest(None, gw.services['echo'], None) gw.authenticateRequest(self.service_request, 'u', 'p', http_request='foo') return d def test_encoding_error(self): encode = _twisted.remoting.encode def force_error(amf_request, context=None): raise pyamf.EncodeError def echo(request, data): return data self.gw.addService(echo) env = remoting.Envelope(pyamf.AMF0, pyamf.ClientTypes.Flash9) request = remoting.Request('echo', body=['hello']) env['/1'] = request d = client.getPage("http://127.0.0.1:%d/" % (self.port,), method="POST", postdata=remoting.encode(env).getvalue()) _twisted.remoting.encode = force_error def switch(x): _twisted.remoting.encode = encode d = self.assertFailure(d, error.Error) def check(exc): self.assertEquals(int(exc.args[0]), http.INTERNAL_SERVER_ERROR) self.assertTrue(exc.args[1].startswith('500 Internal Server Error')) d.addCallback(check) return d.addBoth(switch) def test_tuple(self): def echo(data): return data self.gw.addService(echo) env = remoting.Envelope(pyamf.AMF0, pyamf.ClientTypes.Flash9) request = remoting.Request('echo', body=[('Hi', 'Mom')]) env['/1'] = request d = client.getPage("http://127.0.0.1:%d/" % (self.port,), method="POST", postdata=remoting.encode(env).getvalue()) def cb(result): response = remoting.decode(result) body_response = response['/1'] self.assertEquals(body_response.status, remoting.STATUS_OK) self.assertEquals(body_response.body, ['Hi', 'Mom']) return d.addCallback(cb) def test_timezone(self): import datetime self.executed = False td = datetime.timedelta(hours=-5) now = datetime.datetime.utcnow() def echo(d): self.assertEquals(d, now + td) self.executed = True return d self.gw.addService(echo) self.gw.timezone_offset = -18000 msg = remoting.Envelope(amfVersion=pyamf.AMF0, clientType=0) msg['/1'] = remoting.Request(target='echo', body=[now]) stream = remoting.encode(msg) d = client.getPage("http://127.0.0.1:%d/" % (self.port,), method="POST", postdata=stream.getvalue()) def cb(response): envelope = remoting.decode(''.join(response)) message = envelope['/1'] self.assertEquals(message.status, remoting.STATUS_OK) self.assertEquals(message.body, now) return d.addCallback(cb) def test_double_encode(self): """ See ticket #648 """ self.counter = 0 def service(): self.counter += 1 self.gw.addService(service) env = remoting.Envelope(pyamf.AMF0, pyamf.ClientTypes.Flash9) request = remoting.Request('service') env['/1'] = request d = client.getPage("http://127.0.0.1:%d/" % (self.port,), method="POST", postdata=remoting.encode(env).getvalue()) def cb(result): self.assertEquals(self.counter, 1) return d.addCallback(cb) class DummyHTTPRequest: def __init__(self): self.headers = {} self.finished = False def setResponseCode(self, status): self.status = status def setHeader(self, n, v): self.headers[n] = v def write(self, s): self.content = s def finish(self): self.finished = True class TwistedGatewayTestCase(unittest.TestCase): def test_finalise_request(self): request = DummyHTTPRequest() gw = _twisted.TwistedGateway() gw._finaliseRequest(request, 200, 'xyz', 'text/plain') self.assertEquals(request.status, 200) self.assertEquals(request.content, 'xyz') self.assertTrue('Content-Type' in request.headers) self.assertEquals(request.headers['Content-Type'], 'text/plain') self.assertTrue('Content-Length' in request.headers) self.assertEquals(request.headers['Content-Length'], '3') self.assertTrue(request.finished) def test_get_processor(self): a3 = pyamf.ASObject({'target': 'null'}) a0 = pyamf.ASObject({'target': 'foo.bar'}) gw = _twisted.TwistedGateway() self.assertTrue(isinstance(gw.getProcessor(a3), _twisted.AMF3RequestProcessor)) self.assertTrue(isinstance(gw.getProcessor(a0), _twisted.AMF0RequestProcessor)) class AMF0RequestProcessorTestCase(unittest.TestCase): def test_unknown_service_request(self): gw = _twisted.TwistedGateway({'echo': lambda x: x}) proc = _twisted.AMF0RequestProcessor(gw) request = remoting.Request('sdf') d = proc(request) self.assertTrue(isinstance(d, defer.Deferred)) response = d.result self.assertTrue(isinstance(response, remoting.Response)) self.assertTrue(response.status, remoting.STATUS_ERROR) self.assertTrue(isinstance(response.body, remoting.ErrorFault)) def test_error_auth(self): def auth(u, p): raise IndexError gw = _twisted.TwistedGateway({'echo': lambda x: x}, authenticator=auth) proc = _twisted.AMF0RequestProcessor(gw) request = remoting.Request('echo', envelope=remoting.Envelope()) d = proc(request) self.assertTrue(isinstance(d, defer.Deferred)) response = d.result self.assertTrue(isinstance(response, remoting.Response)) self.assertTrue(response.status, remoting.STATUS_ERROR) self.assertTrue(isinstance(response.body, remoting.ErrorFault)) self.assertEquals(response.body.code, 'IndexError') def test_auth_fail(self): def auth(u, p): return False gw = _twisted.TwistedGateway({'echo': lambda x: x}, authenticator=auth) proc = _twisted.AMF0RequestProcessor(gw) request = remoting.Request('echo', envelope=remoting.Envelope()) d = proc(request) self.assertTrue(isinstance(d, defer.Deferred)) response = d.result self.assertTrue(isinstance(response, remoting.Response)) self.assertTrue(response.status, remoting.STATUS_ERROR) self.assertTrue(isinstance(response.body, remoting.ErrorFault)) self.assertEquals(response.body.code, 'AuthenticationError') def test_deferred_auth(self): d = defer.Deferred() def auth(u, p): return reactor.callLater(0, lambda: True) gw = _twisted.TwistedGateway({'echo': lambda x: x}, authenticator=auth) proc = _twisted.AMF0RequestProcessor(gw) request = remoting.Request('echo', envelope=remoting.Envelope()) def cb(result): self.assertTrue(result) d.callback(None) proc(request).addCallback(cb).addErrback(lambda failure: d.errback()) return d def test_error_preprocessor(self): def preprocessor(service_request): raise IndexError gw = _twisted.TwistedGateway({'echo': lambda x: x}, preprocessor=preprocessor) proc = _twisted.AMF0RequestProcessor(gw) request = remoting.Request('echo', envelope=remoting.Envelope()) d = proc(request) self.assertTrue(isinstance(d, defer.Deferred)) response = d.result self.assertTrue(isinstance(response, remoting.Response)) self.assertTrue(response.status, remoting.STATUS_ERROR) self.assertTrue(isinstance(response.body, remoting.ErrorFault)) self.assertEquals(response.body.code, 'IndexError') def test_deferred_preprocessor(self): d = defer.Deferred() def preprocessor(u, p): return reactor.callLater(0, lambda: True) gw = _twisted.TwistedGateway({'echo': lambda x: x}, preprocessor=preprocessor) proc = _twisted.AMF0RequestProcessor(gw) request = remoting.Request('echo', envelope=remoting.Envelope()) def cb(result): self.assertTrue(result) d.callback(None) proc(request).addCallback(cb).addErrback(lambda failure: d.errback()) return d def test_preprocessor(self): d = defer.Deferred() def preprocessor(service_request): d.callback(None) gw = _twisted.TwistedGateway({'echo': lambda x: x}, preprocessor=preprocessor) proc = _twisted.AMF0RequestProcessor(gw) request = remoting.Request('echo', envelope=remoting.Envelope()) proc(request).addErrback(lambda failure: d.errback()) return d def test_exposed_preprocessor(self): d = defer.Deferred() def preprocessor(http_request, service_request): return reactor.callLater(0, lambda: True) preprocessor = gateway.expose_request(preprocessor) gw = _twisted.TwistedGateway({'echo': lambda x: x}, preprocessor=preprocessor) proc = _twisted.AMF0RequestProcessor(gw) request = remoting.Request('echo', envelope=remoting.Envelope()) def cb(result): self.assertTrue(result) d.callback(None) proc(request).addCallback(cb).addErrback(lambda failure: d.errback()) return d def test_error_body(self): def echo(x): raise KeyError gw = _twisted.TwistedGateway({'echo': echo}) proc = _twisted.AMF0RequestProcessor(gw) request = remoting.Request('echo', envelope=remoting.Envelope()) d = proc(request) self.assertTrue(isinstance(d, defer.Deferred)) response = d.result self.assertTrue(isinstance(response, remoting.Response)) self.assertTrue(response.status, remoting.STATUS_ERROR) self.assertTrue(isinstance(response.body, remoting.ErrorFault)) self.assertEquals(response.body.code, 'KeyError') def test_error_deferred_body(self): d = defer.Deferred() def echo(x): d2 = defer.Deferred() def cb(result): raise IndexError reactor.callLater(0, lambda: d2.callback(None)) d2.addCallback(cb) return d2 gw = _twisted.TwistedGateway({'echo': echo}, expose_request=False) proc = _twisted.AMF0RequestProcessor(gw) request = remoting.Request('echo', envelope=remoting.Envelope()) request.body = ['a'] def cb(result): try: self.assertTrue(isinstance(result, remoting.Response)) self.assertTrue(result.status, remoting.STATUS_ERROR) self.assertTrue(isinstance(result.body, remoting.ErrorFault)) self.assertEquals(result.body.code, 'IndexError') except: d.errback() else: d.callback(None) proc(request).addCallback(cb).addErrback(lambda x: d.errback()) return d class AMF3RequestProcessorTestCase(unittest.TestCase): def test_unknown_service_request(self): gw = _twisted.TwistedGateway({'echo': lambda x: x}, expose_request=False) proc = _twisted.AMF3RequestProcessor(gw) request = remoting.Request('null', body=[messaging.RemotingMessage(body=['spam.eggs'], operation='ss')]) d = proc(request) self.assertTrue(isinstance(d, defer.Deferred)) response = d.result self.assertTrue(isinstance(response, remoting.Response)) self.assertTrue(response.status, remoting.STATUS_ERROR) self.assertTrue(isinstance(response.body, messaging.ErrorMessage)) def test_error_preprocessor(self): def preprocessor(service_request, *args): raise IndexError gw = _twisted.TwistedGateway({'echo': lambda x: x}, expose_request=False, preprocessor=preprocessor) proc = _twisted.AMF3RequestProcessor(gw) request = remoting.Request('null', body=[messaging.RemotingMessage(body=['spam.eggs'], operation='echo')]) d = proc(request) self.assertTrue(isinstance(d, defer.Deferred)) response = d.result self.assertTrue(isinstance(response, remoting.Response)) self.assertTrue(response.status, remoting.STATUS_ERROR) self.assertTrue(isinstance(response.body, messaging.ErrorMessage)) self.assertEquals(response.body.faultCode, 'IndexError') def test_deferred_preprocessor(self): d = defer.Deferred() def preprocessor(u, *args): d2 = defer.Deferred() reactor.callLater(0, lambda: d2.callback(None)) return d2 gw = _twisted.TwistedGateway({'echo': lambda x: x}, expose_request=False, preprocessor=preprocessor) proc = _twisted.AMF3RequestProcessor(gw) request = remoting.Request('null', body=[messaging.RemotingMessage(body=['spam.eggs'], operation='echo')]) def cb(result): self.assertTrue(result) d.callback(None) proc(request).addCallback(cb).addErrback(lambda failure: d.errback()) return d def test_preprocessor(self): d = defer.Deferred() def preprocessor(service_request, *args): d.callback(None) gw = _twisted.TwistedGateway({'echo': lambda x: x}, expose_request=False, preprocessor=preprocessor) proc = _twisted.AMF3RequestProcessor(gw) request = remoting.Request('null', body=[messaging.RemotingMessage(body=['spam.eggs'], operation='echo')]) proc(request).addErrback(lambda failure: d.errback()) return d def test_exposed_preprocessor(self): d = defer.Deferred() def preprocessor(http_request, service_request): return reactor.callLater(0, lambda: True) preprocessor = gateway.expose_request(preprocessor) gw = _twisted.TwistedGateway({'echo': lambda x: x}, expose_request=False, preprocessor=preprocessor) proc = _twisted.AMF3RequestProcessor(gw) request = remoting.Request('null', body=[messaging.RemotingMessage(body=['spam.eggs'], operation='echo')]) def cb(result): try: self.assertTrue(result) except: d.errback() else: d.callback(None) proc(request).addCallback(cb).addErrback(lambda failure: d.errback()) return d def test_error_body(self): def echo(x): raise KeyError gw = _twisted.TwistedGateway({'echo': echo}, expose_request=False) proc = _twisted.AMF3RequestProcessor(gw) request = remoting.Request('null', body=[messaging.RemotingMessage(body=['spam.eggs'], operation='echo')]) d = proc(request) self.assertTrue(isinstance(d, defer.Deferred)) response = d.result self.assertTrue(isinstance(response, remoting.Response)) self.assertTrue(response.status, remoting.STATUS_ERROR) self.assertTrue(isinstance(response.body, messaging.ErrorMessage)) self.assertEquals(response.body.faultCode, 'KeyError') def test_error_deferred_body(self): d = defer.Deferred() def echo(x): d2 = defer.Deferred() def cb(result): raise IndexError reactor.callLater(0, lambda: d2.callback(None)) d2.addCallback(cb) return d2 gw = _twisted.TwistedGateway({'echo': echo}, expose_request=False) proc = _twisted.AMF3RequestProcessor(gw) request = remoting.Request('null', body=[messaging.RemotingMessage(body=['spam.eggs'], operation='echo')]) def cb(result): try: self.assertTrue(isinstance(result, remoting.Response)) self.assertTrue(result.status, remoting.STATUS_ERROR) self.assertTrue(isinstance(result.body, messaging.ErrorMessage)) self.assertEquals(result.body.faultCode, 'IndexError') except: d.errback() else: d.callback(None) proc(request).addCallback(cb).addErrback(lambda x: d.errback()) return d def test_destination(self): d = defer.Deferred() gw = _twisted.TwistedGateway({'spam.eggs': lambda x: x}, expose_request=False) proc = _twisted.AMF3RequestProcessor(gw) request = remoting.Request('null', body=[messaging.RemotingMessage(body=[None], destination='spam', operation='eggs')]) def cb(result): try: self.assertTrue(result) except: d.errback() else: d.callback(None) proc(request).addCallback(cb).addErrback(lambda failure: d.errback()) return d def test_async(self): d = defer.Deferred() gw = _twisted.TwistedGateway({'spam.eggs': lambda x: x}, expose_request=False) proc = _twisted.AMF3RequestProcessor(gw) request = remoting.Request('null', body=[messaging.AsyncMessage(body=[None], destination='spam', operation='eggs')]) def cb(result): msg = result.body try: self.assertTrue(isinstance(msg, messaging.AcknowledgeMessage)) except: d.errback() else: d.callback(None) proc(request).addCallback(cb).addErrback(lambda failure: d.errback()) return d def suite(): import unittest suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TwistedServerTestCase)) suite.addTest(unittest.makeSuite(TwistedGatewayTestCase)) suite.addTest(unittest.makeSuite(AMF0RequestProcessorTestCase)) suite.addTest(unittest.makeSuite(AMF3RequestProcessorTestCase)) return suite if __name__ == '__main__': unittest.main(defaultTest='suite') PK:u3;[,,!pyamf/tests/gateway/test_wsgi.pyc; DȠJc@sdZdkZdkZdklZlZdklZdeifdYZdZ e djoei dd ndS( s$ WSGI gateway tests. @since: 0.1.0 N(sremotingsutil(s WSGIGatewaysWSGIServerTestCasecBsbtZdZdZdZdZdZdZdZdZ d Z d Z RS( NcCst|_t|_dS(N(s WSGIGatewaysselfsgwsFalsesexecuted(sself((s=build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_wsgi.pyssetUps cs^d}ihdd<|iiitihdd!s(s bad_responsesselfsgws assertTruesexecuteds assertRaisessKeyError(sselfs bad_response((sselfs=build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_wsgi.pystest_request_methods  csti}|id|iddhdd<dtt|<d|<}d}i ||i i dS(Ns Bad requestisREQUEST_METHODsPOSTsCONTENT_LENGTHs wsgi.inputcsi|dt_dS(Ns400 Bad Request(sselfs assertEqualssstatussTruesexecuted(sstatussheaders(sself(s=build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_wsgi.pysstart_response.s( sutilsBufferedByteStreamsrequestswritesseeksstrslensenvsstart_responsesselfsgws assertTruesexecuted(sselfsenvsstart_responsesrequest((sselfs=build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_wsgi.pystest_bad_request#s  - csti}|id|iddhdd<dtt|<d|<}d}i ||}t i di|}|d }i|it i|i}it|t ii|id iidS( Ns- test.test/1 aa isREQUEST_METHODsPOSTsCONTENT_LENGTHs wsgi.inputcs6t_i|diddf|jdS(Ns200 OKs Content-Typesapplication/x-amf(sTruesselfsexecuteds assertEqualssstatuss assertTruesheaders(sstatussheaders(sself(s=build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_wsgi.pysstart_responseBs ss/1sService.ResourceNotFound(sutilsBufferedByteStreamsrequestswritesseeksstrslensenvsstart_responsesselfsgwsresponsesremotingsdecodesjoinsenvelopesmessages assertEqualssstatuss STATUS_ERRORsbodys assertTrues isinstances ErrorFaultscodesexecuted(sselfsbodysenvsstart_responsesenvelopesrequestsmessagesresponse((sselfs=build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_wsgi.pystest_unknown_request5s  -   cs~ti}hdd<dtt|<d|<}d}i||}i |dgi i dS(NsREQUEST_METHODsPOSTsCONTENT_LENGTHs wsgi.inputcs6t_i|diddf|jdS(Ns400 Bad Requests Content-Types text/plain(sTruesselfsexecuteds assertEqualssstatuss assertTruesheaders(sstatussheaders(sself(s=build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_wsgi.pysstart_response\s sH400 Bad Request The request body was unable to be successfully decoded.( sutilsBufferedByteStreamsrequestsstrslensenvsstart_responsesselfsgwsresponses assertEqualss assertTruesexecuted(sselfsenvsstart_responsesrequestsresponse((sselfs=build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_wsgi.pystest_eof_decodeSs  - cOs |dS(N(se(sselfsesargsskwargs((s=build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_wsgi.pys_raiseExceptionfscsti_dt_ti}hdd<dtt|<d|<}d}yi ||}Wnit_nXit_i |dgiidS(Ncsit||S(N(sselfs_raiseExceptions Exceptionsargsskwargs(sargsskwargs(sself(s=build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_wsgi.pyskssREQUEST_METHODsPOSTsCONTENT_LENGTHs wsgi.inputcs6t_i|diddf|jdS(Ns500 Internal Server Errors Content-Types text/plain(sTruesselfsexecuteds assertEqualssstatuss assertTruesheaders(sstatussheaders(sself(s=build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_wsgi.pysstart_responseus sH500 Internal Server Error An unexpected error occurred whilst decoding.(sremotingsdecodesselfs old_methodsutilsBufferedByteStreamsrequestsstrslensenvsstart_responsesgwsresponses assertEqualss assertTruesexecuted(sselfsenvsstart_responsesrequestsresponse((sselfs=build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_wsgi.pystest_really_bad_decodeis  -   csti_hdd<dd<dti<}yIxBttfD]4dt_i i |dqCWWnit_nXit_dS(NsREQUEST_METHODsPOSTsCONTENT_LENGTHs0s wsgi.inputcsi||S(N(sselfs_raiseExceptionsxsargsskwargs(sargsskwargs(sxsself(s=build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_wsgi.pysscGs|S(N(sargs(sargs((s=build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_wsgi.pyss( sremotingsdecodesselfs old_methodsutilsBufferedByteStreamsenvsKeyboardInterrupts SystemExitsxs assertRaisessgw(sselfsenvsx((sselfsxs=build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_wsgi.pystest_expected_exceptions_decodes ' $ csti_t_titi ti i }ti dddg}||ds(sTruesselfsgwsexpose_requestsFalsesexecutedsremotingsEnvelopespyamfsAMF0s ClientTypessFlash9senvsRequestsrequestsencodesstrslensechos addServicesresponses assertTrue(sselfsrequestsechosenvsresponse((sselfs=build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_wsgi.pystest_expose_requests   - c s%dk}t_|idd|iid}i i |di _ t i dtidd}t idd d g|d ss(sdatetimesFalsesselfsexecuteds timedeltastdsutcnowsnowsechosgws addServicestimezone_offsetsremotingsEnvelopespyamfsAMF0smsgsRequestsencodesstreamsstrslensenvsresponsesdecodesjoinsenvelopesmessages assertEqualssbody( sselfsstreamsdatetimesenvelopesechosmessagesenvsresponsesmsgstdsnow((sselfsnowstds=build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_wsgi.pys test_timezones   - ( s__name__s __module__ssetUpstest_request_methodstest_bad_requeststest_unknown_requeststest_eof_decodes_raiseExceptionstest_really_bad_decodestest_expected_exceptions_decodestest_expose_requests test_timezone(((s=build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_wsgi.pysWSGIServerTestCases        "cCs*ti}|itit|SdS(N(sunittests TestSuitessuitesaddTests makeSuitesWSGIServerTestCase(ssuite((s=build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_wsgi.pyssuites s__main__s defaultTestssuite( s__doc__sunittestspyamfsremotingsutilspyamf.remoting.gateway.wsgis WSGIGatewaysTestCasesWSGIServerTestCasessuites__name__smain(sremotingsWSGIServerTestCasesunittestsutilssuitespyamfs WSGIGateway((s=build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_wsgi.pys? s     PK:u3;T#pyamf/tests/gateway/test_google.pyc; DȠJc@sdZdkZdklZdklZdkZdklZdklZ dei fdYZ dZ e d joeid d ndS( s. Google Web App gateway tests. @since: 0.3.1 N(sStringIO(swebapp(sremoting(sgooglesWebAppGatewayTestCasecBs>tZdZdZdZdZdZdZRS(NcCstii|ti|_hdt<dt<|_t i |i|_ t i |_ |ii|i |i dS(Ns wsgi.inputs wsgi.output(sunittestsTestCasessetUpsselfs_googles WebAppGatewaysgwsStringIOsenvironswebappsRequestsrequestsResponsesresponses initialize(sself((s?build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_google.pyssetUps !cCs/|ii|i|iiddddS(Ns_Response__statusii(sselfsgwsgets assertEqualssresponses__dict__(sself((s?build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_google.pystest_get's cCsZ|idid|ididd|ii|i|iiddddS(Ns wsgi.inputs Bad requestis_Response__statusi( sselfsenvironswritesseeksgwsposts assertEqualssresponses__dict__(sself((s?build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_google.pystest_bad_request,s cCs|idid|ididd|ii|i|iidddt i |ii i }|d}|i|it i|i}|it|t i|i|iddS(Ns wsgi.inputs- test.test/1 aa is_Response__statusis/1sService.ResourceNotFound(sselfsenvironswritesseeksgwsposts assertEqualssresponses__dict__sremotingsdecodesoutsgetvaluesenvelopesmessagesstatuss STATUS_ERRORsbodys assertTrues isinstances ErrorFaultscode(sselfsbodysenvelopesmessage((s?build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_google.pystest_unknown_request3s   cst_d}ti_ii|didi didi ddii i idS(Ncs9ii|itidt_dS(Ns amf_request(sselfs assertEqualssrequests assertTrueshasattrsTruesexecuted(srequest(sself(s?build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_google.pystestJss test.tests wsgi.inputs test.test/1 i( sFalsesselfsexecutedstestsTruesgwsexpose_requests addServicesenvironswritesseeksposts assertTrue(sselfstest((sselfs?build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_google.pystest_expose_requestGs    c sdk}t_|idd|iid}i i |di _ t i dtidd}t idd d g|d ssPOSTsis8500 Internal Server Error An unexpected error occurred.(sremotingsdecodesselfs old_methods HttpRequests http_requestsmethods raw_post_datas_djangos DjangoGatewaysgws http_responses assertTrues isinstanceshttpsHttpResponseServerErrors assertEqualss status_codescontent(sselfsgws http_requests http_response((sselfs?build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_django.pystest_really_bad_decodes       csti_ti}t}d|_ d|_ y@x9t t fD]+dt_i||qCWWnit_nXit_dS(NsPOSTscsi||S(N(sselfs_raiseExceptionsxsargsskwargs(sargsskwargs(sxsself(s?build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_django.pyss(sremotingsdecodesselfs old_methods_djangos DjangoGatewaysgws HttpRequests http_requestsmethods raw_post_datasKeyboardInterrupts SystemExitsxs assertRaises(sselfsgws http_requestsx((sselfsxs?build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_django.pystest_expected_exceptions_decodes       c sdk}t}t_|idd|iid}t i hd|1sN( sclientsgetPagesselfsportsds assertFailureserrorsErrors addCallback(sselfsd((sselfs@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pystest_invalid_method*s csUtidifdddd}i|ti}|id|SdS(Nshttp://127.0.0.1:%d/smethodsPOSTspostdatas spamandeggscs it|idtiS(Ni(sselfs assertEqualssintsexcsargsshttps BAD_REQUEST(sexc(sself(s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pys:s( sclientsgetPagesselfsportsds assertFailureserrorsErrors addCallback(sselfsd((sselfs@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pystest_bad_content5s csd}ii|tititii }ti dddg}||ds  ! csd}ii|tititii }ti dddg}||ds(sTruesselfsgwsexpose_requestsFalsesexecutedsremotingsEnvelopespyamfsAMF0s ClientTypessFlash9senvsRequestsrequestsechos addServicesclientsgetPagesportsencodesgetvaluesds addCallback(sselfsdsrequestsechosenv((sselfsrequests@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pystest_expose_requests    !csstid}tihddss preprocessor(sdefersDeferredsdspps_twistedsTwistedGatewaysgwsgatewaysServiceRequestsNonesservicessselfsservice_requestspreprocessRequest(sselfsgwsppsd((sselfsds@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pystest_preprocessors  !cstid}ti|}tihddss preprocessors http_requestshello(sdefersDeferredsdsppsgatewaysexpose_requests_twistedsTwistedGatewaysgwsServiceRequestsNonesservicessselfsservice_requestspreprocessRequest(sselfsgwsppsd((sselfsds@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pystest_exposed_preprocessors !cstid}ti|}tihddss preprocessor(sdefersDeferredsdsppsgatewaysexpose_requests_twistedsTwistedGatewaysgwsServiceRequestsNonesservicessselfsservice_requestspreprocessRequest(sselfsgwsppsd((sselfsds@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pys$test_exposed_preprocessor_no_requests !csytid}tihddss authenticatorsusp(sdefersDeferredsdsauths_twistedsTwistedGatewaysgwsgatewaysServiceRequestsNonesservicessselfsservice_requestsauthenticateRequest(sselfsgwsdsauth((sselfsds@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pystest_authenticates   !cstid}ti|}tihddss authenticatorsusps http_requestsfoo(sdefersDeferredsdsauthsgatewaysexpose_requests_twistedsTwistedGatewaysgwsServiceRequestsNonesservicessselfsservice_requestsauthenticateRequest(sselfsgwsdsauth((sselfsds@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pystest_exposed_authenticates  !c stiitd}d}ii|ti t i t i i }tidddg}||ds is amfVersions clientTypeistargetsechosbodys/1shttp://127.0.0.1:%d/smethodsPOSTspostdatacsOtidi|}|d}i|iti i|i dS(Nss/1( sremotingsdecodesjoinsresponsesenvelopesmessagesselfs assertEqualssstatuss STATUS_OKsbodysnow(sresponsesenvelopesmessage(sselfsnow(s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pyscbOs (sdatetimesFalsesselfsexecuteds timedeltastdsutcnowsnowsechosgws addServicestimezone_offsetsremotingsEnvelopespyamfsAMF0smsgsRequestsencodesstreamsclientsgetPagesportsgetvaluesdscbs addCallback( sselfsdsstreamsdatetimescbsechosmsgstdsnow((sselfsnowstds@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pys test_timezone6s   csd_d}ii|tititi i }ti d}||dsssdf(s_twistedsTwistedGatewaysgwsAMF0RequestProcessorsprocsremotingsRequestsrequestsdsselfs assertTrues isinstancesdefersDeferredsresultsresponsesResponsesstatuss STATUS_ERRORsbodys ErrorFault(sselfsgwsdsrequestsprocsresponse((s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pystest_unknown_service_requests  cCsd}tihddss authenticatorsenvelopes IndexError(sauths_twistedsTwistedGatewaysgwsAMF0RequestProcessorsprocsremotingsRequestsEnvelopesrequestsdsselfs assertTrues isinstancesdefersDeferredsresultsresponsesResponsesstatuss STATUS_ERRORsbodys ErrorFaults assertEqualsscode(sselfsgwsdsrequestsauthsprocsresponse((s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pystest_error_auths !  cCsd}tihddss authenticatorsenvelopesAuthenticationError(sauths_twistedsTwistedGatewaysgwsAMF0RequestProcessorsprocsremotingsRequestsEnvelopesrequestsdsselfs assertTrues isinstancesdefersDeferredsresultsresponsesResponsesstatuss STATUS_ERRORsbodys ErrorFaults assertEqualsscode(sselfsgwsdsrequestsauthsprocsresponse((s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pystest_auth_fails !  cstid}tihdds(sreactors callLater(susp((s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pysauthssechocCs|S(N(sx(sx((s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pysss authenticatorsenvelopecsi|itdS(N(sselfs assertTruesresultsdscallbacksNone(sresult(sselfsd(s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pyscbs cs iS(N(sdserrback(sfailure(sd(s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pyss(sdefersDeferredsdsauths_twistedsTwistedGatewaysgwsAMF0RequestProcessorsprocsremotingsRequestsEnvelopesrequestscbs addCallbacks addErrback(sselfsgwsdscbsrequestsauthsproc((sselfsds@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pystest_deferred_auths  !"cCsd}tihddss preprocessorsenvelopes IndexError(s preprocessors_twistedsTwistedGatewaysgwsAMF0RequestProcessorsprocsremotingsRequestsEnvelopesrequestsdsselfs assertTrues isinstancesdefersDeferredsresultsresponsesResponsesstatuss STATUS_ERRORsbodys ErrorFaults assertEqualsscode(sselfsgwsdsrequests preprocessorsprocsresponse((s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pystest_error_preprocessors !  cstid}tihdds(sreactors callLater(susp((s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pys preprocessorssechocCs|S(N(sx(sx((s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pysss preprocessorsenvelopecsi|itdS(N(sselfs assertTruesresultsdscallbacksNone(sresult(sselfsd(s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pyscbs cs iS(N(sdserrback(sfailure(sd(s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pyss(sdefersDeferredsds preprocessors_twistedsTwistedGatewaysgwsAMF0RequestProcessorsprocsremotingsRequestsEnvelopesrequestscbs addCallbacks addErrback(sselfsgwsdscbsrequests preprocessorsproc((sselfsds@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pystest_deferred_preprocessors  !"cstid}tihddss preprocessorsenvelopecs iS(N(sdserrback(sfailure(sd(s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pyss(sdefersDeferredsds preprocessors_twistedsTwistedGatewaysgwsAMF0RequestProcessorsprocsremotingsRequestsEnvelopesrequests addErrback(sselfsgwsdsrequests preprocessorsproc((sds@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pystest_preprocessors  !cstid}ti|}tihdds(sreactors callLater(s http_requestsservice_request((s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pys preprocessorssechocCs|S(N(sx(sx((s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pysss preprocessorsenvelopecsi|itdS(N(sselfs assertTruesresultsdscallbacksNone(sresult(sselfsd(s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pyscb#s cs iS(N(sdserrback(sfailure(sd(s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pys's(sdefersDeferredsds preprocessorsgatewaysexpose_requests_twistedsTwistedGatewaysgwsAMF0RequestProcessorsprocsremotingsRequestsEnvelopesrequestscbs addCallbacks addErrback(sselfsgwsdscbsrequests preprocessorsproc((sselfsds@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pystest_exposed_preprocessors  !"cCsd}tihd|<}ti|}tiddti}||}|i t |ti|i}|i t |ti|i |iti|i t |iti|i|iiddS(NcCs tdS(N(sKeyError(sx((s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pysecho,ssechosenvelopesKeyError(sechos_twistedsTwistedGatewaysgwsAMF0RequestProcessorsprocsremotingsRequestsEnvelopesrequestsdsselfs assertTrues isinstancesdefersDeferredsresultsresponsesResponsesstatuss STATUS_ERRORsbodys ErrorFaults assertEqualsscode(sselfsgwsdsrequestsechosprocsresponse((s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pystest_error_body+s   cstid}tihd|Fs(sdefersDeferredsd2scbsreactors callLaters addCallback(sxscbsd2((sd2s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pysecho@s    sechosexpose_requestsenvelopesacsyeit|tii|itiit|iti i |ii dWni nXitdS(Ns IndexError(sselfs assertTrues isinstancesresultsremotingsResponsesstatuss STATUS_ERRORsbodys ErrorFaults assertEqualsscodesdserrbackscallbacksNone(sresult(sdsself(s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pyscbQscs iS(N(sdserrback(sx(sd(s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pys\s(sdefersDeferredsdsechos_twistedsTwistedGatewaysFalsesgwsAMF0RequestProcessorsprocsremotingsRequestsEnvelopesrequestsbodyscbs addCallbacks addErrback(sselfsgwsdscbsrequestsechosproc((sselfsds@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pystest_error_deferred_body=s    "( s__name__s __module__stest_unknown_service_requeststest_error_authstest_auth_failstest_deferred_authstest_error_preprocessorstest_deferred_preprocessorstest_preprocessorstest_exposed_preprocessorstest_error_bodystest_error_deferred_body(((s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pysAMF0RequestProcessorTestCases         sAMF3RequestProcessorTestCasecBsYtZdZdZdZdZdZdZdZdZ d Z RS( NcCstihddcssexpose_requestsnullsbodys spam.eggss operationsss(s_twistedsTwistedGatewaysFalsesgwsAMF3RequestProcessorsprocsremotingsRequests messagingsRemotingMessagesrequestsdsselfs assertTrues isinstancesdefersDeferredsresultsresponsesResponsesstatuss STATUS_ERRORsbodys ErrorMessage(sselfsgwsdsrequestsprocsresponse((s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pystest_unknown_service_requestbs!-  cCsd}tihddtssexpose_requests preprocessorsnullsbodys spam.eggss operations IndexError(s preprocessors_twistedsTwistedGatewaysFalsesgwsAMF3RequestProcessorsprocsremotingsRequests messagingsRemotingMessagesrequestsdsselfs assertTrues isinstancesdefersDeferredsresultsresponsesResponsesstatuss STATUS_ERRORsbodys ErrorMessages assertEqualss faultCode(sselfsgwsdsrequests preprocessorsprocsresponse((s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pystest_error_preprocessorps -  cstid}tihdds(sdefersDeferredsd2sreactors callLater(susargssd2((sd2s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pys preprocessors sechocCs|S(N(sx(sx((s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pysssexpose_requests preprocessorsnullsbodys spam.eggss operationcsi|itdS(N(sselfs assertTruesresultsdscallbacksNone(sresult(sselfsd(s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pyscbs cs iS(N(sdserrback(sfailure(sd(s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pyss(sdefersDeferredsds preprocessors_twistedsTwistedGatewaysFalsesgwsAMF3RequestProcessorsprocsremotingsRequests messagingsRemotingMessagesrequestscbs addCallbacks addErrback(sselfsgwsdscbsrequests preprocessorsproc((sselfsds@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pystest_deferred_preprocessors  '-"c stid}tihddssexpose_requests preprocessorsnullsbodys spam.eggss operationcs iS(N(sdserrback(sfailure(sd(s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pyss(sdefersDeferredsds preprocessors_twistedsTwistedGatewaysFalsesgwsAMF3RequestProcessorsprocsremotingsRequests messagingsRemotingMessagesrequests addErrback(sselfsgwsdsrequests preprocessorsproc((sds@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pystest_preprocessors  '-cstid}ti|}tihdds(sreactors callLater(s http_requestsservice_request((s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pys preprocessorssechocCs|S(N(sx(sx((s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pysssexpose_requests preprocessorsnullsbodys spam.eggss operationcs6yi|WninXitdS(N(sselfs assertTruesresultsdserrbackscallbacksNone(sresult(sselfsd(s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pyscbs cs iS(N(sdserrback(sfailure(sd(s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pyss(sdefersDeferredsds preprocessorsgatewaysexpose_requests_twistedsTwistedGatewaysFalsesgwsAMF3RequestProcessorsprocsremotingsRequests messagingsRemotingMessagesrequestscbs addCallbacks addErrback(sselfsgwsdscbsrequests preprocessorsproc((sselfsds@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pystest_exposed_preprocessors  '-"cCsd}tihd|s(sdefersDeferredsd2scbsreactors callLaters addCallback(sxscbsd2((sd2s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pysechos    sechosexpose_requestsnullsbodys spam.eggss operationcsyeit|tii|itiit|it i i |ii dWninXitdS(Ns IndexError(sselfs assertTrues isinstancesresultsremotingsResponsesstatuss STATUS_ERRORsbodys messagings ErrorMessages assertEqualss faultCodesdserrbackscallbacksNone(sresult(sdsself(s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pyscbscs iS(N(sdserrback(sx(sd(s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pyss(sdefersDeferredsdsechos_twistedsTwistedGatewaysFalsesgwsAMF3RequestProcessorsprocsremotingsRequests messagingsRemotingMessagesrequestscbs addCallbacks addErrback(sselfsgwsdscbsrequestsechosproc((sselfsds@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pystest_error_deferred_bodys  - "c stitihddssexpose_requestsnullsbodys destinationsspams operationseggscs6yi|WninXitdS(N(sselfs assertTruesresultsdserrbackscallbacksNone(sresult(sselfsd(s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pyscbs cs iS(N(sdserrback(sfailure(sd(s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pyss(sdefersDeferredsds_twistedsTwistedGatewaysFalsesgwsAMF3RequestProcessorsprocsremotingsRequests messagingsRemotingMessagesNonesrequestscbs addCallbacks addErrback(sselfsgwsdscbsrequestsproc((sselfsds@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pystest_destinations !3"c stitihdd ssexpose_requestsnullsbodys destinationsspams operationseggscsK|i}yit|tiWni nXi t dS(N( sresultsbodysmsgsselfs assertTrues isinstances messagingsAcknowledgeMessagesdserrbackscallbacksNone(sresultsmsg(sdsself(s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pyscbs  cs iS(N(sdserrback(sfailure(sd(s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pyss(sdefersDeferredsds_twistedsTwistedGatewaysFalsesgwsAMF3RequestProcessorsprocsremotingsRequests messagings AsyncMessagesNonesrequestscbs addCallbacks addErrback(sselfsgwsdscbsrequestsproc((sselfsds@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pys test_asyncs !3 "( s__name__s __module__stest_unknown_service_requeststest_error_preprocessorstest_deferred_preprocessorstest_preprocessorstest_exposed_preprocessorstest_error_bodystest_error_deferred_bodystest_destinations test_async(((s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pysAMF3RequestProcessorTestCaseas       " cCsudk}|i}|i|it|i|it|i|it|i|it|SdS(N( sunittests TestSuitessuitesaddTests makeSuitesTwistedServerTestCasesTwistedGatewayTestCasesAMF0RequestProcessorTestCasesAMF3RequestProcessorTestCase(sunittestssuite((s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pyssuites  s__main__s defaultTestssuite("s__doc__stwisted.internetsreactorsdeferstwisted.pythonsfailures twisted.webshttpsserversclientserrorsresources twisted.trialsunittestspyamfsremotingspyamf.remotingsgateways pyamf.flexs messagingspyamf.remoting.gatewaystwisteds_twistedsobjects TestServicesTestCasesTwistedServerTestCasesDummyHTTPRequestsTwistedGatewayTestCasesAMF0RequestProcessorTestCasesAMF3RequestProcessorTestCasessuites__name__smain(sdefersremotingsreactorsAMF0RequestProcessorTestCasesunittests_twistedsgatewayserrorssuitespyamfshttpsAMF3RequestProcessorTestCasesTwistedGatewayTestCasesfailures TestServicesresourcesserversTwistedServerTestCasesclientsDummyHTTPRequests messaging((s@build/bdist.linux-x86_64/egg/pyamf/tests/gateway/test_twisted.pys?s& %      S PK;C[k#pyamf/tests/adapters/test_google.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ PyAMF Google adapter tests. @since: 0.3.1 """ import unittest import datetime import struct from google.appengine.ext import db from google.appengine.ext.db import polymodel import pyamf from pyamf import amf3 from pyamf.tests.util import ClassCacheClearingTestCase, Spam from pyamf.adapters import _google_appengine_ext_db as adapter_db class PetModel(db.Model): # 'borrowed' from http://code.google.com/appengine/docs/datastore/entitiesandmodels.html name = db.StringProperty(required=True) type = db.StringProperty(required=True, choices=set(["cat", "dog", "bird"])) birthdate = db.DateProperty() weight_in_pounds = db.IntegerProperty() spayed_or_neutered = db.BooleanProperty() class PetExpando(db.Expando): name = db.StringProperty(required=True) type = db.StringProperty(required=True, choices=set(["cat", "dog", "bird"])) birthdate = db.DateProperty() weight_in_pounds = db.IntegerProperty() spayed_or_neutered = db.BooleanProperty() class EncodingModelTestCase(ClassCacheClearingTestCase): def setUp(self): ClassCacheClearingTestCase.setUp(self) self.jessica = PetModel(name='Jessica', type='cat') self.jessica.birthdate = datetime.date(1986, 10, 2) self.jessica.weight_in_pounds = 5 self.jessica.spayed_or_neutered = False def tearDown(self): ClassCacheClearingTestCase.tearDown(self) try: self.jessica.delete() except: pass def test_amf0(self): encoder = pyamf.get_encoder(pyamf.AMF0) context = encoder.context alias = context.getClassAlias(PetModel) self.assertEquals(alias.__class__, adapter_db.DataStoreClassAlias) encoder.writeElement(self.jessica) self.assertEquals(encoder.stream.getvalue(), '\x03\x00\x04_key\x05\x00\tbirthdate\x0bB^\xc4\xae\xaa\x00\x00' '\x00\x00\x00\x00\x04name\x02\x00\x07Jessica\x00\x12' 'spayed_or_neutered\x01\x00\x00\x04type\x02\x00\x03cat\x00\x10' 'weight_in_pounds\x00@\x14\x00\x00\x00\x00\x00\x00\x00\x00\t') def test_amf3(self): encoder = pyamf.get_encoder(pyamf.AMF3) encoder.writeElement(self.jessica) self.assertEquals(encoder.stream.getvalue(), '\nk\x01\t_key\x13birthdate\tname%spayed_or_neutered\ttype!' 'weight_in_pounds\x01\x08\x01B^\xc4\xae\xaa\x00\x00\x00\x06\x0f' 'Jessica\x02\x06\x07cat\x04\x05\x01') def test_save_amf0(self): self.jessica.put() k = str(self.jessica.key()) encoder = pyamf.get_encoder(pyamf.AMF0) encoder.writeElement(self.jessica) self.assertEquals(encoder.stream.getvalue(), '\x03\x00\x04_key\x02%s%s\x00\tbirthdate\x0bB^\xc4\xae\xaa\x00' '\x00\x00\x00\x00\x00\x04name\x02\x00\x07Jessica\x00\x12' 'spayed_or_neutered\x01\x00\x00\x04type\x02\x00\x03cat\x00\x10' 'weight_in_pounds\x00@\x14\x00\x00\x00\x00\x00\x00\x00\x00\t' % ( struct.pack('>H', len(k)), k)) def test_save_amf3(self): self.jessica.put() k = str(self.jessica.key()) encoder = pyamf.get_encoder(pyamf.AMF3) encoder.writeElement(self.jessica) self.assertEquals(encoder.stream.getvalue(), '\nk\x01\t_key\x13birthdate\tname%%spayed_or_neutered\ttype!' 'weight_in_pounds\x06%s%s\x08\x01B^\xc4\xae\xaa\x00\x00\x00\x06' '\x0fJessica\x02\x06\x07cat\x04\x05\x01' % ( amf3.encode_int(len(k) << 1 | amf3.REFERENCE_BIT), k)) def test_alias_amf0(self): pyamf.register_class(PetModel, 'Pet') encoder = pyamf.get_encoder(pyamf.AMF0) encoder.writeElement(self.jessica) self.assertEquals(encoder.stream.getvalue(), '\x10\x00\x03Pet\x00\x04_key\x05\x00\tbirthdate\x0bB^\xc4\xae\xaa' '\x00\x00\x00\x00\x00\x00\x04name\x02\x00\x07Jessica\x00\x12' 'spayed_or_neutered\x01\x00\x00\x04type\x02\x00\x03cat\x00\x10' 'weight_in_pounds\x00@\x14\x00\x00\x00\x00\x00\x00\x00\x00\t') def test_alias_amf3(self): pyamf.register_class(PetModel, 'Pet') encoder = pyamf.get_encoder(pyamf.AMF3) encoder.writeElement(self.jessica) self.assertEquals(encoder.stream.getvalue(), '\nk\x07Pet\t_key\x13birthdate\tname%spayed_or_neutered\ttype!' 'weight_in_pounds\x01\x08\x01B^\xc4\xae\xaa\x00\x00\x00\x06\x0f' 'Jessica\x02\x06\x07cat\x04\x05\x01') class EncodingExpandoTestCase(ClassCacheClearingTestCase): def setUp(self): ClassCacheClearingTestCase.setUp(self) self.jessica = PetExpando(name='Jessica', type='cat') self.jessica.birthdate = datetime.date(1986, 10, 2) self.jessica.weight_in_pounds = 5 self.jessica.spayed_or_neutered = False self.jessica.foo = 'bar' def tearDown(self): ClassCacheClearingTestCase.tearDown(self) try: self.jessica.delete() except: pass def test_amf0(self): encoder = pyamf.get_encoder(pyamf.AMF0) encoder.writeElement(self.jessica) self.assertEquals(encoder.stream.getvalue(), '\x03\x00\x04_key\x05\x00\tbirthdate\x0bB^\xc4\xae\xaa\x00\x00' '\x00\x00\x00\x00\x04name\x02\x00\x07Jessica\x00\x12' 'spayed_or_neutered\x01\x00\x00\x04type\x02\x00\x03cat\x00\x10' 'weight_in_pounds\x00@\x14\x00\x00\x00\x00\x00\x00\x00\x03foo\x02' '\x00\x03bar\x00\x00\t') def test_amf3(self): encoder = pyamf.get_encoder(pyamf.AMF3) encoder.writeElement(self.jessica) self.assertEquals(encoder.stream.getvalue(), '\nk\x01\t_key\x13birthdate\tname%spayed_or_neutered\ttype!' 'weight_in_pounds\x01\x08\x01B^\xc4\xae\xaa\x00\x00\x00\x06\x0f' 'Jessica\x02\x06\x07cat\x04\x05\x07foo\x06\x07bar\x01') def test_save_amf0(self): self.jessica.put() k = str(self.jessica.key()) encoder = pyamf.get_encoder(pyamf.AMF0) encoder.writeElement(self.jessica) self.assertEquals(encoder.stream.getvalue(), '\x03\x00\x04_key\x02%s%s\x00\tbirthdate\x0bB^\xc4\xae\xaa\x00' '\x00\x00\x00\x00\x00\x04name\x02\x00\x07Jessica\x00\x12' 'spayed_or_neutered\x01\x00\x00\x04type\x02\x00\x03cat\x00\x10' 'weight_in_pounds\x00@\x14\x00\x00\x00\x00\x00\x00\x00\x03foo\x02' '\x00\x03bar\x00\x00\t' % (struct.pack('>H', len(k)), k)) def test_save_amf3(self): self.jessica.put() k = str(self.jessica.key()) encoder = pyamf.get_encoder(pyamf.AMF3) encoder.writeElement(self.jessica) self.assertEquals(encoder.stream.getvalue(), '\nk\x01\t_key\x13birthdate\tname%%spayed_or_neutered\ttype!' 'weight_in_pounds\x06%s%s\x08\x01B^\xc4\xae\xaa\x00\x00\x00\x06' '\x0fJessica\x02\x06\x07cat\x04\x05\x07foo\x06\x07bar\x01' % ( amf3.encode_int(len(k) << 1 | amf3.REFERENCE_BIT), k)) def test_alias_amf0(self): pyamf.register_class(PetExpando, 'Pet') encoder = pyamf.get_encoder(pyamf.AMF0) encoder.writeElement(self.jessica) self.assertEquals(encoder.stream.getvalue(), '\x10\x00\x03Pet\x00\x04_key\x05\x00\tbirthdate\x0bB^\xc4\xae\xaa' '\x00\x00\x00\x00\x00\x00\x04name\x02\x00\x07Jessica\x00\x12' 'spayed_or_neutered\x01\x00\x00\x04type\x02\x00\x03cat\x00\x10' 'weight_in_pounds\x00@\x14\x00\x00\x00\x00\x00\x00\x00\x03foo\x02' '\x00\x03bar\x00\x00\t') def test_alias_amf3(self): pyamf.register_class(PetExpando, 'Pet') encoder = pyamf.get_encoder(pyamf.AMF3) encoder.writeElement(self.jessica) self.assertEquals(encoder.stream.getvalue(), '\nk\x07Pet\t_key\x13birthdate\tname%spayed_or_neutered\ttype!' 'weight_in_pounds\x01\x08\x01B^\xc4\xae\xaa\x00\x00\x00\x06\x0f' 'Jessica\x02\x06\x07cat\x04\x05\x07foo\x06\x07bar\x01') class EncodingReferencesTestCase(ClassCacheClearingTestCase): """ This test case refers to L{db.ReferenceProperty}, not AMF references. """ def test_model(self): class Author(db.Model): name = db.StringProperty() class Novel(db.Model): title = db.StringProperty() author = db.ReferenceProperty(Author) a = Author(name='Jane Austen') a.put() k = str(a.key()) b = Novel(title='Sense and Sensibility', author=a) self.assertEquals(b.author, a) try: encoder = pyamf.get_encoder(pyamf.AMF0) encoder.writeElement(b) self.assertEquals(encoder.stream.getvalue(), '\x03\x00\x04_key\x05\x00\x06author\x03\x00\x04_key\x02%s%s' '\x00\x04name\x02\x00\x0bJane Austen\x00\x00\t\x00\x05title' '\x02\x00\x15Sense and Sensibility\x00\x00\t' % ( struct.pack('>H', len(k)), k)) encoder = pyamf.get_encoder(pyamf.AMF3) encoder.writeElement(b) self.assertEquals(encoder.stream.getvalue(), '\n;\x01\t_key\rauthor\x0btitle\x01\n+\x01\x00\tname\x06%s%s' '\x06\x17Jane Austen\x01\x06+Sense and Sensibility\x01' % ( amf3.encode_int(len(k) << 1 | amf3.REFERENCE_BIT), k)) # now test with aliases .. pyamf.register_class(Author, 'Author') pyamf.register_class(Novel, 'Novel') encoder = pyamf.get_encoder(pyamf.AMF0) encoder.writeElement(b) self.assertEquals(encoder.stream.getvalue(), '\x10\x00\x05Novel' '\x00\x04_key\x05\x00\x06author\x10\x00\x06Author\x00\x04_key' '\x02%s%s\x00\x04name\x02\x00\x0bJane Austen\x00\x00\t\x00' '\x05title\x02\x00\x15Sense and Sensibility\x00\x00\t' % ( struct.pack('>H', len(k)), k)) encoder = pyamf.get_encoder(pyamf.AMF3) encoder.writeElement(b) self.assertEquals(encoder.stream.getvalue(), '\n;\x0bNovel\t_key' '\rauthor\x0btitle\x01\n+\rAuthor\x02\tname\x06%s%s\x06\x17' 'Jane Austen\x01\x06+Sense and Sensibility\x01' % ( amf3.encode_int(len(k) << 1 | amf3.REFERENCE_BIT), k)) finally: a.delete() def test_expando(self): class Author(db.Expando): name = db.StringProperty() class Novel(db.Expando): title = db.StringProperty() author = db.ReferenceProperty(Author) a = Author(name='Jane Austen') a.put() k = str(a.key()) b = Novel(title='Sense and Sensibility', author=a) self.assertEquals(b.author, a) try: encoder = pyamf.get_encoder(pyamf.AMF0) encoder.writeElement(b) self.assertEquals(encoder.stream.getvalue(), '\x03\x00\x04_key\x05\x00\x06author\x03\x00\x04_key\x02%s%s' '\x00\x04name\x02\x00\x0bJane Austen\x00\x00\t\x00\x05title' '\x02\x00\x15Sense and Sensibility\x00\x00\t' % ( struct.pack('>H', len(k)), k)) encoder = pyamf.get_encoder(pyamf.AMF3) encoder.writeElement(b) self.assertEquals(encoder.stream.getvalue(), '\n;\x01\t_key\rauthor\x0btitle\x01\n+\x01\x00\tname\x06%s%s' '\x06\x17Jane Austen\x01\x06+Sense and Sensibility\x01' % ( amf3.encode_int(len(k) << 1 | amf3.REFERENCE_BIT), k)) # now test with aliases .. pyamf.register_class(Author, 'Author') pyamf.register_class(Novel, 'Novel') encoder = pyamf.get_encoder(pyamf.AMF0) encoder.writeElement(b) self.assertEquals(encoder.stream.getvalue(), '\x10\x00\x05Novel' '\x00\x04_key\x05\x00\x06author\x10\x00\x06Author\x00\x04_key' '\x02%s%s\x00\x04name\x02\x00\x0bJane Austen\x00\x00\t\x00' '\x05title\x02\x00\x15Sense and Sensibility\x00\x00\t' % ( struct.pack('>H', len(k)), k)) encoder = pyamf.get_encoder(pyamf.AMF3) encoder.writeElement(b) self.assertEquals(encoder.stream.getvalue(), '\n;\x0bNovel\t_key\rauthor\x0btitle\x01\n+\rAuthor\x02\tname' '\x06%s%s\x06\x17Jane Austen\x01\x06+Sense and Sensibility' '\x01' % (amf3.encode_int(len(k) << 1 | amf3.REFERENCE_BIT), k)) finally: a.delete() def test_dynamic_property_referenced_object(self): class Author(db.Model): name = db.StringProperty() class Novel(db.Model): title = db.StringProperty() author = db.ReferenceProperty(Author) try: a = Author(name='Jane Austen') a.put() b = Novel(title='Sense and Sensibility', author=a) b.put() x = Novel.all().filter('title = ', 'Sense and Sensibility').get() foo = [1, 2, 3] x.author.bar = foo k = str(x.key()) l = str(x.author.key()) stream = pyamf.encode(x) self.assertEquals(stream.getvalue(), '\x03\x00\x04_key\x02%s%s' '\x00\x06author\x03\x00\x04_key\x02%s%s\x00\x04name\x02\x00' '\x0bJane Austen\x00\x03bar\n\x00\x00\x00\x03\x00?\xf0\x00' '\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x00\x00@' '\x08\x00\x00\x00\x00\x00\x00\x00\x00\t\x00\x05title\x02\x00' '\x15Sense and Sensibility\x00\x00\t' % ( struct.pack('>H', len(k)), k, struct.pack('>H', len(l)), l)) finally: a.delete() b.delete() class ListModel(db.Model): numbers = db.ListProperty(long) class ListPropertyTestCase(ClassCacheClearingTestCase): def test_encode(self): obj = ListModel() obj.numbers = [2, 4, 6, 8, 10] encoder = pyamf.get_encoder(pyamf.AMF0) encoder.writeElement(obj) self.assertEquals(encoder.stream.getvalue(), '\x03\x00\x04_key\x05\x00\x07numbers\n\x00\x00\x00\x05\x00@' '\x00\x00\x00\x00\x00\x00\x00\x00@\x10\x00\x00\x00\x00\x00\x00' '\x00@\x18\x00\x00\x00\x00\x00\x00\x00@ \x00\x00\x00\x00\x00\x00' '\x00@$\x00\x00\x00\x00\x00\x00\x00\x00\t') encoder = pyamf.get_encoder(pyamf.AMF3) encoder.writeElement(obj) self.assertEquals(encoder.stream.getvalue(), '\n+\x01\t_key\x0fnumbers\x01\t\x0b\x01\x04\x02\x04\x04\x04\x06' '\x04\x08\x04\n\x01') pyamf.register_class(ListModel, 'list-model') encoder = pyamf.get_encoder(pyamf.AMF0) encoder.writeElement(obj) self.assertEquals(encoder.stream.getvalue(), '\x10\x00\nlist-model\x00\x04_key\x05\x00\x07numbers\n\x00\x00' '\x00\x05\x00@\x00\x00\x00\x00\x00\x00\x00\x00@\x10\x00\x00\x00' '\x00\x00\x00\x00@\x18\x00\x00\x00\x00\x00\x00\x00@ \x00\x00\x00' '\x00\x00\x00\x00@$\x00\x00\x00\x00\x00\x00\x00\x00\t') encoder = pyamf.get_encoder(pyamf.AMF3) encoder.writeElement(obj) self.assertEquals(encoder.stream.getvalue(), '\n+\x15list-model\t_key\x0fnumbers\x01\t\x0b\x01\x04\x02\x04\x04' '\x04\x06\x04\x08\x04\n\x01') def test_decode(self): pyamf.register_class(ListModel, 'list-model') decoder = pyamf.get_decoder(pyamf.AMF0) decoder.stream.write( '\x10\x00\nlist-model\x00\x07numbers\n\x00\x00' '\x00\x05\x00@\x00\x00\x00\x00\x00\x00\x00\x00@\x10\x00\x00\x00' '\x00\x00\x00\x00@\x18\x00\x00\x00\x00\x00\x00\x00@ \x00\x00' '\x00\x00\x00\x00\x00@$\x00\x00\x00\x00\x00\x00\x00\x00\t') decoder.stream.seek(0) x = decoder.readElement() self.assertTrue(isinstance(x, ListModel)) self.assertTrue(hasattr(x, 'numbers')) self.assertEquals(x.numbers, [2, 4, 6, 8, 10]) decoder = pyamf.get_decoder(pyamf.AMF3) decoder.stream.write( '\n\x0b\x15list-model\x0fnumbers\t\x0b\x01\x04\x02\x04' '\x04\x04\x06\x04\x08\x04\n\x01') decoder.stream.seek(0) x = decoder.readElement() self.assertTrue(isinstance(x, ListModel)) self.assertTrue(hasattr(x, 'numbers')) self.assertEquals(x.numbers, [2, 4, 6, 8, 10]) def test_none(self): pyamf.register_class(ListModel, 'list-model') decoder = pyamf.get_decoder(pyamf.AMF0) decoder.stream.write( '\x10\x00\nlist-model\x00\x07numbers\x05\x00\x00\t') decoder.stream.seek(0) x = decoder.readElement() self.assertEquals(x.numbers, []) class DecodingModelTestCase(ClassCacheClearingTestCase): def setUp(self): ClassCacheClearingTestCase.setUp(self) pyamf.register_class(PetModel, 'Pet') self.jessica = PetModel(name='Jessica', type='cat') self.jessica.birthdate = datetime.date(1986, 10, 2) self.jessica.weight_in_pounds = 5 self.jessica.spayed_or_neutered = False self.jessica.put() self.key = str(self.jessica.key()) def tearDown(self): ClassCacheClearingTestCase.tearDown(self) self.jessica.delete() def test_amf0(self): d = pyamf.get_decoder(pyamf.AMF0) b = d.stream b.write('\x10\x00\x03Pet\x00\x04_key\x02%s%s\x00\x04type\x02\x00\x03' 'cat\x00\x10weight_in_pounds\x00@\x14\x00\x00\x00\x00\x00\x00\x00' '\x04name\x02\x00\x07Jessica\x00\tbirthdate\x0bB^\xc4\xae\xaa\x00' '\x00\x00\x00\x00\x00\x12spayed_or_neutered\x01\x00\x00\x00\t' % ( struct.pack('>H', len(self.key)), self.key)) b.seek(0) x = d.readElement() self.assertTrue(isinstance(x, PetModel)) self.assertEquals(x.__class__, PetModel) self.assertEquals(x.type, self.jessica.type) self.assertEquals(x.weight_in_pounds, self.jessica.weight_in_pounds) self.assertEquals(x.birthdate, self.jessica.birthdate) self.assertEquals(x.spayed_or_neutered, self.jessica.spayed_or_neutered) # now check db.Model internals self.assertEquals(x.key(), self.jessica.key()) self.assertEquals(x.kind(), self.jessica.kind()) self.assertEquals(x.parent(), self.jessica.parent()) self.assertEquals(x.parent_key(), self.jessica.parent_key()) self.assertTrue(x.is_saved()) def test_amf3(self): d = pyamf.get_decoder(pyamf.AMF3) b = d.stream b.write('\n\x0b\x07Pet\tname\x06\x0fJessica\t_key\x06%s%s\x13birthdate' '\x08\x01B^\xc4\xae\xaa\x00\x00\x00!weight_in_pounds\x04\x05\x07' 'foo\x06\x07bar\ttype\x06\x07cat%%spayed_or_neutered\x02\x01' % ( amf3.encode_int(len(self.key) << 1 | amf3.REFERENCE_BIT), self.key)) b.seek(0) x = d.readElement() self.assertTrue(isinstance(x, PetModel)) self.assertEquals(x.__class__, PetModel) self.assertEquals(x.type, self.jessica.type) self.assertEquals(x.weight_in_pounds, self.jessica.weight_in_pounds) self.assertEquals(x.birthdate, self.jessica.birthdate) self.assertEquals(x.spayed_or_neutered, self.jessica.spayed_or_neutered) # now check db.Model internals self.assertEquals(x.key(), self.jessica.key()) self.assertEquals(x.kind(), self.jessica.kind()) self.assertEquals(x.parent(), self.jessica.parent()) self.assertEquals(x.parent_key(), self.jessica.parent_key()) self.assertTrue(x.is_saved()) class DecodingExpandoTestCase(ClassCacheClearingTestCase): def setUp(self): ClassCacheClearingTestCase.setUp(self) pyamf.register_class(PetExpando, 'Pet') self.jessica = PetExpando(name='Jessica', type='cat') #self.jessica.birthdate = datetime.date(1986, 10, 2) self.jessica.weight_in_pounds = 5 self.jessica.spayed_or_neutered = False self.jessica.foo = 'bar' self.jessica.put() self.key = str(self.jessica.key()) def tearDown(self): ClassCacheClearingTestCase.tearDown(self) self.jessica.delete() def test_amf0(self): d = pyamf.get_decoder(pyamf.AMF0) b = d.stream b.write('\x10\x00\x03Pet\x00\x04_key\x02%s%s\x00\x04type\x02\x00\x03' 'cat\x00\x10weight_in_pounds\x00@\x14\x00\x00\x00\x00\x00\x00\x00' '\x04name\x02\x00\x07Jessica\x00\tbirthdate\x0bB^\xc4\xae\xaa\x00' '\x00\x00\x00\x00\x00\x12spayed_or_neutered\x01\x00\x00\x00\t' % ( struct.pack('>H', len(self.key)), self.key)) b.seek(0) x = d.readElement() self.assertTrue(isinstance(x, PetExpando)) self.assertEquals(x.__class__, PetExpando) self.assertEquals(x.type, self.jessica.type) self.assertEquals(x.weight_in_pounds, self.jessica.weight_in_pounds) self.assertEquals(x.birthdate, datetime.date(1986, 10, 2)) self.assertEquals(x.spayed_or_neutered, self.jessica.spayed_or_neutered) # now check db.Expando internals self.assertEquals(x.key(), self.jessica.key()) self.assertEquals(x.kind(), self.jessica.kind()) self.assertEquals(x.parent(), self.jessica.parent()) self.assertEquals(x.parent_key(), self.jessica.parent_key()) self.assertTrue(x.is_saved()) def test_amf3(self): d = pyamf.get_decoder(pyamf.AMF3) b = d.stream b.write('\n\x0b\x07Pet\tname\x06\x0fJessica\t_key\x06%s%s\x13birthdate' '\x08\x01B^\xc4\xae\xaa\x00\x00\x00!weight_in_pounds\x04\x05\x07' 'foo\x06\x07bar\ttype\x06\x07cat%%spayed_or_neutered\x02\x01' % ( amf3.encode_int(len(self.key) << 1 | amf3.REFERENCE_BIT), self.key)) b.seek(0) x = d.readElement() self.assertTrue(isinstance(x, PetExpando)) self.assertEquals(x.__class__, PetExpando) self.assertEquals(x.type, self.jessica.type) self.assertEquals(x.weight_in_pounds, self.jessica.weight_in_pounds) self.assertEquals(x.birthdate, datetime.date(1986, 10, 2)) self.assertEquals(x.spayed_or_neutered, self.jessica.spayed_or_neutered) # now check db.Expando internals self.assertEquals(x.key(), self.jessica.key()) self.assertEquals(x.kind(), self.jessica.kind()) self.assertEquals(x.parent(), self.jessica.parent()) self.assertEquals(x.parent_key(), self.jessica.parent_key()) self.assertTrue(x.is_saved()) class ClassAliasTestCase(unittest.TestCase): def setUp(self): self.alias = adapter_db.DataStoreClassAlias(PetModel, 'foo.bar') self.jessica = PetModel(name='Jessica', type='cat') self.jessica_expando = PetExpando(name='Jessica', type='cat') self.jessica_expando.foo = 'bar' def tearDown(self): try: self.jessica.delete() except: pass if self.jessica_expando.is_saved(): self.jessica_expando.delete() try: pyamf.unregister_class(PetModel) except: pass def test_get_alias(self): alias = pyamf.register_class(PetModel) self.assertTrue(isinstance(alias, adapter_db.DataStoreClassAlias)) def test_alias(self): self.alias.compile() self.assertEquals(self.alias.decodable_properties, [ '_key', 'birthdate', 'name', 'spayed_or_neutered', 'type', 'weight_in_pounds' ]) self.assertEquals(self.alias.encodable_properties, [ '_key', 'birthdate', 'name', 'spayed_or_neutered', 'type', 'weight_in_pounds' ]) self.assertEquals(self.alias.static_attrs, ['_key', 'birthdate', 'name', 'spayed_or_neutered', 'type', 'weight_in_pounds']) self.assertEquals(self.alias.readonly_attrs, None) self.assertEquals(self.alias.exclude_attrs, None) self.assertEquals(self.alias.reference_properties, None) def test_create_instance(self): x = self.alias.createInstance() self.assertTrue(isinstance(x, adapter_db.ModelStub)) self.assertTrue(hasattr(x, 'klass')) self.assertEquals(x.klass, self.alias.klass) # test some stub functions self.assertEquals(x.properties(), self.alias.klass.properties()) self.assertEquals(x.dynamic_properties(), []) def test_apply(self): x = self.alias.createInstance() self.assertTrue(hasattr(x, 'klass')) self.alias.applyAttributes(x, { adapter_db.DataStoreClassAlias.KEY_ATTR: None, 'name': 'Jessica', 'type': 'cat', 'birthdate': None, 'weight_in_pounds': None, 'spayed_or_neutered': None }) self.assertFalse(hasattr(x, 'klass')) def test_get_attrs(self): sa, da = self.alias.getEncodableAttributes(self.jessica) self.assertEquals(sa, { '_key': None, 'type': 'cat', 'name': 'Jessica', 'birthdate': None, 'weight_in_pounds': None, 'spayed_or_neutered': None }) self.assertEquals(da, None) def test_get_attrs_expando(self): sa, da = self.alias.getEncodableAttributes(self.jessica_expando) self.assertEquals(sa, { '_key': None, 'type': 'cat', 'name': 'Jessica', 'birthdate': None, 'weight_in_pounds': None, 'spayed_or_neutered': None, }) self.assertEquals(da, { 'foo': 'bar' }) def test_get_attributes(self): sa, da = self.alias.getEncodableAttributes(self.jessica) self.assertEquals(sa, { '_key': None, 'type': 'cat', 'name': 'Jessica', 'birthdate': None, 'weight_in_pounds': None, 'spayed_or_neutered': None }) self.assertEquals(da, None) def test_get_attributes_saved(self): self.jessica.put() sa, da = self.alias.getEncodableAttributes(self.jessica) self.assertEquals(sa, { 'name': 'Jessica', '_key': str(self.jessica.key()), 'type': 'cat', 'birthdate': None, 'weight_in_pounds': None, 'spayed_or_neutered': None }) self.assertEquals(da, None) def test_get_attributes_expando(self): sa, da = self.alias.getEncodableAttributes(self.jessica_expando) self.assertEquals(sa, { 'name': 'Jessica', '_key': None, 'type': 'cat', 'birthdate': None, 'weight_in_pounds': None, 'spayed_or_neutered': None }) self.assertEquals(da, { 'foo': 'bar' }) def test_get_attributes_saved_expando(self): self.jessica_expando.put() sa, da = self.alias.getEncodableAttributes(self.jessica_expando) self.assertEquals(sa, { 'name': 'Jessica', '_key': str(self.jessica_expando.key()), 'type': 'cat', 'birthdate': None, 'weight_in_pounds': None, 'spayed_or_neutered': None }) self.assertEquals(da, { 'foo': 'bar' }) def test_arbitrary_properties(self): self.jessica.foo = 'bar' sa, da = self.alias.getEncodableAttributes(self.jessica) self.assertEquals(sa, { '_key': None, 'type': 'cat', 'name': 'Jessica', 'birthdate': None, 'weight_in_pounds': None, 'spayed_or_neutered': None }) self.assertEquals(da, { 'foo': 'bar' }) def test_property_type(self): class PropertyTypeModel(db.Model): @property def readonly(self): return True def _get_prop(self): return False def _set_prop(self, v): self.prop = v read_write = property(_get_prop, _set_prop) alias = adapter_db.DataStoreClassAlias(PropertyTypeModel, 'foo.bar') obj = PropertyTypeModel() sa, da = alias.getEncodableAttributes(obj) self.assertEquals(sa, {'_key': None}) self.assertEquals(da, {'read_write': False, 'readonly': True}) self.assertFalse(hasattr(obj, 'prop')) alias.applyAttributes(obj, { '_key': None, 'readonly': False, 'read_write': 'foo' }) self.assertEquals(obj.prop, 'foo') class ReferencesTestCase(ClassCacheClearingTestCase): def setUp(self): ClassCacheClearingTestCase.setUp(self) self.jessica = PetModel(name='Jessica', type='cat') self.jessica.birthdate = datetime.date(1986, 10, 2) self.jessica.weight_in_pounds = 5 self.jessica.spayed_or_neutered = False self.jessica.put() self.jessica2 = PetModel.all().filter('name', 'Jessica').get() self.assertNotEquals(id(self.jessica), id(self.jessica2)) self.assertEquals(str(self.jessica.key()), str(self.jessica2.key())) def tearDown(self): ClassCacheClearingTestCase.tearDown(self) self.jessica.delete() def test_amf0(self): encoder = pyamf.get_encoder(pyamf.AMF0) context = encoder.context stream = encoder.stream s = str(self.jessica.key()) self.assertFalse(hasattr(context, 'gae_objects')) encoder.writeObject(self.jessica) self.assertTrue(hasattr(context, 'gae_objects')) self.assertEquals(context.gae_objects, {PetModel: {s: self.jessica}}) self.assertEquals(stream.getvalue(), '\x03\x00\x04_key\x02%s%s\x00' '\tbirthdate\x0bB^\xc4\xae\xaa\x00\x00\x00\x00\x00\x00\x04name' '\x02\x00\x07Jessica\x00\x12spayed_or_neutered\x01\x00\x00\x04' 'type\x02\x00\x03cat\x00\x10weight_in_pounds\x00@\x14\x00\x00\x00' '\x00\x00\x00\x00\x00\t' % (struct.pack('>H', len(s)), s)) stream.truncate() encoder.writeObject(self.jessica2) self.assertTrue(hasattr(context, 'gae_objects')) self.assertEquals(context.gae_objects, {PetModel: {s: self.jessica}}) self.assertEquals(stream.getvalue(), '\x07\x00\x00') stream.truncate() # check a non referenced object toby = PetModel(name='Toby', type='cat') toby.put() try: encoder.writeObject(toby) finally: toby.delete() def test_amf3(self): encoder = pyamf.get_encoder(pyamf.AMF3) context = encoder.context stream = encoder.stream s = str(self.jessica.key()) self.assertFalse(hasattr(context, 'gae_objects')) encoder.writeObject(self.jessica) self.assertTrue(hasattr(context, 'gae_objects')) self.assertEquals(context.gae_objects, {PetModel: {s: self.jessica}}) self.assertEquals(stream.getvalue(), '\nk\x01\t_key\x13birthdate\t' 'name%%spayed_or_neutered\ttype!weight_in_pounds\x06%s%s\x08\x01' 'B^\xc4\xae\xaa\x00\x00\x00\x06\x0fJessica\x02\x06\x07cat\x04' '\x05\x01' % (amf3.encode_int(len(s) << 1 | amf3.REFERENCE_BIT), s)) stream.truncate() encoder.writeObject(self.jessica2) self.assertTrue(hasattr(context, 'gae_objects')) self.assertEquals(context.gae_objects, {PetModel: {s: self.jessica}}) self.assertEquals(stream.getvalue(), '\n\x00') def test_decode(self): pyamf.register_class(PetModel, 'Pet') k = str(self.jessica.key()) bytes = '\x10\x00\x03Pet\x00\x04_key\x02%s%s\x00\x04type\x02\x00' + \ '\x03cat\x00\x10weight_in_pounds\x00@\x14\x00\x00\x00\x00\x00' + \ '\x00\x00\x04name\x02\x00\x07Jessica\x00\tbirthdate\x0bB^\xc4' + \ '\xae\xaa\x00\x00\x00\x00\x00\x00\x12spayed_or_neutered' + \ '\x01\x00\x00\x00\t' bytes = bytes % (struct.pack('>H', len(k)), k) decoder = pyamf.get_decoder(pyamf.AMF0) context = decoder.context stream = decoder.stream stream.write(bytes * 2) stream.seek(0) j = decoder.readElement() alias = context.getClassAlias(PetModel) self.assertTrue(isinstance(j, PetModel)) self.assertTrue(isinstance(alias, adapter_db.DataStoreClassAlias)) self.assertEquals(context.gae_objects, {PetModel: {k: j}}) j2 = decoder.readElement() self.assertTrue(isinstance(j2, PetModel)) self.assertEquals(context.gae_objects, {PetModel: {k: j}}) def test_cached_reference_properties(self): class Author(db.Model): name = db.StringProperty() class Novel(db.Model): title = db.StringProperty() author = db.ReferenceProperty(Author) a = Author(name='Jane Austen') a.put() k = str(a.key()) b = Novel(title='Sense and Sensibility', author=a) b.put() c = Novel(title='Pride and Prejudice', author=a) c.put() try: s, p = Novel.all().order('-title').fetch(2) encoder = pyamf.get_encoder(pyamf.AMF3) context = encoder.context self.assertFalse(hasattr(context, 'gae_objects')) encoder.writeElement(s) self.assertTrue(hasattr(context, 'gae_objects')) self.assertEquals(context.gae_objects, { Novel: {str(s.key()): s}, Author: {k: a} }) encoder.writeElement(p) self.assertEquals(context.gae_objects, { Novel: { str(s.key()): s, str(p.key()): p, }, Author: {k: a} }) finally: a.delete() b.delete() c.delete() c = Novel(title='Pride and Prejudice', author=None) c.put() try: encoder = pyamf.get_encoder(encoding=pyamf.AMF3) alias = adapter_db.DataStoreClassAlias(Novel, None) sa, da = alias.getEncodableAttributes(c, codec=encoder) self.assertEquals(sa, { '_key': str(c.key()), 'title': 'Pride and Prejudice', 'author': None }) self.assertEquals(da, None) finally: c.delete() class GAEReferenceCollectionTestCase(unittest.TestCase): def setUp(self): self.klass = adapter_db.GAEReferenceCollection def test_init(self): x = self.klass() self.assertEquals(x, {}) def test_get(self): x = self.klass() # not a class type self.assertRaises(TypeError, x.getClassKey, chr, '') # not a subclass of db.Model/db.Expando self.assertRaises(TypeError, x.getClassKey, Spam, '') # wrong type for key self.assertRaises(TypeError, x.getClassKey, PetModel, 3) x = self.klass() self.assertRaises(KeyError, x.getClassKey, PetModel, 'foo') self.assertEquals(x, {PetModel: {}}) obj = object() x[PetModel]['foo'] = obj obj2 = x.getClassKey(PetModel, 'foo') self.assertEquals(id(obj), id(obj2)) self.assertEquals(x, {PetModel: {'foo': obj}}) def test_add(self): x = self.klass() # not a class type self.assertRaises(TypeError, x.addClassKey, chr, '') # not a subclass of db.Model/db.Expando self.assertRaises(TypeError, x.addClassKey, Spam, '') # wrong type for key self.assertRaises(TypeError, x.addClassKey, PetModel, 3) x = self.klass() pm1 = PetModel(type='cat', name='Jessica') pm2 = PetModel(type='dog', name='Sam') pe1 = PetExpando(type='cat', name='Toby') self.assertEquals(x, {}) x.addClassKey(PetModel, 'foo', pm1) self.assertEquals(x, {PetModel: {'foo': pm1}}) x.addClassKey(PetModel, 'bar', pm2) self.assertEquals(x, {PetModel: {'foo': pm1, 'bar': pm2}}) x.addClassKey(PetExpando, 'baz', pe1) self.assertEquals(x, { PetModel: {'foo': pm1, 'bar': pm2}, PetExpando: {'baz': pe1} }) class GettableModelStub(db.Model): gets = [] @staticmethod def get(*args, **kwargs): GettableModelStub.gets.append([args, kwargs]) class HelperTestCase(unittest.TestCase): def test_getGAEObjects(self): context = Spam() self.assertFalse(hasattr(context, 'gae_objects')) x = adapter_db.getGAEObjects(context) self.assertTrue(isinstance(x, adapter_db.GAEReferenceCollection)) self.assertTrue(hasattr(context, 'gae_objects')) self.assertEquals(id(x), id(context.gae_objects)) def test_loadInstanceFromDatastore(self): # not a class type self.assertRaises(TypeError, adapter_db.loadInstanceFromDatastore, chr, '') # not a subclass of db.Model/db.Expando self.assertRaises(TypeError, adapter_db.loadInstanceFromDatastore, Spam, '') # not a valid key type self.assertRaises(TypeError, adapter_db.loadInstanceFromDatastore, GettableModelStub, 2) self.assertEquals(GettableModelStub.gets, []) adapter_db.loadInstanceFromDatastore(GettableModelStub, 'foo', codec=None) self.assertEquals(GettableModelStub.gets, [[('foo',), {}]]) codec = Spam() codec.context = Spam() GettableModelStub.gets = [] self.assertFalse(hasattr(codec.context, 'gae_objects')) adapter_db.loadInstanceFromDatastore(GettableModelStub, 'foo', codec=codec) self.assertTrue(hasattr(codec.context, 'gae_objects')) self.assertEquals(GettableModelStub.gets, [[('foo',), {}]]) gae_objects = codec.context.gae_objects self.assertTrue(isinstance(gae_objects, adapter_db.GAEReferenceCollection)) self.assertEquals(gae_objects, {GettableModelStub: {'foo': None}}) def test_Query_type(self): """ L{db.Query} instances get converted to lists .. """ q = PetModel.all() self.assertTrue(isinstance(q, db.Query)) self.assertEquals(pyamf.encode(q).getvalue(), '\n\x00\x00\x00\x00') class FloatPropertyTestCase(unittest.TestCase): """ Tests for #609. """ def setUp(self): class FloatModel(db.Model): f = db.FloatProperty() self.klass = FloatModel self.f = FloatModel() self.alias = adapter_db.DataStoreClassAlias(self.klass, None) def tearDown(self): if self.f.is_saved(): self.f.delete() def test_behaviour(self): """ Test the behaviour of the Google SDK not handling ints gracefully """ self.assertRaises(db.BadValueError, setattr, self.f, 'f', 3) self.f.f = 3.0 self.assertEquals(self.f.f, 3.0) def test_apply_attributes(self): self.alias.applyAttributes(self.f, {'f': 3}) self.assertEquals(self.f.f, 3.0) class PolyModelTestCase(unittest.TestCase): """ Tests for L{db.PolyModel}. See #633 """ def setUp(self): class Poly(polymodel.PolyModel): s = db.StringProperty() self.klass = Poly self.p = Poly() self.alias = adapter_db.DataStoreClassAlias(self.klass, None) def test_encode(self): self.p.s = 'foo' sa, da = self.alias.getEncodableAttributes(self.p) self.assertEquals(sa, {'_key': None, 's': 'foo'}) self.assertEquals(da, None) def test_deep_inheritance(self): class DeepPoly(self.klass): d = db.IntegerProperty() self.alias = adapter_db.DataStoreClassAlias(DeepPoly, None) self.dp = DeepPoly() self.dp.s = 'bar' self.dp.d = 92 sa, da = self.alias.getEncodableAttributes(self.dp) self.assertEquals(sa, { '_key': None, 's': 'bar', 'd': 92 }) self.assertEquals(da, None) def suite(): suite = unittest.TestSuite() test_cases = [ EncodingModelTestCase, EncodingExpandoTestCase, EncodingReferencesTestCase, ListPropertyTestCase, DecodingModelTestCase, DecodingExpandoTestCase, ClassAliasTestCase, ReferencesTestCase, GAEReferenceCollectionTestCase, HelperTestCase, FloatPropertyTestCase, PolyModelTestCase ] for tc in test_cases: suite.addTest(unittest.makeSuite(tc)) return suite if __name__ == '__main__': unittest.main(defaultTest='suite') PKR:cA$$"pyamf/tests/adapters/test_array.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Tests for the L{collections} L{pyamf.adapters._collections} module. @since: 0.5 """ import unittest import array import pyamf class ArrayTestCase(unittest.TestCase): """ """ def setUp(self): self.orig = ['f', 'o', 'o'] self.obj = array.array('c') self.obj.append('f') self.obj.append('o') self.obj.append('o') def encdec(self, encoding): return pyamf.decode(pyamf.encode(self.obj, encoding=encoding), encoding=encoding).next() def test_amf0(self): self.assertEquals(self.encdec(pyamf.AMF0), self.orig) def test_amf3(self): self.assertEquals(self.encdec(pyamf.AMF3), self.orig) def suite(): suite = unittest.TestSuite() classes = [] if hasattr(array, 'array'): classes.append(ArrayTestCase) for x in classes: suite.addTest(unittest.makeSuite(x)) return suite if __name__ == '__main__': unittest.main(defaultTest='suite') PK :K+mm(pyamf/tests/adapters/test_collections.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ Tests for the L{collections} L{pyamf.adapters._collections} module. @since: 0.5 """ import unittest import collections import pyamf class CollectionsTestCase(unittest.TestCase): """ """ def encdec(self, encoding): return pyamf.decode(pyamf.encode(self.obj, encoding=encoding), encoding=encoding).next() class DequeTestCase(CollectionsTestCase): """ Tests for L{collections.deque} """ def setUp(self): self.orig = [1, 2, 3] self.obj = collections.deque(self.orig) def test_amf0(self): self.assertEquals(self.encdec(pyamf.AMF0), self.orig) def test_amf3(self): self.assertEquals(self.encdec(pyamf.AMF3), self.orig) class DefaultDictTestCase(CollectionsTestCase): """ Tests for L{collections.defaultdict} """ def setUp(self): s = 'mississippi' self.obj = collections.defaultdict(int) for k in s: self.obj[k] += 1 self.orig = dict(self.obj) def test_amf0(self): self.assertEquals(self.encdec(pyamf.AMF3), self.orig) def test_amf3(self): self.assertEquals(self.encdec(pyamf.AMF3), self.orig) def suite(): suite = unittest.TestSuite() classes = [] if hasattr(collections, 'deque'): classes.append(DequeTestCase) if hasattr(collections, 'defaultdict'): classes.append(DefaultDictTestCase) for x in classes: suite.addTest(unittest.makeSuite(x)) return suite if __name__ == '__main__': unittest.main(defaultTest='suite') PK:P:ll pyamf/tests/adapters/__init__.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ File included to make the directory a Python package. The test_*.py files are special in this directory in that they refer to the top level module names of the adapter to test. An attempt will be made to import that module but ignored if it fails (not available on the system). """ PK.;} """ def test_abstract(self): from django.db import models class CommonInfo(models.Model): name = models.CharField(max_length=100) age = models.PositiveIntegerField() class Meta: abstract = True class Student(CommonInfo): home_group = models.CharField(max_length=5) self.resetDB() alias = self.adapter.DjangoClassAlias(Student) x = Student() sa, da = alias.getEncodableAttributes(x) self.assertEquals(sa, { 'age': None, 'home_group': '', 'id': None, 'name': '' }) self.assertEquals(da, None) def test_concrete(self): from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Restaurant(Place): serves_hot_dogs = models.BooleanField() serves_pizza = models.BooleanField() self.resetDB() alias = self.adapter.DjangoClassAlias(Place) x = Place() sa, da = alias.getEncodableAttributes(x) self.assertEquals(sa, { 'id': None, 'name': '', 'address': '' }) self.assertEquals(da, None) alias = self.adapter.DjangoClassAlias(Restaurant) x = Restaurant() sa, da = alias.getEncodableAttributes(x) self.assertEquals(sa, { 'id': None, 'name': '', 'address': '', 'serves_hot_dogs': False, 'serves_pizza': False }) self.assertEquals(da, None) class MockFile(object): """ mock for L{django.core.files.base.File} """ def chunks(self): return [] def __len__(self): return 0 def read(self, n): return '' class FieldsTestCase(ModelsBaseTestCase): """ Tests for L{fields} """ def tearDown(self): ModelsBaseTestCase.tearDown(self) try: os.unlink(os.path.join(os.getcwd(), 'foo')) except OSError: raise pass def test_file(self): from django.db import models self.executed = False def get_studio_watermark(*args, **kwargs): self.executed = True return 'foo' class Image(models.Model): file = models.FileField(upload_to=get_studio_watermark) text = models.CharField(max_length=64) self.resetDB() alias = self.adapter.DjangoClassAlias(Image) i = Image() i.file.save('bar', MockFile()) i.save() sa, da = alias.getEncodableAttributes(i) self.assertEquals(sa, {'text': '', 'id': 1, 'file': u'foo'}) self.assertEquals(da, None) self.assertTrue(self.executed) attrs = alias.getDecodableAttributes(i, sa) self.assertEquals(attrs, {'text': ''}) class ImageTestCase(ModelsBaseTestCase): """ Tests for L{fields} """ def test_image(self): from django.db import models self.executed = False def get_studio_watermark(*args, **kwargs): self.executed = True return 'foo' class Profile(models.Model): file = models.ImageField(upload_to=get_studio_watermark) text = models.CharField(max_length=64) self.resetDB() alias = self.adapter.DjangoClassAlias(Profile) i = Profile() i.file.save('bar', MockFile()) i.save() sa, da = alias.getEncodableAttributes(i) self.assertEquals(sa, {'text': '', 'id': 1, 'file': u'foo_'}) self.assertEquals(da, None) self.assertTrue(self.executed) attrs = alias.getDecodableAttributes(i, sa) self.assertEquals(attrs, {'text': ''}) class ReferenceTestCase(ModelsBaseTestCase): """ Test case to make sure that the same object from the database is encoded by reference. """ def setUp(self): ModelsBaseTestCase.setUp(self) from django.db import models class ParentReference(models.Model): name = models.CharField(max_length=100) bar = models.ForeignKey('ChildReference', null=True) class ChildReference(models.Model): name = models.CharField(max_length=100) foo = models.ForeignKey(ParentReference) self.ParentReference = ParentReference self.ChildReference = ChildReference self.resetDB() def tearDown(self): ModelsBaseTestCase.tearDown(self) def test_not_referenced(self): """ Test to ensure that we observe the correct behaviour in the Django ORM. """ f = self.ParentReference() f.name = 'foo' b = self.ChildReference() b.name = 'bar' f.save() b.foo = f b.save() f.bar = b f.save() self.assertEquals(f.id, 1) foo = self.ParentReference.objects.select_related().get(id=1) self.assertFalse(foo.bar.foo is foo) def test_referenced_encode(self): f = self.ParentReference() f.name = 'foo' b = self.ChildReference() b.name = 'bar' f.save() b.foo = f b.save() f.bar = b f.save() self.assertEquals(f.id, 2) foo = self.ParentReference.objects.select_related().get(id=2) # ensure the referenced attribute resolves foo.bar.foo self.assertEquals(pyamf.encode(foo).getvalue(), '\x03\x00\x02id\x00' '@\x00\x00\x00\x00\x00\x00\x00\x00\x04name\x02\x00\x03foo\x00' '\x03bar\x03\x00\x02id\x00@\x00\x00\x00\x00\x00\x00\x00\x00\x04na' 'me\x02\x00\x03bar\x00\x03foo\x07\x00\x00\x00\x00\t\x00\x00\t') def suite(): suite = unittest.TestSuite() try: import django except ImportError: return suite test_cases = [ TypeMapTestCase, ClassAliasTestCase, ForeignKeyTestCase, I18NTestCase, PKTestCase, ModelInheritanceTestCase, FieldsTestCase, ReferenceTestCase ] try: import PIL except: pass else: test_cases.append(ImageTestCase) for tc in test_cases: suite.addTest(unittest.makeSuite(tc)) return suite if __name__ == '__main__': unittest.main(defaultTest='suite') PK;*..'pyamf/tests/adapters/test_sqlalchemy.py# Copyright (c) 2007-2009 The PyAMF Project. # See LICENSE.txt for details. """ PyAMF SQLAlchemy adapter tests. @since 0.4 """ import unittest import sqlalchemy from sqlalchemy import MetaData, Table, Column, Integer, String, ForeignKey, \ create_engine from sqlalchemy.orm import mapper, relation, sessionmaker, clear_mappers import pyamf.flex from pyamf.tests.util import Spam from pyamf.adapters import _sqlalchemy_orm as adapter class BaseObject(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) class User(BaseObject): def __init__(self, **kwargs): BaseObject.__init__(self, **kwargs) self.lazy_loaded = [LazyLoaded()] class Address(BaseObject): pass class LazyLoaded(BaseObject): pass class AnotherLazyLoaded(BaseObject): pass class BaseTestCase(unittest.TestCase): """ Initialise up all table/mappers. """ def setUp(self): # Create DB and map objects self.metadata = MetaData() self.engine = create_engine('sqlite:///:memory:', echo=False) Session = sessionmaker(bind=self.engine) self.session = Session() self.tables = {} self.tables['users'] = Table('users', self.metadata, Column('id', Integer, primary_key=True), Column('name', String(64))) self.tables['addresses'] = Table('addresses', self.metadata, Column('id', Integer, primary_key=True), Column('user_id', Integer, ForeignKey('users.id')), Column('email_address', String(128))) self.tables['lazy_loaded'] = Table('lazy_loaded', self.metadata, Column('id', Integer, primary_key=True), Column('user_id', Integer, ForeignKey('users.id'))) self.tables['another_lazy_loaded'] = Table('another_lazy_loaded', self.metadata, Column('id', Integer, primary_key=True), Column('user_id', Integer, ForeignKey('users.id'))) self.mappers = {} self.mappers['user'] = mapper(User, self.tables['users'], properties={ 'addresses': relation(Address, backref='user', lazy=False), 'lazy_loaded': relation(LazyLoaded, lazy=True), 'another_lazy_loaded': relation(AnotherLazyLoaded, lazy=True) }) self.mappers['addresses'] = mapper(Address, self.tables['addresses']) self.mappers['lazy_loaded'] = mapper(LazyLoaded, self.tables['lazy_loaded']) self.mappers['another_lazy_loaded'] = mapper(AnotherLazyLoaded, self.tables['another_lazy_loaded']) self.metadata.create_all(self.engine) pyamf.register_class(User, 'server.User') pyamf.register_class(Address, 'server.Address') pyamf.register_class(LazyLoaded, 'server.LazyLoaded') def tearDown(self): clear_mappers() pyamf.unregister_class(User) pyamf.unregister_class(Address) pyamf.unregister_class(LazyLoaded) def _build_obj(self): user = User() user.name = "test_user" user.addresses.append(Address(email_address="test@example.org")) return user def _save(self, obj): # this covers deprecation warnings etc. if hasattr(self.session, 'add'): self.session.add(obj) elif hasattr(self.session, 'save'): self.session.save(obj) else: raise AttributeError('Don\'t know how to save an object') def _clear(self): # this covers deprecation warnings etc. if hasattr(self.session, 'expunge_all'): self.session.expunge_all() elif hasattr(self.session, 'clear'): self.session.clear() else: raise AttributeError('Don\'t know how to clear session') class SATestCase(BaseTestCase): def _test_obj(self, encoded, decoded): self.assertEquals(User, decoded.__class__) self.assertEquals(encoded.name, decoded.name) self.assertEquals(encoded.addresses[0].email_address, decoded.addresses[0].email_address) def test_encode_decode_transient(self): user = self._build_obj() encoder = pyamf.get_encoder(pyamf.AMF3) encoder.writeElement(user) encoded = encoder.stream.getvalue() decoded = pyamf.get_decoder(pyamf.AMF3, encoded).readElement() self._test_obj(user, decoded) def test_encode_decode_persistent(self): user = self._build_obj() self._save(user) self.session.commit() self.session.refresh(user) encoder = pyamf.get_encoder(pyamf.AMF3) encoder.writeElement(user) encoded = encoder.stream.getvalue() decoded = pyamf.get_decoder(pyamf.AMF3, encoded).readElement() self._test_obj(user, decoded) def test_encode_decode_list(self): max = 5 for i in range(0, max): user = self._build_obj() user.name = "%s" % i self._save(user) self.session.commit() users = self.session.query(User).all() encoder = pyamf.get_encoder(pyamf.AMF3) encoder.writeElement(users) encoded = encoder.stream.getvalue() decoded = pyamf.get_decoder(pyamf.AMF3, encoded).readElement() self.assertEquals([].__class__, decoded.__class__) for i in range(0, max): self._test_obj(users[i], decoded[i]) def test_sa_merge(self): user = self._build_obj() for i, string in enumerate(['one', 'two', 'three']): addr = Address(email_address="%s@example.org" % string) user.addresses.append(addr) self._save(user) self.session.commit() self.session.refresh(user) encoder = pyamf.get_encoder(pyamf.AMF3) encoder.writeElement(user) encoded = encoder.stream.getvalue() decoded = pyamf.get_decoder(pyamf.AMF3, encoded).readElement() del decoded.addresses[0] del decoded.addresses[1] merged_user = self.session.merge(decoded) self.assertEqual(len(merged_user.addresses), 2) def test_encode_decode_with_references(self): user = self._build_obj() self._save(user) self.session.commit() self.session.refresh(user) max = 5 users = [] for i in range(0, max): users.append(user) encoder = pyamf.get_encoder(pyamf.AMF3) encoder.writeElement(users) encoded = encoder.stream.getvalue() decoded = pyamf.get_decoder(pyamf.AMF3, encoded).readElement() for i in range(0, max): self.assertEquals(id(decoded[0]), id(decoded[i])) class BaseClassAliasTestCase(BaseTestCase): def setUp(self): BaseTestCase.setUp(self) self.alias = pyamf.get_class_alias(User) class ClassAliasTestCase(BaseClassAliasTestCase): def test_type(self): self.assertEquals(self.alias.__class__, adapter.SaMappedClassAlias) def test_get_mapper(self): self.assertFalse(hasattr(self.alias, 'mapper')) self.alias.compile() mapper = adapter.class_mapper(User) self.assertTrue(hasattr(self.alias, 'mapper')) self.assertEquals(id(mapper), id(self.alias.mapper)) def test_get_attrs(self): u = self._build_obj() static, dynamic = self.alias.getEncodableAttributes(u) self.assertEquals(static.keys(), [ 'id', 'lazy_loaded', 'addresses', 'name', 'another_lazy_loaded' ]) self.assertEquals(dynamic, {'sa_key': [None], 'sa_lazy': []}) def test_get_attributes(self): u = self._build_obj() self.assertFalse(u in self.session) self.assertEquals([None], self.mappers['user'].primary_key_from_instance(u)) static, dynamic = self.alias.getEncodableAttributes(u) self.assertEquals(static, { 'addresses': u.addresses, 'lazy_loaded': u.lazy_loaded, 'another_lazy_loaded': [], 'id': None, 'name': 'test_user' }) self.assertEquals(dynamic, { 'sa_lazy': [], 'sa_key': [None] }) def test_property(self): class Person(object): foo = 'bar' baz = 'gak' def _get_rw_property(self): return self.foo def _set_rw_property(self, val): self.foo = val def _get_ro_property(self): return self.baz rw = property(_get_rw_property, _set_rw_property) ro = property(_get_ro_property) self.mappers['person'] = mapper(Person, self.tables['users']) alias = adapter.SaMappedClassAlias(Person, 'person') obj = Person() sa, da = alias.getEncodableAttributes(obj) self.assertEquals(sa, { 'id': None, 'name': None}) self.assertEquals(da, { 'sa_key': [None], 'sa_lazy': [], 'rw': 'bar', 'ro': 'gak'}) self.assertEquals(obj.ro, 'gak') alias.applyAttributes(obj, { 'sa_key': [None], 'sa_lazy': [], 'id': None, 'name': None, 'rw': 'bar', 'ro': 'baz'}) self.assertEquals(obj.ro, 'gak') class ApplyAttributesTestCase(BaseClassAliasTestCase): def test_undefined(self): u = self.alias.createInstance() attrs = { 'sa_lazy': ['another_lazy_loaded'], 'sa_key': [None], 'addresses': [], 'lazy_loaded': [], 'another_lazy_loaded': pyamf.Undefined, # <-- the important bit 'id': None, 'name': 'test_user' } self.alias.applyAttributes(u, attrs) d = u.__dict__.copy() if sqlalchemy.__version__.startswith('0.4'): self.assertTrue('_state' in d) del d['_state'] elif sqlalchemy.__version__.startswith('0.5'): self.assertTrue('_sa_instance_state' in d) del d['_sa_instance_state'] self.assertEquals(d, { 'lazy_loaded': [], 'addresses': [], 'name': 'test_user', 'id': None }) def test_decode_unaliased(self): u = self.alias.createInstance() attrs = { 'sa_lazy': [], 'sa_key': [None], 'addresses': [], 'lazy_loaded': [], # this is important because we haven't registered AnotherLazyLoaded # as an alias and the decoded object for an untyped object is an # instance of pyamf.ASObject 'another_lazy_loaded': [pyamf.ASObject({'id': 1, 'user_id': None})], 'id': None, 'name': 'test_user' } # sqlalchemy can't find any state to work with self.assertRaises(AttributeError, self.alias.applyAttributes, u, attrs) class AdapterTestCase(BaseTestCase): """ Checks to see if the adapter will actually intercept a class correctly. """ def test_mapped(self): self.assertNotEquals(None, adapter.class_mapper(User)) self.assertTrue(adapter.is_class_sa_mapped(User)) def test_instance(self): u = User() self.assertTrue(adapter.is_class_sa_mapped(u)) def test_not_mapped(self): self.assertRaises(adapter.UnmappedInstanceError, adapter.class_mapper, Spam) self.assertFalse(adapter.is_class_sa_mapped(Spam)) def suite(): suite = unittest.TestSuite() try: import pysqlite2 except ImportError: return suite classes = [ SATestCase, AdapterTestCase, ClassAliasTestCase, ApplyAttributesTestCase ] for x in classes: suite.addTest(unittest.makeSuite(x)) return suite if __name__ == '__main__': unittest.main(defaultTest='suite') PK:u3;}pLV V #pyamf/tests/adapters/test_array.pyc; L]Jc@shdZdkZdkZdkZdeifdYZdZedjoeiddndS(sR Tests for the L{collections} L{pyamf.adapters._collections} module. @since: 0.5 Ns ArrayTestCasecBs2tZdZdZdZdZdZRS(s cCsXdddg|_tid|_|iid|iid|iiddS(Nsfsosc(sselfsorigsarraysobjsappend(sself((s?build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_array.pyssetUps cCs/titi|id|d|iSdS(Nsencoding(spyamfsdecodesencodesselfsobjsencodingsnext(sselfsencoding((s?build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_array.pysencdecscCs#|i|iti|idS(N(sselfs assertEqualssencdecspyamfsAMF0sorig(sself((s?build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_array.pys test_amf0!scCs#|i|iti|idS(N(sselfs assertEqualssencdecspyamfsAMF3sorig(sself((s?build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_array.pys test_amf3$s(s__name__s __module__s__doc__ssetUpsencdecs test_amf0s test_amf3(((s?build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_array.pys ArrayTestCases    cCsbti}g}ttdo|itnx$|D]}|i ti |q:W|SdS(Nsarray( sunittests TestSuitessuitesclassesshasattrsarraysappends ArrayTestCasesxsaddTests makeSuite(sclassessxssuite((s?build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_array.pyssuite(s s__main__s defaultTestssuite( s__doc__sunittestsarrayspyamfsTestCases ArrayTestCasessuites__name__smain(sunittestssuitesarrayspyamfs ArrayTestCase((s?build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_array.pys?s     PK:u3;bj%%)pyamf/tests/adapters/test_collections.pyc; TfZJc@sdZdkZdkZdkZdeifdYZdefdYZdefdYZdZe d joei d d ndS( sR Tests for the L{collections} L{pyamf.adapters._collections} module. @since: 0.5 NsCollectionsTestCasecBstZdZdZRS(s cCs/titi|id|d|iSdS(Nsencoding(spyamfsdecodesencodesselfsobjsencodingsnext(sselfsencoding((sEbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_collections.pysencdecs(s__name__s __module__s__doc__sencdec(((sEbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_collections.pysCollectionsTestCases s DequeTestCasecBs)tZdZdZdZdZRS(s( Tests for L{collections.deque} cCs+dddg|_ti|i|_dS(Niii(sselfsorigs collectionssdequesobj(sself((sEbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_collections.pyssetUpscCs#|i|iti|idS(N(sselfs assertEqualssencdecspyamfsAMF0sorig(sself((sEbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_collections.pys test_amf0#scCs#|i|iti|idS(N(sselfs assertEqualssencdecspyamfsAMF3sorig(sself((sEbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_collections.pys test_amf3&s(s__name__s __module__s__doc__ssetUps test_amf0s test_amf3(((sEbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_collections.pys DequeTestCases   sDefaultDictTestCasecBs)tZdZdZdZdZRS(s. Tests for L{collections.defaultdict} cCsRd}tit|_x!|D]}|i|cd7s   cCsVdkl}dk}|i}ti|_|iiddt |_ ||_dS(N(s connectionis autoclobber( s django.dbs connectionssyssstderrs old_stderrsutilsNullFileDescriptorscreationscreate_test_dbsTruesselfsdb_name(sselfssyss connections old_stderr((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysresetDBFs    (s__name__s __module__ssetUpstearDownsresetDB(((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysModelsBaseTestCases ) sTypeMapTestCasecBstZdZdZRS(NcCsdkl}d|ifdY}|ititi}|i |i i |i |iidtiti}|i |i i |i |iiddS(N(smodelssSpamcBstZRS(N(s__name__s __module__(((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysSpamVss s (s django.dbsmodelssModelsSpamsselfsresetDBspyamfs get_encodersAMF0sencoders writeElementsobjectssalls assertEqualssstreamsgetvaluesAMF3(sselfsmodelssencodersSpam((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pystest_objects_allSs  cCsdkl}titi}|i|i|i |i i dtiti }|i|i|i |i i ddS(N(sfieldsss( sdjango.db.modelssfieldsspyamfs get_encodersAMF0sencoders writeElements NOT_PROVIDEDsselfs assertEqualssstreamsgetvaluesAMF3(sselfsfieldssencoder((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pystest_NOT_PROVIDEDcs (s__name__s __module__stest_objects_allstest_NOT_PROVIDED(((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysTypeMapTestCaseRs sClassAliasTestCasecBs,tZdZdZdZdZRS(Nc sdkldifdY}|}tiddd|_tiddd|_ tidddddd|_ |i i |t}|i|\}}|i|hdt<dtidddd d <d tidddddd<d tid d d ddd<|i|t|}|i|hdt<dtidddd d <d tidddddd<d tid d d ddd<|i|it|i|i tiddd|i|i tidddddd|i|itiddd|}|i|hdt<dt<d t<d t<|i|it|i|i t|i|i t|i|itdS(N(smodelss TestClasscs,tZiZiZiZRS(N( s__name__s __module__smodelss TimeFieldsts DateFieldsds DateTimeFieldsdt((smodels(s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pys TestClassts  i iisidsdisdtstii(s django.dbsmodelssModels TestClasssxsdatetimestimestsdatesdsdtsselfsadaptersDjangoClassAliassNonesaliassgetEncodableAttributesssasdas assertEqualssysapplyAttributessid(sselfsmodelss TestClasssaliassysxssasda((smodelss@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pys test_timeqs,  !y y"+" 4cCsdkl}dkl}d|ifdY}|ii|t }|}|i |hdt i<|i|i|i|i|_|i|\}}|i|t |i|hdt i<dS(N(smodels(sfieldssUndefinedClasscBstZRS(N(s__name__s __module__(((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysUndefinedClassssid(s django.dbsmodelssdjango.db.modelssfieldssModelsUndefinedClasssselfsadaptersDjangoClassAliassNonesaliassxsapplyAttributesspyamfs Undefineds assertEqualssids NOT_PROVIDEDsgetEncodableAttributesssasda(sselfssasmodelssfieldssdasaliassxsUndefinedClass((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pystest_undefineds    cCsdkl}d|ifdY}|ii|d}|}|i |i |hdt tZiddZiZiZ dZ RS(Ns max_lengthidcCs |iSdS(N(sselfsheadline(sself((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pys __unicode__s( s__name__s __module__smodelss CharFieldsheadlines DateFieldspub_dates ForeignKeysReportersreporters __unicode__((sReportersmodels(s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysArticles s first_namesJohns last_namesSmithsemailsjohn@example.comsPaulsJonesspaul@example.comsheadlinesThis is a testspub_dateiiisreporterispkis_reporter_cachesdefersfieldsuThis is a testsidsencodings? ;headlineidpub_dateThis is a testBpUYj@reporters ;headlineidpub_dateThis is a testBpUYj@reporter K emailfirst_namelast_name!john@example.com John Smith(#s django.dbsmodelssModelsReportersArticlesselfsresetDBsrssavesr2sdatetimesdatesas assertEqualssidsobjectssfilters assertFalses__dict__sreporters assertTruesadaptersDjangoClassAliassTruesaliasshasattrsgetEncodableAttributesssasdaspyamfs UndefinedsencodesAMF3sgetvaluesselect_related( sselfsasr2sReportersmodelssaliassrsArticlessasda((sReportersmodelss@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pystest_one_to_manysD    * @!X !csdkldifdYdifdY}|idtdd}|i dtdd }|i dtdd }|i |dtd d }|i |i |id |ii||iit} |ii|t} iidd d} |iidd d}| i| \}}|i |hdd <dd<|i |t| i|\}}|i |hd d<dd <d|g<|i |t|} | i| hd d<dd <d|g<|i | id|i | id | ii} |i t!| d |i | d|dS(N(smodelss Publicationcs6tZiddZdZdfdYZRS(Ns max_lengthicCs |iSdS(N(sselfstitle(sself((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pys __unicode__PssMetacBstZdfZRS(Nstitle(s__name__s __module__sordering(((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysMetaSs(s__name__s __module__smodelss CharFieldstitles __unicode__sMeta((smodels(s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pys PublicationMs sArticle2csEtZiddZiZdZdfdYZ RS(Ns max_lengthidcCs |iSdS(N(sselfsheadline(sself((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pys __unicode__ZssMetacBstZdfZRS(Nsheadline(s__name__s __module__sordering(((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysMeta]s( s__name__s __module__smodelss CharFieldsheadlinesManyToManyFields Publications publicationss __unicode__sMeta((s Publicationsmodels(s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysArticle2Vs sidstitlesThe Python Journals Science NewssScience Weeklysheadlines%Django lets you build Web apps easilyispkiuThe Python Journalu%Django lets you build Web apps easilys publicationsuTest("s django.dbsmodelssModels PublicationsArticle2sselfsresetDBsNonesp1ssavesp2sp3sa1s assertEqualssids publicationssaddsadaptersDjangoClassAliass pub_aliass art_aliassobjectssfilterstest_publications test_articlesgetEncodableAttributesssasdasxsapplyAttributessheadlinesallspslen(sselfsArticle2sp2sp1s Publicationsp3smodelssdasa1spstest_publications pub_aliass art_aliassxssas test_article((s Publicationsmodelss@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pystest_many_to_manyJs>       ". .(s__name__s __module__stest_one_to_manystest_many_to_many(((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysForeignKeyTestCases Vs I18NTestCasecBstZdZRS(NcCs6dkl}|iti|diddS(N(s ugettext_lazysHellosHello(sdjango.utils.translations ugettext_lazysselfs assertEqualsspyamfsencodesgetvalue(sselfs ugettext_lazy((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pys test_encodes (s__name__s __module__s test_encode(((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pys I18NTestCasess PKTestCasecBs tZdZdZdZRS(s^ See ticket #599 for this. Check to make sure that django pk fields are set first cs dkldifdYdifdY}|idtdd}|dtd d }|i t d |||i |i |i |id |ii|t}|}|i|hd d <dd <d|g<dS(N(smodelss Publicationcs6tZiddZdZdfdYZRS(Ns max_lengthicCs |iSdS(N(sselfstitle(sself((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pys __unicode__ssMetacBstZdfZRS(Nstitle(s__name__s __module__sordering(((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysMetas(s__name__s __module__smodelss CharFieldstitles __unicode__sMeta((smodels(s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pys Publications sArticle2csEtZiddZiZdZdfdYZ RS(Ns max_lengthidcCs |iSdS(N(sselfsheadline(sself((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pys __unicode__ssMetacBstZdfZRS(Nsheadline(s__name__s __module__sordering(((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysMetas( s__name__s __module__smodelss CharFieldsheadlinesManyToManyFields Publications publicationss __unicode__sMeta((s Publicationsmodels(s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysArticle2s sidstitlesThe Python Journalsheadlines%Django lets you build Web apps easilycCs|ii|S(N(sas publicationssaddsp(sasp((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pyssisFoo bar!s publications(s django.dbsmodelssModels PublicationsArticle2sselfsresetDBsNonespsas assertRaisess ValueErrorssaves assertEqualssidsadaptersDjangoClassAliass article_aliassxsapplyAttributes(sselfsArticle2sas Publicationsmodelss article_aliasspsx((s Publicationsmodelss@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pystest_behaviours      cCsdkl}d|ifdY}|i|ii|t}|}|i |i t|i |hdd<|i |i tdS(sk See #556. Make sure that PK fields with a value of 0 are actually set to C{None}. (smodelssFoocBstZRS(N(s__name__s __module__(((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysFoossidiN(s django.dbsmodelssModelsFoosselfsresetDBsadaptersDjangoClassAliassNonesaliassxs assertEqualssidsapplyAttributes(sselfsmodelssaliassxsFoo((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pys test_nones   (s__name__s __module__s__doc__stest_behaviours test_none(((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pys PKTestCases  ,sModelInheritanceTestCasecBs tZdZdZdZRS(sy Tests for L{Django model inheritance} csdkldifdY}d|fdY}|i|ii|}|}|i |\}}|i|hdt<dd<d t<d d<|i|tdS( N(smodelss CommonInfocs9tZiddZiZdfdYZRS(Ns max_lengthidsMetacBstZeZRS(N(s__name__s __module__sTruesabstract(((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysMetas(s__name__s __module__smodelss CharFieldsnamesPositiveIntegerFieldsagesMeta((smodels(s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pys CommonInfos sStudentcstZiddZRS(Ns max_lengthi(s__name__s __module__smodelss CharFields home_group((smodels(s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysStudentssages home_groupssidsname(s django.dbsmodelssModels CommonInfosStudentsselfsresetDBsadaptersDjangoClassAliassaliassxsgetEncodableAttributesssasdas assertEqualssNone(sselfsaliassmodelssdas CommonInfosStudentsxssa((smodelss@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pys test_abstracts   4cs8dkldifdY}d|fdY}|i|ii|}|}|i |\}}|i|hdt<dd<d d<|i|t|ii|}|}|i |\}}|i|hdt<dd<d d<d t<d t<|i|tdS( N(smodelssPlacecs,tZiddZiddZRS(Ns max_lengthi2iP(s__name__s __module__smodelss CharFieldsnamesaddress((smodels(s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysPlacess Restaurantcs tZiZiZRS(N(s__name__s __module__smodelss BooleanFieldsserves_hot_dogss serves_pizza((smodels(s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pys Restaurants sidsnamessaddresssserves_hot_dogss serves_pizza(s django.dbsmodelssModelsPlaces RestaurantsselfsresetDBsadaptersDjangoClassAliassaliassxsgetEncodableAttributesssasdas assertEqualssNonesFalse(sselfs RestaurantsmodelssdasaliassPlacesxssa((smodelss@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pys test_concrete s   + =(s__name__s __module__s__doc__s test_abstracts test_concrete(((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysModelInheritanceTestCases  sMockFilecBs)tZdZdZdZdZRS(s1 mock for L{django.core.files.base.File} cCsgSdS(N((sself((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pyschunks:scCsdSdS(Ni((sself((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pys__len__=scCsdSdS(Ns((sselfsn((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysread@s(s__name__s __module__s__doc__schunkss__len__sread(((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysMockFile5s   sFieldsTestCasecBs tZdZdZdZRS(s Tests for L{fields} cCsPti|y&titiitidWntj o nXdS(Nsfoo( sModelsBaseTestCasestearDownsselfsossunlinkspathsjoinsgetcwdsOSError(sself((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pystearDownIs  &c sdklt_ddifdY}ii i |}|}|i idt|i|i|\}}i|hdd<dd <d d <i|tii|i||}i|hdd<dS( N(smodelscst_dSdS(Nsfoo(sTruesselfsexecuted(sargsskwargs(sself(s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysget_studio_watermarkWs sImagecs,tZidZiddZRS(Ns upload_tos max_lengthi@(s__name__s __module__smodelss FileFieldsget_studio_watermarksfiles CharFieldstext((smodelssget_studio_watermark(s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysImage\ssbarstextssidisfileufoo(s django.dbsmodelssFalsesselfsexecutedsget_studio_watermarksModelsImagesresetDBsadaptersDjangoClassAliassaliassisfilessavesMockFilesgetEncodableAttributesssasdas assertEqualssNones assertTruesgetDecodableAttributessattrs( sselfsismodelssImagesdasaliassget_studio_watermarksattrsssa((sselfsmodelssget_studio_watermarks@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pys test_fileRs      +(s__name__s __module__s__doc__stearDowns test_file(((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysFieldsTestCaseDs  s ImageTestCasecBstZdZdZRS(s Tests for L{fields} c sdklt_ddifdY}ii i |}|}|i idt|i|i|\}}i|hdd<dd <d d <i|tii|i||}i|hdd<dS( N(smodelscst_dSdS(Nsfoo(sTruesselfsexecuted(sargsskwargs(sself(s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysget_studio_watermark~s sProfilecs,tZidZiddZRS(Ns upload_tos max_lengthi@(s__name__s __module__smodelss ImageFieldsget_studio_watermarksfiles CharFieldstext((smodelssget_studio_watermark(s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysProfilessbarstextssidisfileufoo_(s django.dbsmodelssFalsesselfsexecutedsget_studio_watermarksModelsProfilesresetDBsadaptersDjangoClassAliassaliassisfilessavesMockFilesgetEncodableAttributesssasdas assertEqualssNones assertTruesgetDecodableAttributessattrs( sselfsProfilesismodelssdasaliassget_studio_watermarksattrsssa((sselfsmodelssget_studio_watermarks@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pys test_imageys      +(s__name__s __module__s__doc__s test_image(((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pys ImageTestCasets sReferenceTestCasecBs2tZdZdZdZdZdZRS(sd Test case to make sure that the same object from the database is encoded by reference. csuti|dkldifdYdifdY}|_||_|idS(N(smodelssParentReferencecs/tZiddZiddeZRS(Ns max_lengthidsChildReferencesnull(s__name__s __module__smodelss CharFieldsnames ForeignKeysTruesbar((smodels(s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysParentReferencessChildReferencecs)tZiddZiZRS(Ns max_lengthid(s__name__s __module__smodelss CharFieldsnames ForeignKeysParentReferencesfoo((smodelssParentReference(s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysChildReferences( sModelsBaseTestCasessetUpsselfs django.dbsmodelssModelsParentReferencesChildReferencesresetDB(sselfsmodelssParentReferencesChildReference((smodelssParentReferences@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pyssetUps    cCsti|dS(N(sModelsBaseTestCasestearDownsself(sself((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pystearDownscCs|i}d|_|i}d|_|i||_|i||_|i|i |i d|ii i i dd}|i|ii|jdS(sa Test to ensure that we observe the correct behaviour in the Django ORM. sfoosbarisidN(sselfsParentReferencesfsnamesChildReferencesbssavesfoosbars assertEqualssidsobjectssselect_relatedsgets assertFalse(sselfsbsfoosf((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pystest_not_referenceds         cCs|i}d|_|i}d|_|i||_|i||_|i|i |i d|ii i i dd}|ii|i ti|iddS(NsfoosbarisidsGid@namefoobarid@namebarfoo (sselfsParentReferencesfsnamesChildReferencesbssavesfoosbars assertEqualssidsobjectssselect_relatedsgetspyamfsencodesgetvalue(sselfsbsfoosf((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pystest_referenced_encodes          (s__name__s __module__s__doc__ssetUpstearDownstest_not_referencedstest_referenced_encode(((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pysReferenceTestCases    cCsti}y dk}Wntj o |SnXttttt t t t g}y dk}WnnX|itx$|D]}|iti|q|W|SdS(N(sunittests TestSuitessuitesdjangos ImportErrorsTypeMapTestCasesClassAliasTestCasesForeignKeyTestCases I18NTestCases PKTestCasesModelInheritanceTestCasesFieldsTestCasesReferenceTestCases test_casessPILsappends ImageTestCasestcsaddTests makeSuite(sPILsdjangossuites test_casesstc((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pyssuites      s__main__s defaultTestssuite(s__doc__sunittestssyssossnewsdatetimespyamfs pyamf.testssutilsTestCasesModelsBaseTestCasesTypeMapTestCasesClassAliasTestCasesForeignKeyTestCases I18NTestCases PKTestCasesModelInheritanceTestCasesobjectsMockFilesFieldsTestCases ImageTestCasesReferenceTestCasessuites__name__smain(sutilsModelsBaseTestCases I18NTestCasesunittestsForeignKeyTestCasesTypeMapTestCasesFieldsTestCases ImageTestCasesdatetimessyssModelInheritanceTestCasesReferenceTestCases PKTestCasesClassAliasTestCasessuitesnewsosspyamfsMockFile((s@build/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_django.pys?s*       >KM0'J  PK:u3;R2OyLyL(pyamf/tests/adapters/test_sqlalchemy.pyc; Jc@sdZdkZdkZdklZlZlZlZlZlZl Z dk l Z l Z l Z lZdkZdklZdklZdefdYZdefd YZd efd YZd efd YZdefdYZdeifdYZdefdYZdefdYZdefdYZ defdYZ!defdYZ"dZ#e$djoei%ddndS( s- PyAMF SQLAlchemy adapter tests. @since 0.4 N(sMetaDatasTablesColumnsIntegersStrings ForeignKeys create_engine(smappersrelations sessionmakers clear_mappers(sSpam(s_sqlalchemy_orms BaseObjectcBstZdZRS(NcKs|ii|dS(N(sselfs__dict__supdateskwargs(sselfskwargs((sDbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_sqlalchemy.pys__init__s(s__name__s __module__s__init__(((sDbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_sqlalchemy.pys BaseObjectssUsercBstZdZRS(NcKs#ti||tg|_dS(N(s BaseObjects__init__sselfskwargss LazyLoadeds lazy_loaded(sselfskwargs((sDbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_sqlalchemy.pys__init__s(s__name__s __module__s__init__(((sDbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_sqlalchemy.pysUserssAddresscBstZRS(N(s__name__s __module__(((sDbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_sqlalchemy.pysAddress"ss LazyLoadedcBstZRS(N(s__name__s __module__(((sDbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_sqlalchemy.pys LazyLoaded&ssAnotherLazyLoadedcBstZRS(N(s__name__s __module__(((sDbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_sqlalchemy.pysAnotherLazyLoaded*ss BaseTestCasecBs;tZdZdZdZdZdZdZRS(s* Initialise up all table/mappers. c Csft|_tddt|_td|i}||_h|_ t d|it dt dt t dtd|i dtZdZdZdZdZdZdZRS(NcCsQ|it|i|i|i|i|i|idi|ididS(Ni( sselfs assertEqualssUsersdecodeds __class__sencodedsnames addressess email_address(sselfsencodedsdecoded((sDbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_sqlalchemy.pys _test_objscCsi|i}titi}|i||ii }ti ti|i }|i||dS(N(sselfs _build_objsuserspyamfs get_encodersAMF3sencoders writeElementsstreamsgetvaluesencodeds get_decoders readElementsdecodeds _test_obj(sselfsdecodedsencodersusersencoded((sDbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_sqlalchemy.pystest_encode_decode_transients   cCs|i}|i||ii|ii|titi }|i ||i i }titi |i}|i||dS(N(sselfs _build_objsusers_savessessionscommitsrefreshspyamfs get_encodersAMF3sencoders writeElementsstreamsgetvaluesencodeds get_decoders readElementsdecodeds _test_obj(sselfsdecodedsencodersusersencoded((sDbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_sqlalchemy.pystest_encode_decode_persistents    cCsd}x=td|D],}|i}d||_|i|qW|ii |ii t i }titi}|i||ii}titi|i}|igi|ix/td|D]}|i||||qWdS(Niis%s(smaxsrangesisselfs _build_objsusersnames_savessessionscommitsquerysUsersallsusersspyamfs get_encodersAMF3sencoders writeElementsstreamsgetvaluesencodeds get_decoders readElementsdecodeds assertEqualss __class__s _test_obj(sselfsdecodedsuserssismaxsencodersusersencoded((sDbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_sqlalchemy.pystest_encode_decode_lists     c Cs |i}xFtdddgD]/\}}tdd|}|ii |q"W|i ||i i |i i |titi}|i||ii}titi|i}|id=|id=|i i|}|it|iddS( Nsonestwosthrees email_addresss%s@example.orgiii(sselfs _build_objsusers enumeratesisstringsAddresssaddrs addressessappends_savessessionscommitsrefreshspyamfs get_encodersAMF3sencoders writeElementsstreamsgetvaluesencodeds get_decoders readElementsdecodedsmerges merged_users assertEqualslen( sselfsdecodedsaddrsisencodersusers merged_usersencodedsstring((sDbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_sqlalchemy.pys test_sa_merges        cCs|i}|i||ii|ii|d}g}x$t d|D]}|i |qRWt i t i}|i||ii}t it i|i}x;t d|D]*}|it|dt||qWdS(Nii(sselfs _build_objsusers_savessessionscommitsrefreshsmaxsuserssrangesisappendspyamfs get_encodersAMF3sencoders writeElementsstreamsgetvaluesencodeds get_decoders readElementsdecodeds assertEqualssid(sselfsdecodedsuserssismaxsencodersusersencoded((sDbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_sqlalchemy.pys"test_encode_decode_with_referencess     (s__name__s __module__s _test_objstest_encode_decode_transientstest_encode_decode_persistentstest_encode_decode_lists test_sa_merges"test_encode_decode_with_references(((sDbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_sqlalchemy.pys SATestCases    sBaseClassAliasTestCasecBstZdZRS(NcCs#ti|tit|_dS(N(s BaseTestCasessetUpsselfspyamfsget_class_aliassUsersalias(sself((sDbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_sqlalchemy.pyssetUps (s__name__s __module__ssetUp(((sDbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_sqlalchemy.pysBaseClassAliasTestCasessClassAliasTestCasecBs5tZdZdZdZdZdZRS(NcCs|i|iitidS(N(sselfs assertEqualssaliass __class__sadaptersSaMappedClassAlias(sself((sDbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_sqlalchemy.pys test_typescCst|it|id|iitit}|i t|id|i t |t |iidS(Nsmapper( sselfs assertFalseshasattrsaliasscompilesadapters class_mappersUsersmappers assertTrues assertEqualssid(sselfsmapper((sDbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_sqlalchemy.pystest_get_mappers  cCsr|i}|ii|\}}|i|idddddg|i|hdt g<dg<dS(Nsids lazy_loadeds addressessnamesanother_lazy_loadedssa_keyssa_lazy( sselfs _build_objsusaliassgetEncodableAttributessstaticsdynamics assertEqualsskeyssNone(sselfsstaticsusdynamic((sDbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_sqlalchemy.pystest_get_attrss %cCs|i}|i||ij|itg|idi||i i |\}}|i|hd|i <d|i<dg<dt<dd<|i|hdg<d tg<dS( Nsusers addressess lazy_loadedsanother_lazy_loadedsidsnames test_userssa_lazyssa_key(sselfs _build_objsus assertFalsessessions assertEqualssNonesmapperssprimary_key_from_instancesaliassgetEncodableAttributessstaticsdynamics addressess lazy_loaded(sselfsstaticsusdynamic((sDbuild/bdist.linux-x86_64/egg/pyamf/tests/adapters/test_sqlalchemy.pystest_get_attributess  #CcCs/dtfdY}t||id|id= 1.2.6 uuid>=1.30 [cython] Cython>=0.10 [wsgi] wsgiref [sqlalchemy] SQLAlchemy>=0.4 [twisted] Twisted>=2.5.0 [django] Django>=0.96PK6u3; EGG-INFO/top_level.txtcpyamf pyamf PK6u3;2EGG-INFO/zip-safe PK:u3;V z!EGG-INFO/native_libs.txtcpyamf/util.so cpyamf/amf3.so PK:'ADcpyamf/__init__.pyPK:u3;``cpyamf/util.soPK:u3;HC<`cpyamf/amf3.soPK:u3;>v Ycpyamf/__init__.pycPK:u3;%Zcpyamf/util.pyPK:u3;G.\cpyamf/amf3.pyPK:u3; ,,l]cpyamf/util.pycPK:u3;i,,_cpyamf/amf3.pycPK.; sC bpyamf/sol.pyPK p3;wVVHypyamf/__init__.pyPK.;kWnhh =pyamf/amf0.pyPK.;z pyamf/amf3.pyPK:u3;clܧ rpyamf/sol.pycPK:u3;Ԍ]pyamf/__init__.pycPK:u3;zI>U|U| pyamf/amf0.pycPK:u3;7ppq pyamf/amf3.pycPK:- pyamf/adapters/_sqlalchemy_orm_collections.pyPKR:I&X pyamf/adapters/_array.pyPKm; pyamf/adapters/_google_appengine_ext_db.pyPK:u3;t.m pyamf/adapters/_sqlalchemy_orm_collections.pycPK:u3;4 ++p pyamf/adapters/_array.pycPK:u3; Bs pyamf/adapters/_collections.pycPK:u3;#DDdu pyamf/adapters/_decimal.pycPK:u3;rWz pyamf/adapters/_sets.pycPK:u3;S655} pyamf/adapters/util.pycPK:u3;/p99* pyamf/adapters/_django_db_models_query.pycPK:u3;8W" pyamf/adapters/_sqlalchemy_orm.pycPK:u3;1: : × pyamf/adapters/__init__.pycPK:u3;ّ+6 pyamf/adapters/_django_db_models_fields.pycPK:u3;!G,6 pyamf/adapters/_django_utils_translation.pycPK:u3;gfD)D))6 pyamf/adapters/_django_db_models_base.pycPKG$;~~>P>P pyamf/remoting/__init__.pyPKǠ;O~7' pyamf/remoting/amf0.pyPK^;@7 pyamf/remoting/amf3.pyPK:u3;' r r`M pyamf/remoting/__init__.pycPK:u3;w pyamf/remoting/amf0.pycPK:u3;y pyamf/remoting/amf3.pycPKG$;ٜ pyamf/remoting/gateway/wsgi.pyPKG$; pyamf/remoting/gateway/google.pyPKp3;;=2##pyamf/flex/__init__.pyPK:u3;' pyamf/flex/data.pycPK:u3;7٤QQpyamf/flex/messaging.pycPK:u3;M/,,,&Rpyamf/flex/__init__.pycPK:O3.K.K#pyamf/tests/remoting/test_client.pyPK:Jtt pyamf/tests/remoting/__init__.pyPKǠ;2=)>pyamf/tests/remoting/test_remoteobject.pyPK:u3;8oo$Epyamf/tests/remoting/test_client.pycPK:u3;܄!iZpyamf/tests/remoting/__init__.pycPK:u3;]{7{7*l[pyamf/tests/remoting/test_remoteobject.pycPKG$; >\ /pyamf/tests/gateway/test_wsgi.pyPKG$;%mm m "Epyamf/tests/gateway/test_google.pyPK:wpyamf/tests/gateway/__init__.pyPKG$;26Q"pyamf/tests/gateway/test_django.pyPK,;$dd#pyamf/tests/gateway/test_twisted.pyPK:u3;[,,!=8pyamf/tests/gateway/test_wsgi.pycPK:u3;T#epyamf/tests/gateway/test_google.pycPK:u3;# V{pyamf/tests/gateway/__init__.pycPK:u3;g+''#i|pyamf/tests/gateway/test_django.pycPK:u3;3m$]pyamf/tests/gateway/test_twisted.pycPK;C[k#upyamf/tests/adapters/test_google.pyPKR:cA$$"pyamf/tests/adapters/test_array.pyPK :K+mm(&pyamf/tests/adapters/test_collections.pyPK:P:ll "pyamf/tests/adapters/__init__.pyPK.;