如何使用Python处理来自服务器的响应?

时间:2016-02-23 20:11:49

标签: python json python-2.7

----G3wq

Com-data; name="Audio"; paramName="TEXT_TO_READ"

Content-Type: audio/x-wav;codec=pcm;bit=16;rate=16000

NContext: 6d46462d-f312-4352-bf01-0a220ed75ae4



ÿÿÿÿÿÿÿÿÿÿÿÿÿÿþÿÿÿÿÿþÿþÿþÿþÿýÿþÿþÿýÿÿÿÿÿÿÿ





    ÿÿÿÿýÿþÿýÿýÿúÿøÿúÿúÿúÿûÿþÿýÿùÿûÿüÿþÿüÿùÿúÿõÿ÷ÿóÿñÿôÿñÿïÿòÿñÿîÿîÿôÿóÿ÷ÿ÷ÿóÿõÿòÿïÿíÿðÿïÿ    ÿÿûÿïÿçÿäÿïÿïÿøÿþÿýÿóÿïÿèÿèÿàÿäÿæÿâÿìÿñÿ÷ÿøÿõÿõÿñÿïÿïÿðÿìÿæÿôÿõÿøÿúÿûÿøÿìÿóÿòÿýÿüÿûÿþÿýÿÿÿ÷ÿøÿüÿøÿõÿìÿïÿòÿ÷ÿúÿûÿ  üÿ÷ÿûÿ÷ÿ    
ÿÿÿÿòÿïÿïÿòÿýÿÿÿøÿõÿôÿîÿüÿ

þÿþÿùÿ#ÿÿøÿ
% :÷îfï

----N_NMSP_vutc5w1XobDdefsYG3wq

Content-Disposition: form-data; name="Audio"; paramName="TEXT_TO_READ"

Content-Type: audio/x-wav;codec=pcm;bit=16;rate=16000

Ne-Context: 6d46462d-f312-4352-bf01-0a220ed75ae4



‚ìÔáqâì÷ø
ûC\}IûÚ÷ö-ûMüäùøüï/˜?/.·\ÕîV’Š+³ÍcÛ¶Rúÿüÿ
âÿ±ÿ-×ÿbÿÖþ”þÓþ0ÿÎþ¾þÿ¬ÿœB“CéÛéŠ}¼ã,ÿ–ÿŽÿ=ÿ±þÿÀÅÿWÿ)N”õ¡Ïkÿîþ4þÒþ÷üÀüIýŸý¸þ'þ½üÅÿH’Z)ùÚ€ÿïûøüœýQýûúŠøéú‡þ‹âÿÿ…8^Í0Æ &ýwû?û?þbýú±ù)ÿè?´~¹¶’îuÿRýJü¡üÿ<þ¼þnþˆèr¢ÇnØnTÿûý©ý;üGû\ûsûëþ–ã‚óþt^Lçñ(»ýlÿ\K§™ýÀü—ý¢ÿ›þz ä¦ÿrÿÖ?à´åÿV=ÅiYRýÇýÿœ ‹®½éþåÿ¿ÿy‘Æýóüý%ý¦ÿ_•4ORò›³&U(ÿ?þTþ‹ÿ-ýŠúZú•ü4ÿjÿ«ûCüñþ’õ äïø‚þþ¢ÿÖþšû2úRú<üýõü¾ý~ýJG­FÕy(&èÿlþVÿ?þ‹ýÅý¤ÿwº®ÿäý—ÿœÛvþÜüýAû5þLþ!þü»ù|ü†þÂþÀÀþÉÿ“ãÙu­úNíÕ,þËü#ýfýÄæÿJþxü¶ý‘~596Žn…w?ÜGý‰ýöüáþÇþÖý7ÿœýVÿsÿC€´
öýøüþ¢”·’þ*ýBþýÝû9ýøú2üŸü   úJû²ú

ù‰·“û#÷Wüýyyþþ‰ýýòÿkÙûVüæÁâÿûù§ùAøýKoÎÿ0þð'ü™üºù%üòü?     ¼7MH.Hýúɪ5YxqÿåÿñýIþÌ

FSÉþÛüõúdùü÷¿öMõèóšò?ñóð†ðsðAð5ðððòïÐï˜ïºïðjðÅðãð†ð
ð?ïï î'îî×í£íüììÎê?é€èÂççiæˆå¢äªãÔâÝáá>àäß-à±àá‰áwáCáŒá=â¥ãAå>ç éëÂìäî[ñô÷ú9ý¤›†7Ÿ? ʼd Œ#K&Y(*?+ù,%.Þ.Q/î/,00ˆ/§.«-$,ª*E)È'!&H$?"ï5+gHë|$¼>    ˜F
Ãÿ‹ýëûuúúøn÷øõÊôxóRò^ñ€ðöï^ïòî{îÇííwìþë›ëAëÝêªêQêþéŠéîèQèœçÞæ[æøåeåå{äïãã=â?ááóàá&á'áôà­à¸àá¬áµâÄãÚäæ,çeè¶é³ëêí„ðÓòõõ÷¿úçýoY;“»àÑO"Ý$R'§)–+z-Í.û/‡0Ý0!1J11s0‡/6.Ú,h+*?(ù%q#î y
kØ L©.} åCÐÿ³ý¯ûáùø{öÒôBóîñ…ð¢ïåî0î‚íÂì.ì²ëBëâêtêê›é9éçè¦èMèèÈçwç×æFæäå˜åmåRå4åÚäZäöã?ãdã=ãWã¥ãäsäÈäå åfå;æ…çöèIêµë@íˆîðËñÞóþõ"øjú­ý`îéu
¡OÄ?ð÷„     "Ì#b%E&›'â(£)*-*ó)Ç)u)é(>(Â'?&J%Ë#á! íÁ‹%è¤wá)³2ìþþüûùïöõ9óQñ›ï=îíÀë©ê?é˜è¡ç¥æ¿ååqäääÙã¹ã?ãgãJããÖâÕâðâ1ã›ãýãKä9ääVäÀäJå+æSç@è¨è$éêIë£ìî›ïLñ
óõ<÷)ùúHü?þÿÍ–  %ýgôm¦âlLÎ0 a!  "š"<#È#ü#M$%±%/%ë#Ð","»!ó  «9¸´Åô6\
0ê>eÿþ#ý›ü½ûŠúQùaøÌ÷0÷Šöíõ’õBõïôˆôôyó*ó?óióŒó?óÑóô[ô‘ô´ôõôYõñõ‡öòöL÷{÷º÷û÷ ø?øxøîø‰ù6úÅúûoûÐûAü¡üýbý¶ý#þwþÿcÿuÿsÿzÿºÿïÿ!8A9(ÿÿÿÿÿÿÿÿ

----NMSP_vutc5w1XobDdefsYG3wq

Content-Disposition: form-data; name="QueryResult"

Content-Type: application/JSON; charset=utf-8

N-Context: 6d46462d-f312-4352-bf01-0a220ed75ae4

{"TTSStatus":"Success","result_type":"NVC_TTS_CMD","NMAS_PRFX_SESSION_ID":"23de3ddd-62b9-407c-88f0-1f81d7c1e475","NMAS_PRFX_TRANSACTION_ID":"1"}

---NNMSP_vutc5w1XobDdefsYG3wq--

我只是从服务器获取标题,二进制数据和TTSStatus,但现在我得到的只是获得标题,二进制,标题,二进制和TTSStatus。当我从服务器获取头文件,二进制数据和TTSStatus时,下面的代码工作正常。

有人可以告诉我如何修改它吗?

for part in msg.walk():
        content_type = part.get_content_type()
        payload = part.get_payload()
        try:
            #if there is no reference file exist then create one based on the response 

            if content_type == "audio/x-wav" and len(payload):
                ref_filename = get_filename('pcm', output_filename + '_ref', outputfolder)
                if not os.path.exists(ref_filename):
                    with open(ref_filename, 'wb') as f_pcm:
                        f_pcm.write(payload)

                else:
                    print "[Warning] Reference PCM file is already there"

                cur_filename = get_filename('pcm', output_filename, outputfolder)
                if len(cur_filename):
                    with open(cur_filename, 'wb') as f_pcm:
                        f_pcm.write(payload)

                else:
                    print "[ERROR] Not able to create a Response PCM file \n"

                Error_Status = compare_files(ref_filename, cur_filename)

            #copy the header or the json response from the server

            elif content_type == "application/json":
                with open(get_filename('json', output_filename, outputfolder), 'w') as f_json:
                    f_json.write(payload)
        except:
            print "\n[ERROR] Can't Create Reference PCM or Response JSON files!"
            Error_Status = 1

1 个答案:

答案 0 :(得分:1)

看来你有时会为每个请求返回两个PCM块。以前第二个条目是空的。

以下内容将在每个文件的末尾添加一个段号。它基于我的原始代码,因此您需要将更改应用于完整的当前脚本:

    data = "MIME-Version: 1.0\nContent-Type: {}\n{}".format(res.getheader('content-type'), res.read())
    msg = email.message_from_string(data)
    segment = 1

    for part in msg.walk():
        content_type = part.get_content_type()
        payload = part.get_payload()

        if content_type == "audio/x-wav" and len(payload):
            pcm_filename = '{}_{}'.format(output_filename, segment)
            segment += 1

            ref_filename = get_filename('pcm', pcm_filename + '_ref', LNG)
            if not os.path.exists(ref_filename):
                with open(ref_filename, 'wb') as f_pcm:
                    f_pcm.write(payload)

            cur_filename = get_filename('pcm', pcm_filename, LNG)
            with open(cur_filename, 'wb') as f_pcm:
                f_pcm.write(payload)

            compare_files(ref_filename, cur_filename)

        elif content_type == "application/json":
            with open(get_filename('json', output_filename, LNG), 'w') as f_json:
                f_json.write(payload)

您还可以更改以下行:

output_filename = "".join([x if x.isalnum() else "_" for x in required_text[:80]]).replace('__', '_').strip('_')

这样可以从输出文件名中删除任何双下划线或尾部下划线。

或者,如果要将所有段附加在一起,可以尝试类似以下版本的内容。不幸的是,我无法重新创建多段响应,因此无法对此进行测试,以确定是否可以将各个段附加在一起并使其仍能正常播放:

    data = "MIME-Version: 1.0\nContent-Type: {}\n{}".format(res.getheader('content-type'), res.read())
    msg = email.message_from_string(data)
    wav_data = []

    for part in msg.walk():
        content_type = part.get_content_type()
        payload = part.get_payload()

        if content_type == "audio/x-wav" and len(payload):
            wav_data.append(payload)
        elif content_type == "application/json":
            with open(get_filename('json', output_filename, LNG), 'w') as f_json:
                f_json.write(payload)

    if len(wav_data):
        payload = ''.join(wav_data)

        ref_filename = get_filename('pcm', output_filename + '_ref', LNG)
        if not os.path.exists(ref_filename):
            with open(ref_filename, 'wb') as f_pcm:
                f_pcm.write(payload)

        cur_filename = get_filename('pcm', output_filename, LNG)
        with open(cur_filename, 'wb') as f_pcm:
            f_pcm.write(payload)

        compare_files(ref_filename, cur_filename)