python如何搭建http web服务器

使用python做了些很有趣的代码封装,希望能在php+nginx里调用,因为使用了第三方库的原因很难移植,除了用php执行python命令调用外,有什么更好的办法吗?

试了下,可以用python启一下webserver来实现http server的封装。下边实现一个用http接口访问python,执行简单的时间戳转日期,用来做示范。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: python_server.py
Desc: python服务测试
"""

from BaseHTTPServer import BaseHTTPRequestHandler
from BaseHTTPServer import HTTPServer
import os
import re
import time
import urllib

#自定义处理程序,用于处理HTTP请求
class TestHTTPHandler(BaseHTTPRequestHandler):

	def do_GET(self):
	"""处理GET请求"""
		#1.页面输出模板字符串
		templateStr = '''
			<html>
				<head>
					<meta charset="utf-8">
					<title>getdate Link Generator</title>
				</head>
				<body>
					<form action="/getdate" method="GET">
					时间戳:<input maxLength=10 size=10 name=s value="1482765230"/><input type="submit" value="转换日期"/>
					</form>
					%s
				</body>
			</html>
		'''

		#2.匹配请求url
		pattern = re.compile(r'/getdate\?s=([^\&]+)')
		match = pattern.match(self.path)

		#3.获取参数并做对应处理
		dateval = ''
		if match:
			# 使用Match获得分组信息
			s = urllib.unquote(match.group(1))
			if s.isdigit():
				x = time.localtime(long(s))
				dateval = '日期:' + time.strftime('%Y-%m-%d %H:%M:%S', x)
			else:
				dateval = '传入时间戳无效'
		else:
			dateval = '请输入时间戳后点击"转换日期"按钮'

		#4.输出结果
		self.protocal_version = 'HTTP/1.1' #设置协议版本
		self.send_response(200) #设置响应状态码
		self.send_header("Welcome", "Contect") #设置响应头
		self.end_headers()
		self.wfile.write(templateStr % dateval) #输出响应内容


#启动服务函数
def start_server(port):
	http_server = HTTPServer(('', int(port)), TestHTTPHandler)
	http_server.serve_forever() #设置一直监听并接收请求


#os.chdir('/data/static') #改变工作目录到 static 目录
start_server(8010) #启动服务,监听8010端口

将以上代码保存为python_server.py,使用utf8编码。

启动服务:

python python_server.py

测试:

http://test.yanjingang.com:8010/getdate?s=1482765230

输入时间戳,点击按钮,下方显示对应的日期。

1111

当然,你可以用这个方法把python服务封装成一个后端http api供调用。

注:用python做webserver不是一个好主意,正式环境大负载场景还是要用nginx。

yan 2016.12.27 18:50

参考:http://blog.csdn.net/testcs_dn/article/details/50449048

欢迎关注下方“非著名资深码农“公众号进行交流~

One thought on “python如何搭建http web服务器

匿名进行回复 取消回复

邮箱地址不会被公开。