Python3實現簡單的http server


前端的開發的html給我們的時候,由於內部有一些ajax請求的.json的數據,需要在一個web server中查看,每次放到http服務器太麻煩。還是直接用python造一個最方便。
最簡單的,直接用
python3 -m http.server
但是我在測試的時候發現在收到json數據的時候,由於content-type不對,部分內容顯示不出來,於是寫出來新版本.
這個版本加了幾種常見的mimetype的支持。
在Mac下使用python3 myhttpserver.py啟動。

#!/usr/bin/env python
#--coding:utf-8--

from http.server import BaseHTTPRequestHandler, HTTPServer
from os import path
from urllib.parse import urlparse

curdir = path.dirname(path.realpath(__file__))
sep = '/'

# MIME-TYPE
mimedic = [
						('.html', 'text/html'),
						('.htm', 'text/html'),
						('.js', 'application/javascript'),
						('.css', 'text/css'),
						('.json', 'application/json'),
						('.png', 'image/png'),
						('.jpg', 'image/jpeg'),
						('.gif', 'image/gif'),
						('.txt', 'text/plain'),
						('.avi', 'video/x-msvideo'),
					]

class testHTTPServer_RequestHandler(BaseHTTPRequestHandler):
	# GET
	def do_GET(self):
		sendReply = False
		querypath = urlparse(self.path)
		filepath, query = querypath.path, querypath.query
		
		if filepath.endswith('/'):
			filepath += 'index.html'
		filename, fileext = path.splitext(filepath)
		for e in mimedic:
			if e[0] == fileext:
				mimetype = e[1]
				sendReply = True

		if sendReply == True:
			try:
				with open(path.realpath(curdir + sep + filepath),'rb') as f:
					content = f.read()
					self.send_response(200)
					self.send_header('Content-type',mimetype)
					self.end_headers()
					self.wfile.write(content)
			except IOError:
				self.send_error(404,'File Not Found: %s' % self.path)

def run():
	port = 8000
	print('starting server, port', port)

	# Server settings
	server_address = ('', port)
	httpd = HTTPServer(server_address, testHTTPServer_RequestHandler)
	print('running server...')
	httpd.serve_forever()

if __name__ == '__main__':
	run()

源碼:Github-Syler-httpserver


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM