zoukankan      html  css  js  c++  java
  • 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


    作者:xiao.chun(小春)
    我的独立博客:http://1few.com
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.

  • 相关阅读:
    java Map集合学习
    java web 中的WEB-INF文件夹
    java web 通过前台输入的数据(name-value)保存到后台 xml文件中
    java web前端调试手段
    java学习之多线程
    java 反射学习
    java web前端easyui(layout+tree+双tabs)布局+树+2个选项卡tabs
    java socket编程(也是学习多线程的例子)详细版----转
    rman
    oracle 分区 查询
  • 原文地址:https://www.cnblogs.com/asis/p/6842996.html
Copyright © 2011-2022 走看看