搜尋
首頁後端開發Python教學詳解python3實現的web端json通訊協議

本篇文章主要介紹了python3實現的web端json通訊協議,具有一定的參考價值,有興趣的小夥伴們可以參考一下。

之前有用python3實現過tcp協議的,後來又實現了http協議的通信,今天公司想做一個功能自動測試系統,

下午弄了一會,發現json格式的實現可以更簡單一點,代碼如下:簡單解說一下,一般與伺服器通訊分兩塊,一塊是get協議,一塊是post協議,

get協議很簡單,直接就可訪問了,post協議,實際上把data數據用起來,程序直接會自動辨別類型。

在寫的過程中遇到3個問題:

1 在實作post協定時曾經遇到錯誤,

大致說資料格式的問題,解決方法很簡單,轉為utf-8格式:bytes(data , 'utf8') ,

2 獲取到的json數據遇到裡面中文時遇到編碼問題

發現表現出0xaa0xbb0xcc0xdd這樣的編碼,json加載時調用utf8即可,使用這一句代碼:json.loads( rawtext.decode('utf8'))

3 印出json時表現出一行很長很長的字串

長長的字串看了非常痛苦,根本看不清json裡面各對象的關係,網路上說用什麼json.tool方法解決,不過那是針對命令列的,我這是在調試過程中還是希望直接打印出來,

採用如下程式碼:print (json.dumps(jsonStr, sort_keys=False, ensure_ascii = False, indent=2)) ,這裡要注意ensure_ascii必須為False,否則裡面有中文時

看到的又是0xx什麼的,indent=2表示格式化json顯示,sort_keys則表示此json無需排序


#!/usr/bin/evn python3
#coding=utf-8

# 针对web端json协议的通信库,通信协议为json,传出的data为json格式,接收的数据也是json格式
# 外界调用时可先初始化web_json类,如下所示:
# get调用
# web = web_json("http://baidu.com/")
# params = "abcd/select/100000?userID=1234&groupID=79"
# web.url_get(params)
# 
# post调用
# web = web_json("http://baidu.com/")
# params = "abcd/select/100000"
# data = '{"name": "jack", "id": "1"}'
# web.url_post(params, data)

from urllib.request import urlopen
from urllib.parse import quote
import json

class web_json:
  def __init__(self, base_url):
    self.base_url = base_url
    
  def get_url_data(self, params, data):
    web = urlopen(self.base_url + params, data)
    print (web.url)
    print ("status: " , web.status)
    rawtext = web.read()
    jsonStr = json.loads(rawtext.decode('utf8'))  
    print (json.dumps(jsonStr, sort_keys=False, ensure_ascii= False, indent=2))
    return jsonStr    
  
  # get方法
  def url_get(self, params):
    return self.get_url_data(params, None)
  
  # post方法
  def url_post(self, params, data):
    data=bytes(data, 'utf8')
    return self.get_url_data(params, data)


以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持PHP中文網。

更多詳解python3實現的web端json通訊協定相關文章請關注PHP中文網!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python:深入研究彙編和解釋Python:深入研究彙編和解釋May 12, 2025 am 12:14 AM

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

Python是一種解釋或編譯語言,為什麼重要?Python是一種解釋或編譯語言,為什麼重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

對於python中的循環時循環與循環:解釋了關鍵差異對於python中的循環時循環與循環:解釋了關鍵差異May 12, 2025 am 12:08 AM

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

循環時:實用指南循環時:實用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

Python:它是真正的解釋嗎?揭穿神話Python:它是真正的解釋嗎?揭穿神話May 12, 2025 am 12:05 AM

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

與同一元素的Python串聯列表與同一元素的Python串聯列表May 11, 2025 am 12:08 AM

concatenateListSinpythonWithTheSamelements,使用:1)operatoTotakeEpduplicates,2)asettoremavelemavphicates,or3)listcompreanspherensionforcontroloverduplicates,每個methodhasdhasdifferentperferentperferentperforentperforentperforentperfornceandordorimplications。

解釋與編譯語言:Python的位置解釋與編譯語言:Python的位置May 11, 2025 am 12:07 AM

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允許ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

循環時:您什麼時候在Python中使用?循環時:您什麼時候在Python中使用?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境