Python中BaseHTTPRequestHandler實現(xiàn)簡單的API接口
BaseHTTPRequestHandler介紹
這是一個以TCPServer為基礎(chǔ)開發(fā)的模塊,可以在請求外層添加http協(xié)議報文,發(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) ?# 獲取請求的url
? ? ? ? ? ? if path == '/api/counting/':
? ? ? ? ? ? ? ? # print(path)
? ? ? ? ? ? ? ? length = int(self.headers['content-length']) ?# 獲取除頭部后的請求參數(shù)的長度
? ? ? ? ? ? ? ? datas = self.rfile.read(length) # 獲取請求參數(shù)數(shù)據(jù),請求數(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']) ?# 獲取除頭部后的請求參數(shù)的長度
? ? ? ? ? ? ? ? datas = self.rfile.read(length) # 獲取請求參數(shù)數(shù)據(jù),請求數(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()請求代碼
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:
主要包含兩個類HTTPServer和BaseHTTPRequestHandler
- HTTPServer:
繼承SocketServer.TCPServer,用于獲取請求,并將請求分配給應(yīng)答程序處理 - BaseHTTPRequestHandler:
繼承SocketServer.StreamRequestHandler,對http連接的請求作出應(yīng)答(response)
基于BaseHTTPServer 的Http Server的處理流程:
HTTPServer綁定對應(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)聽請求,當(dāng)接收到請求后調(diào)用
當(dāng)監(jiān)聽到請求時,取出請求對象
應(yīng)答:
創(chuàng)建新線程以連接對象(開始理解成請求對象)為參數(shù)實例化應(yīng)答類:ServerHTTP()應(yīng)答類根據(jù)請求方式調(diào)用ServerHTTP.do_XXX處理方法
常用方法/屬性:
BaseHTTPRequestHandler.path ? ? ? ? ? ? ? ? ? ?#包含的請求路徑和GET請求的數(shù)據(jù)
BaseHTTPRequestHandler.command ? ? ? ? ? ? ? ? #請求類型GET、POST...
BaseHTTPRequestHandler.request_version ? ? ? ? #請求的協(xié)議類型HTTP/1.0、HTTP/1.1
BaseHTTPRequestHandler.headers ? ? ? ? ? ? ? ? #請求的頭
BaseHTTPRequestHandler.responses ? ? ? ? ? ? ? #HTTP錯誤代碼及對應(yīng)錯誤信息的字典
BaseHTTPRequestHandler.handle() ? ? ? ? ? ? ? ?#用于處理某一連接對象的請求,調(diào)用handle_one_request方法處理
BaseHTTPRequestHandler.handle_one_request() ? ?#根據(jù)請求類型調(diào)用do_XXX()方法,XXX為請求類型
BaseHTTPRequestHandler.do_XXX() ? ? ? ? ? ? ? ?#處理請求
BaseHTTPRequestHandler.send_error() ? ? ? ? ? ?#發(fā)送并記錄一個完整的錯誤回復(fù)到客戶端,內(nèi)部調(diào)用send_response()方法實現(xiàn)
BaseHTTPRequestHandler.send_response() ? ? ? ? #發(fā)送一個響應(yīng)頭并記錄已接收的請求
BaseHTTPRequestHandler.send_header() ? ? ? ? ? #發(fā)送一個指定的HTTP頭到輸出流。 keyword 應(yīng)該指定頭關(guān)鍵字,value 指定它的值
BaseHTTPRequestHandler.end_headers() ? ? ? ? ? #發(fā)送一個空白行,標(biāo)識發(fā)送HTTP頭部結(jié)束
BaseHTTPRequestHandler.wfile ? ?#self.connection.makefile('rb', self.wbufsize) self.wbufsize = -1 應(yīng)答的HTTP文本流對象,可寫入應(yīng)答信息
BaseHTTPRequestHandler.rfile ? ?#self.connection.makefile('wb', self.rbufsize) self.rbufsize = 0 ?請求的HTTP文本流對象,可讀取請求信息cgi.parse_header(string)
解析HTTP報頭字段(如'content-type’ )之后提供的數(shù)據(jù)。
數(shù)據(jù)將被分解為一個主值和一個次要參數(shù)的字典、并以元組的形式返回。
到此這篇關(guān)于Python中BaseHTTPRequestHandler實現(xiàn)簡單的API接口的文章就介紹到這了,更多相關(guān)BaseHTTPRequestHandler實現(xiàn)API接口內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python實現(xiàn)剪貼板中轉(zhuǎn)換C語言代碼為printf語句
這篇文章主要為大家詳細(xì)介紹了Python實現(xiàn)剪貼板中轉(zhuǎn)換C語言代碼為printf語句,可以用于運行代碼的追蹤,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2026-02-02
Python3.6簡單操作Mysql數(shù)據(jù)庫
這篇文章主要為大家詳細(xì)介紹了Python3.6簡單操作Mysql數(shù)據(jù)庫,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-09-09
Centos部署django服務(wù)nginx+uwsgi的方法
這篇文章主要介紹了Centos部署django服務(wù)nginx+uwsgi的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01

