【python socket編程】—— 2.解析http請求頭

前文:【python socket編程】—— 1.初探html

在上一篇文章中咱們知道,socket.accept()接受的數據是請求頭,請求頭格式是這樣的:python

POST /login HTTP/1.1
Host: 127.0.0.1:1207
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://127.0.0.1:1207/login
Content-Type: application/x-www-form-urlencoded
Content-Length: 27
Cookie: D9zb2HfPUf8RI7AOwsUZpiBq
Connection: keep-alive
Upgrade-Insecure-Requests: 1

username=Harp&password=1234

這是一個POST請求,請求頭第一行是POST /login HTTP/1.1,以空格劃分,分別是請求方法、路徑和協議,以後則是key: value形式的各類數據組成的header,咱們暫且無論每一行分別是什麼意思,而後是空行,結尾的username=Harp&password=1234body部分,表單經過POST方法提交的數據(如帳號密碼)就在這裏,GET請求則沒有body部分。請求頭的換行使用的是'/r/n'編程


編寫一個Request類,來解析請求的方法、路徑、headerbody,以下:segmentfault

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# contact: liutao25@baidu.com

from urllib.parse import unquote, quote


class Request:
    def __init__(self, r):
        self.content = r
        self.method = r.split()[0]
        self.path = r.split()[1]
        self.body = r.split('\r\n\r\n', 1)[1]

    def form_body(self):
        return self._parse_parameter(self.body)

    def parse_path(self):
        index = self.path.find('?')
        if index == -1:
            return self.path, {}
        else:
            path, query_string = self.path.split('?', 1)
            query = self._parse_parameter(query_string)
            return path, query

    @property
    def headers(self):
        header_content = self.content.split('\r\n\r\n', 1)[0].split('\r\n')[1:]
        result = {}
        for line in header_content:
            k, v = line.split(': ')
            result[quote(k)] = quote(v)
        return result

    @staticmethod
    def _parse_parameter(parameters):
        args = parameters.split('&')
        query = {}
        for arg in args:
            k, v = arg.split('=')
            query[k] = unquote(v)
        return query

下一篇文章:【python socket編程】—— 3.響應app

相關文章
相關標籤/搜索