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

查看:284
本文介绍了如何在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,其开发服务器是基于stdlib的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

你好,世界!在localhost: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天全站免登陆