python學習之——網絡數據傳輸( json / xml / base64 )

json

server.py
===========================
from tornado import web
from tornado import ioloop
from tornado import httpserver
import json

# 第一種獲取年齡的方式,傳過來名字,返回對應年齡
class Get_age_1(web.RequestHandler):

    def post(self, *args, **kwargs):
        info_dict = self.request.body.decode('utf-8')
        print(info_dict)

        # 公共變量
        app = self.Application
        app._public_value = 30

        self.finish(json.dumps({'age':20}))


# 第二種獲取年齡方式,通過url的參數傳遞(get方式可以,post不可以用這種方式)
class Get_age_2(web.RequestHandler):

    def get(self, name):
        age = 20
        print(name)
        
        # 公共變量
        app = self.Application
        app._public_value = 10

        self.finish(json.dumps({"name":name, "age":age}))


class Application(web.Application):

    def __init__(self):
        handler = [
            (r'/get_age', Get_age_1),
            (r'/get_age/?(?P<name>.+)?', Get_age_2)
        ]
        web.Application.__init__(self, handlers=handler)

        # 公共變量可以這用
        self._public_value = 20


def make_app():

    ioloop_t = ioloop.IOLoop()

    httpserver_t = httpserver.HTTPServer(Application())

    httpserver_t.listen(8889)

    ioloop_t.start()


if __name__ == "__main__":

    make_app()


client.py 
===========================
import requests
import json

# 傳遞字典
url = 'http://172.56.1.78:8889/get_age'
info = {'name':'li_ming'}
r = requests.post(url, data=json.dumps(info))
result_dic = json.loads(r.content.decode("utf-8"))
print(result_dic)

# 傳遞參數
url_1 = 'http://172.56.1.78:8889/get_age/li_ming'
r_1 = requests.get(url_1)
result_dict_1 = json.loads(r_1.content.decode('utf-8'))
print(result_dict_1)

base64

import base64

# base64_demo.py 將二進制數據編碼爲可打印ASCII字符,並且可解碼爲二進制
# 支持: base16 base32 base64 base85
# 可作用文本 / URL / HTTP POST
# 現代接口: 支持 字節(bytes-like object) 的編碼 和 解碼
# 傳統接口: 支持 文件對象的編碼 和 解碼

# 字節編解碼
=============================
bytes = base64.b64encode(b'I love China')
print(bytes)

bytes = base64.b64decode(bytes)
print(bytes)

# 輸出:
b'SSBsb3ZlIENoaW5h'
b'I love China'

文件對象編解碼
=============================
# 編碼, input從文件讀取二進制數據, output寫入文件 (每76個字節後 和 末尾 插b'\n')
base64.encode(open("test.txt", "rb"), open("test_base", "wb"))
# 解碼
base64.decode(open("test_base", "rb"), open("test_new.txt", "wb"))

xml

# 解析和創建xml數據
# 傳統的接口傳的數據還是xml
# 這裏只講ElementTree, 其他兩種方式再說...-.-!
 
# 解析XML文件有三種方式:
    # 1. SAX: 適合讀取大文件,數據流形式讀取,速度快,內存佔用少,通過回調函數返回數據
    # 2. DOM: 適合讀取小文件,數據映射到內存中的樹,速度慢,耗內存
    # 3. ElementTree: 默認適合小文件, 遞增解析方式適合大中文件,數據生成元素樹,速度快,內存佔用少
 
data = '''<?xml version='1.0' encoding='utf-8'?>
        <data>
            <student name="liuyan">
                <age>21</age>
            </student>
            <student name="tanwei">
                <age>22</age>
            </student>
        </data>
        '''
 
import xml.etree.ElementTree as et
 
path = "xml.xml"  # xml裏的數據與data相同

==========================================
def et_encode():
    '''
    編碼爲xml數據
    '''
 
    # 創建
    root = et.Element("data")  # 根元素
    name = et.SubElement(root, "name", attrib={"show": "yes"})  # 子元素
    age = et.SubElement(name, "age")
    age.text = '21'
 
    et_ = et.ElementTree(root)  # 生成xml
    et_.write("new.xml", encoding="utf-8", xml_declaration=True)
    et.dump(root)  # 寫入文件
 
=============================================== 
def et_decode():
    '''
    xml數據解碼
    '''
 
    tree = et.parse(path)
    root = tree.getroot()  # 獲取根元素
    # 遍歷xml文檔
    for child in root:  # 第二層
        print(child.tag, child.attrib, child.text) # tag:元素名 attrib:屬性{key:value} text:內容
        for i in child:  # 第三層
            print(i.tag, i.attrib, i.text)
 
    # 遍歷所有age元素
    for node in root.iter("age"):
        print(node.tag, node.text)
 
    # 修改元素
    for node in root.iter("age"):
        new_year = int(node.text) + 1
        node.text = str(new_year)  # 修改值
        node.set("updated", "age")  # 添加屬性
    tree.write(path, encoding="utf-8", xml_declaration=True)
 
    # 刪除元素
    for student in root.findall("student"):  # findall()定位元素可使用XPath表達式
        age = int(student.find("age").text)
        if age > 22:
            root.remove(student)  # 刪除元素
    tree.write(path, encoding="utf-8", xml_declaration=True)
 
 
if __name__ == "__main__":
    et_encode()
    et_decode()
 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章