Python中BaseHTTPRequestHandler實(shí)現(xiàn)簡(jiǎn)單的API接口
BaseHTTPRequestHandler介紹
這是一個(gè)以TCPServer為基礎(chǔ)開發(fā)的模塊,可以在請(qǐng)求外層添加http協(xié)議報(bào)文,發(fā)送http協(xié)議。
#! /usr/bin/env python3 # -*- coding:UTF-8 -*- from http.server import HTTPServer, BaseHTTPRequestHandler import json import cgi import datetime host = ('',8003) engine = create_engine('mysql+pymysql://pointgrab_user:pointgrabAaaa1111@rm-bp1d2s03ka9b803602o.mysql.rds.aliyuncs.com:3306/pointgrab_info',echo=False) class TodoHandler(BaseHTTPRequestHandler): ? ? def do_GET(self): ? ? ? ? self.send_error(415, 'Only post is supported') ? ? def do_POST(self): ? ? ? ? ctype, pdict = cgi.parse_header(self.headers['content-type']) ? ? ? ? # print(ctype, pdict) ? ? ? ? token = self.headers['X-Auth-Token'] ? ? ? ? # print(token) ? ? ? ? if token == 'token' and ctype == 'application/json': ? ? ? ? ? ? path = str(self.path) ?# 獲取請(qǐng)求的url ? ? ? ? ? ? if path == '/api/counting/': ? ? ? ? ? ? ? ? # print(path) ? ? ? ? ? ? ? ? length = int(self.headers['content-length']) ?# 獲取除頭部后的請(qǐng)求參數(shù)的長(zhǎng)度 ? ? ? ? ? ? ? ? datas = self.rfile.read(length) # 獲取請(qǐng)求參數(shù)數(shù)據(jù),請(qǐng)求數(shù)據(jù)為json字符串 ? ? ? ? ? ? ? ? # print(datas) ? ? ? ? ? ? ? ? rjson = json.loads(datas.decode()) ? ? ? ? ? ? ? ? # print(rjson,type(rjson)) ? ? ? ? ? ? ? ? countingdf = counting(rjson) ? ? ? ? ? ? ? ? data_into_sql(countingdf) ? ? ? ? ? ? ? ? self.send_response(200) ? ? ? ? ? ? ? ? self.send_header('Content-type', 'application/json') ? ? ? ? ? ? ? ? self.end_headers() ? ? ? ? ? ? ? ? self.wfile.write(json.dumps('Counting data is inserted').encode()) ? ? ? ? ? ? elif path == '/api/traffic/': ? ? ? ? ? ? ? ? # print(path) ? ? ? ? ? ? ? ? length = int(self.headers['content-length']) ?# 獲取除頭部后的請(qǐng)求參數(shù)的長(zhǎng)度 ? ? ? ? ? ? ? ? datas = self.rfile.read(length) # 獲取請(qǐng)求參數(shù)數(shù)據(jù),請(qǐng)求數(shù)據(jù)為json字符串 ? ? ? ? ? ? ? ? # print(datas) ? ? ? ? ? ? ? ? rjson = json.loads(datas.decode()) ? ? ? ? ? ? ? ? # print(rjson,type(rjson)) ? ? ? ? ? ? ? ? trafficdf = traffic(rjson) ? ? ? ? ? ? ? ? data_into_sql(trafficdf) ? ? ? ? ? ? ? ? self.send_response(200) ? ? ? ? ? ? ? ? self.send_header('Content-type', 'application/json') ? ? ? ? ? ? ? ? self.end_headers() ? ? ? ? ? ? ? ? self.wfile.write(json.dumps('Traffic data is inserted').encode()) ? ? ? ? ? ? else: ? ? ? ? ? ? ? ? self.send_error(404, "Not Found") ? ? ? ? else: ? ? ? ? ? ? self.send_error(415, "Only json data is supported.") if __name__ == '__main__': ? ? server = HTTPServer(host, TodoHandler) ? ? print("Starting server, listen at: %s:%s" % host) ? ? server.serve_forever()
請(qǐng)求代碼
POST /api/counting/ HTTP/1.1
Host: 127.0.0.1:8003
Content-Type: application/json
X-Auth-Token: token
Accept: */*
Host: 127.0.0.1:8003
content-length: 126
Connection: keep-alive
cache-control: no-cache{"areaId":"vQ_82PjcQFyt5LHA_751sg","devices":["R3QAztuSQZusLP5Fz9jVXg"],"count":2,"type":"COUNTING","timestamp":1526376098800}
BaseHTTPServer:
主要包含兩個(gè)類HTTPServer和BaseHTTPRequestHandler
- HTTPServer:
繼承SocketServer.TCPServer,用于獲取請(qǐng)求,并將請(qǐng)求分配給應(yīng)答程序處理 - BaseHTTPRequestHandler:
繼承SocketServer.StreamRequestHandler,對(duì)http連接的請(qǐng)求作出應(yīng)答(response)
基于BaseHTTPServer 的Http Server的處理流程:
HTTPServer綁定對(duì)應(yīng)的應(yīng)答類(BaseHTTPRequestHandler )
http_server = HTTPServer(('', int(port)), ServerHTTP)
監(jiān)聽端口:
http_server.serve_forever()
serve_forever()方法使用select.select()循環(huán)監(jiān)聽請(qǐng)求,當(dāng)接收到請(qǐng)求后調(diào)用
當(dāng)監(jiān)聽到請(qǐng)求時(shí),取出請(qǐng)求對(duì)象
應(yīng)答:
創(chuàng)建新線程以連接對(duì)象(開始理解成請(qǐng)求對(duì)象)為參數(shù)實(shí)例化應(yīng)答類:ServerHTTP()應(yīng)答類根據(jù)請(qǐng)求方式調(diào)用ServerHTTP.do_XXX處理方法
常用方法/屬性:
BaseHTTPRequestHandler.path ? ? ? ? ? ? ? ? ? ?#包含的請(qǐng)求路徑和GET請(qǐng)求的數(shù)據(jù) BaseHTTPRequestHandler.command ? ? ? ? ? ? ? ? #請(qǐng)求類型GET、POST... BaseHTTPRequestHandler.request_version ? ? ? ? #請(qǐng)求的協(xié)議類型HTTP/1.0、HTTP/1.1 BaseHTTPRequestHandler.headers ? ? ? ? ? ? ? ? #請(qǐng)求的頭 BaseHTTPRequestHandler.responses ? ? ? ? ? ? ? #HTTP錯(cuò)誤代碼及對(duì)應(yīng)錯(cuò)誤信息的字典 BaseHTTPRequestHandler.handle() ? ? ? ? ? ? ? ?#用于處理某一連接對(duì)象的請(qǐng)求,調(diào)用handle_one_request方法處理 BaseHTTPRequestHandler.handle_one_request() ? ?#根據(jù)請(qǐng)求類型調(diào)用do_XXX()方法,XXX為請(qǐng)求類型 BaseHTTPRequestHandler.do_XXX() ? ? ? ? ? ? ? ?#處理請(qǐng)求 BaseHTTPRequestHandler.send_error() ? ? ? ? ? ?#發(fā)送并記錄一個(gè)完整的錯(cuò)誤回復(fù)到客戶端,內(nèi)部調(diào)用send_response()方法實(shí)現(xiàn) BaseHTTPRequestHandler.send_response() ? ? ? ? #發(fā)送一個(gè)響應(yīng)頭并記錄已接收的請(qǐng)求 BaseHTTPRequestHandler.send_header() ? ? ? ? ? #發(fā)送一個(gè)指定的HTTP頭到輸出流。 keyword 應(yīng)該指定頭關(guān)鍵字,value 指定它的值 BaseHTTPRequestHandler.end_headers() ? ? ? ? ? #發(fā)送一個(gè)空白行,標(biāo)識(shí)發(fā)送HTTP頭部結(jié)束 BaseHTTPRequestHandler.wfile ? ?#self.connection.makefile('rb', self.wbufsize) self.wbufsize = -1 應(yīng)答的HTTP文本流對(duì)象,可寫入應(yīng)答信息 BaseHTTPRequestHandler.rfile ? ?#self.connection.makefile('wb', self.rbufsize) self.rbufsize = 0 ?請(qǐng)求的HTTP文本流對(duì)象,可讀取請(qǐng)求信息
cgi.parse_header(string)
解析HTTP報(bào)頭字段(如'content-type’ )之后提供的數(shù)據(jù)。
數(shù)據(jù)將被分解為一個(gè)主值和一個(gè)次要參數(shù)的字典、并以元組的形式返回。
到此這篇關(guān)于Python中BaseHTTPRequestHandler實(shí)現(xiàn)簡(jiǎn)單的API接口的文章就介紹到這了,更多相關(guān)BaseHTTPRequestHandler實(shí)現(xiàn)API接口內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python使用OS模塊操作系統(tǒng)接口及常用功能詳解
os是?Python?標(biāo)準(zhǔn)庫中的一個(gè)模塊,提供了與操作系統(tǒng)交互的功能,在本節(jié)中,我們將介紹os模塊的一些常用功能,并通過實(shí)例代碼詳細(xì)講解每個(gè)知識(shí)點(diǎn)2023-06-06python中關(guān)于時(shí)間和日期函數(shù)的常用計(jì)算總結(jié)(time和datatime)
python中關(guān)于時(shí)間和日期函數(shù)有time和datatime使用介紹,需要的朋友可以參考下2013-03-03Python實(shí)現(xiàn)的監(jiān)測(cè)服務(wù)器硬盤使用率腳本分享
這篇文章主要介紹了Python實(shí)現(xiàn)的監(jiān)測(cè)服務(wù)器硬盤使用率腳本分享,本文腳本適應(yīng)windows和linux系統(tǒng),需要的朋友可以參考下2014-11-11Win10下安裝CUDA11.0+CUDNN8.0+tensorflow-gpu2.4.1+pytorch1.7.0+p
這篇文章主要介紹了Win10下安裝CUDA11.0+CUDNN8.0+tensorflow-gpu2.4.1+pytorch1.7.0+paddlepaddle-gpu2.0.0,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03Python如何爬取實(shí)時(shí)變化的WebSocket數(shù)據(jù)的方法
這篇文章主要介紹了Python如何爬取實(shí)時(shí)變化的WebSocket數(shù)據(jù)的方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03Python namedtuple命名元組實(shí)現(xiàn)過程解析
這篇文章主要介紹了Python namedtuple命名元組實(shí)現(xiàn)過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-01-01使用python統(tǒng)計(jì)文件行數(shù)示例分享
當(dāng)文件的尺寸非常大的時(shí)候(10G之上吧),想知道行數(shù)是個(gè)問題,提供一個(gè)使用python統(tǒng)計(jì)文件行數(shù)的示例,需要的朋友可以參考下2014-02-02