【问题标题】:How to change the startup message when starting webpy server?启动 webpy 服务器时如何更改启动消息?
【发布时间】:2016-03-15 07:50:33
【问题描述】:

我正在使用 web.py 框架来编写一个命令行工具。我使用

启动服务器
class MyApplication(web.application):
    def run(self, port=8080, *middleware):
        func = self.wsgifunc(*middleware)
        return web.httpserver.runsimple(func, ('0.0.0.0', port))

app = MyApplication(urls, globals())
app.run(port=9090)

什么时候我会收到一条控制台消息:

http://0.0.0.0:9090/

如何将此消息覆盖为我自己的自定义消息?

【问题讨论】:

  • 为什么? web.py 告诉你它正在监听的主机和端口。这很有用。
  • 是的,但就我而言,我不希望用户看到这条消息。我想给一个自定义消息。
  • 没有用户会看到这个。它只显示在服务器上。
  • 很明显,您确实想禁止显示此消息。为什么不看web.py的源码?
  • @LutzHorn:我在命令行工具中使用 webpy,所以当命令运行时,此消息将打印在控制台上

标签: python web.py


【解决方案1】:

技术上可以通过覆盖sys.stdout来覆盖此消息

import sys
o = sys.stdout
sys.stdout = open('/dev/null', 'w')
app.run(port=9090)

这肯定会抑制所有刷新到标准输出的消息,因此您可能需要覆盖/猴子修补WSGIServer.start 方法,以分配回真正的sys.stdout 对象。

您可以在 override/monkey-patched WSGIServer.start 函数中打印任何自定义消息。

完全可行的演示:

import web
from web import httpserver
import sys


WSGIServer = httpserver.WSGIServer
stdout = sys.stdout
message = "Welcome"


def _WSGIServer(*args):
    server = WSGIServer(*args)
    start = server.start

    def _start(*args):
        sys.stdout = stdout
        print message
        start()
    server.start = _start
    return server
httpserver.WSGIServer = _WSGIServer


class MyApplication(web.application):
    def run(self, port=8080, *middleware):
        func = self.wsgifunc(*middleware)
        return web.httpserver.runsimple(func, ('0.0.0.0', port))


app = MyApplication([], globals())
sys.stdout = open('/dev/null', 'w')
app.run(port=9090)

【讨论】:

    猜你喜欢
    • 2017-12-05
    • 2014-07-24
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 2013-12-25
    • 2018-05-25
    • 1970-01-01
    • 2016-09-08
    相关资源
    最近更新 更多