如何在 Flask 中获取当前端口号? [英] How to get the current port number in Flask?

查看:87
本文介绍了如何在 Flask 中获取当前端口号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Flask,如何获取flask 连接的当前端口号?我想使用端口 0 在随机端口上启动服务器,但我还需要知道我在哪个端口上.

Using Flask, how can I get the current port number that flask is connected to? I want to start a server on a random port using port 0 but I also need to know which port I am on.

编辑

我想我已经找到了解决我的问题的方法,尽管它不是问题的答案.我可以遍历以 49152 开头的端口,并尝试通过 app.run(port=PORT) 使用该端口.我可以在 try catch 块中执行此操作,以便如果我收到 Address already in use 错误,我可以尝试下一个端口.

I think I've found a work around for my issue, although it isn't an answer to the question. I can iterate through ports starting with 49152 and attempt to use that port through app.run(port=PORT). I can do this in a try catch block so that if I get an Address already in use error, I can try the next port.

推荐答案

你不能轻易得到 Flask 使用的服务器套接字,因为它隐藏在标准库的内部(Flask 使用 Werkzeug,它的开发服务器是基于标准库的BaseHTTPServer).

You can't easily get at the server socket used by Flask, as it's hidden in the internals of the standard library (Flask uses Werkzeug, whose development server is based on the stdlib's BaseHTTPServer).

但是,您可以自己创建一个临时端口,然后关闭创建它的套接字,然后自己使用该端口.例如:

However, you can create an ephemeral port yourself and then close the socket that creates it, then use that port yourself. For example:

# hello.py
from flask import Flask, request
import socket

app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello, world! running on %s' % request.host

if __name__ == '__main__':
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('localhost', 0))
    port = sock.getsockname()[1]
    sock.close()
    app.run(port=port)

会给你要使用的端口号.运行示例:

will give you the port number to use. An example run:

$ python hello.py 
* Running on http://127.0.0.1:34447/

并且,在浏览到 http://localhost:34447/ 时,我看到

and, on browsing to http://localhost:34447/, I see

你好,世界!在本地主机上运行:34447

Hello, world! running on localhost:34447

在我的浏览器中.

当然,如果在关闭套接字和 Flask 使用该端口打开套接字之间有其他东西使用该端口,您将收到地址正在使用"错误,但您可以在您的环境.

Of course, if something else uses that port between you closing the socket and then Flask opening the socket with that port, you'd get an "Address in use" error, but you may be able to use this technique in your environment.

这篇关于如何在 Flask 中获取当前端口号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆