使用Python编写免安装运行时、以Windows后台服务形式运行的WEB服务器

构建环境

  • 安装python2.7
  • 安装Setup Tools

https://pypi.python.org/pypi/setuptools获取安装脚本的链接http://peak.telecommunity.com/dist/ez_setup.py,下载并运行

  • 使用Setup Tools自动下载安装webpy库

运行"C:\Python27\Scripts>easy_install.exe web.py"

  • 手动下载安装pywin32库

http://sourceforge.net/projects/pywin32/files/pywin32/Build%20218/

  • 下载并安装py2exe(也可使用PyInstaller、cxfreeze打包python程序)



编写脚本

  • WebServer.py

import web



class WebServer(web.auto_application): 

  def run(self, port, *middleware): 

      func = self.wsgifunc(*middleware) 

      return web.httpserver.runsimple(func, ('0.0.0.0', port)) 



app = WebServer() 



##########################web services

class hello(app.page): 

    def GET(self): 

        return 'Hello,world' 



class visit(app.page):

    path = '/visit/.*'

    def GET(self): 

        return 'you are visiting '+web.ctx.path

##########################

      

def main():

    app.run(port=8089)



if __name__ == "__main__": 

    main()



  • WindowsService.py

import win32serviceutil

import win32service

import win32event

import thread



def log(message):

        logger = file("e:\log.txt","a")

        logger.write(message+"\r\n")

        logger.close()





class WindowsService(win32serviceutil.ServiceFramework):

        #这两行必须

        _svc_name_ = ""

        _svc_display_name_ = ""

        

        def __init__(self, args):

                win32serviceutil.ServiceFramework.__init__(self, args)

                self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

                

        def SvcStop(self):

                self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)

                win32event.SetEvent(self.hWaitStop)

                

        def SvcDoRun(self):

                import WebServer

                thread.start_new(WebServer.main, ())

                win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)

  • setup.py

# mysetup.py

from distutils.core import setup

import py2exe



setup(service=["WindowsService"])



打包成独立可执行文件

python setup.py py2exe



安装为windows服务并运行

sc create MyPythonServer binPath= f:\desktop\dist\WindowsService.exe

sc start MyPythonServer

在浏览器中访问:”http://127.0.0.1:8089/visit/whatever“,结果显示"you are visiting /visit/whatever"



下载



参考

python访问REST
  
用Python实现CRUD功能REST服务
  
Getting RESTful with web.py
  
Web.py初探:安装与HelloWorld
  
使用py2exe制作免运行时的可执行文件
  
Web.py初探:安装与HelloWorld
  
Create win32 services using Python and py2exe


Python在windows下打包exe程序
  

你可能感兴趣的:(windows)