python flask 如何修改默认端口号的方法步骤


Posted in Python onJuly 12, 2019

场景:按照github文档上启动一个flask的app,默认是用5000端口,如果5000端口被占用,启动失败。

样例代码:

from flask import Flask
 
app = Flask(__name__)
 
@app.route('/')
def hello():
  return 'Hello, World!'

启动的脚本:

$ env FLASK_APP=hello.py flask run

出错信息如下:

renjg@renjg-HP-Compaq-Pro-6380-MT:~/WorkSpace/python/django$ env FLASK_APP=index.py flask run
 * Serving Flask app "index.py"
 * Environment: production
  WARNING: Do not use the development server in a production environment.
  Use a production WSGI server instead.
 * Debug mode: off
Traceback (most recent call last):
 File "/usr/local/bin/flask", line 11, in <module>
  sys.exit(main())
 File "/usr/local/lib/python2.7/dist-packages/flask/cli.py", line 894, in main
  cli.main(args=args, prog_name=name)
 File "/usr/local/lib/python2.7/dist-packages/flask/cli.py", line 557, in main
  return super(FlaskGroup, self).main(*args, **kwargs)
 File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 717, in main
  rv = self.invoke(ctx)
 File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 1137, in invoke
  return _process_result(sub_ctx.command.invoke(sub_ctx))
 File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 956, in invoke
  return ctx.invoke(self.callback, **ctx.params)
 File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 555, in invoke
  return callback(*args, **kwargs)
 File "/usr/local/lib/python2.7/dist-packages/click/decorators.py", line 64, in new_func
  return ctx.invoke(f, obj, *args, **kwargs)
 File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 555, in invoke
  return callback(*args, **kwargs)
 File "/usr/local/lib/python2.7/dist-packages/flask/cli.py", line 771, in run_command
  threaded=with_threads, ssl_context=cert)
 File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 814, in run_simple
  inner()
 File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 774, in inner
  fd=fd)
 File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 660, in make_server
  passthrough_errors, ssl_context, fd=fd)
 File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 577, in __init__
  self.address_family), handler)
 File "/usr/lib/python2.7/SocketServer.py", line 417, in __init__
  self.server_bind()
 File "/usr/lib/python2.7/BaseHTTPServer.py", line 108, in server_bind
  SocketServer.TCPServer.server_bind(self)
 File "/usr/lib/python2.7/SocketServer.py", line 431, in server_bind
  self.socket.bind(self.server_address)
 File "/usr/lib/python2.7/socket.py", line 228, in meth
  return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use

问题:

那么该怎么指定新的端口呢?又如何查看5000端口指定的位置呢?

源码分析,首先clone github上的flask框架,然后直接grep命令查看5000的位置。

renjg@renjg-HP-Compaq-Pro-6380-MT:~/WorkSpace/python/django/flask$ grep 5000 * -nrw
docs/patterns/appdispatch.rst:28:  run_simple('localhost', 5000, application, use_reloader=True)
docs/patterns/appdispatch.rst:48:    run_simple('localhost', 5000, app,
docs/config.rst:417:   * Running on http://127.0.0.1:5000/
docs/config.rst:453:   * Running on http://127.0.0.1:5000/
docs/quickstart.rst:51:   * Running on http://127.0.0.1:5000/
docs/quickstart.rst:66:   * Running on http://127.0.0.1:5000/
docs/quickstart.rst:72:Now head over to `http://127.0.0.1:5000/ <http://127.0.0.1:5000/>`_, and you
docs/deploying/wsgi-standalone.rst:38:  $ uwsgi --http 127.0.0.1:5000 --module myproject:app
docs/deploying/wsgi-standalone.rst:55:  http_server = WSGIServer(('', 5000), app)
docs/server.rst:26:*http://localhost:5000/*.
docs/cli.rst:97:   * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
docs/cli.rst:143:   * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
docs/tutorial/static.rst:58:Go to http://127.0.0.1:5000/auth/login and the page should look like the
docs/tutorial/factory.rst:169:   * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
docs/tutorial/factory.rst:174:Visit http://127.0.0.1:5000/hello in a browser and you should see the
docs/tutorial/templates.rst:174:then go to http://127.0.0.1:5000/auth/register.
examples/javascript/README.rst:39:Open http://127.0.0.1:5000 in a browser.
examples/tutorial/README.rst:62:Open http://127.0.0.1:5000 in a browser.
<strong>flask/app.py:878:    :param port: the port of the webserver. Defaults to ``5000`` or the
flask/app.py:925:    _port = 5000
flask/cli.py:738:@click.option('--port', '-p', default=5000,</strong>
README.rst:43:   * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
tests/test_basic.py:369:    SERVER_NAME='localhost:5000',
tests/test_basic.py:377:  rv = client.get('/', 'http://localhost:5000/')
tests/test_basic.py:385:    SERVER_NAME='127.0.0.1:5000',
tests/test_basic.py:393:  rv = client.get('/', 'http://127.0.0.1:5000/')
tests/test_basic.py:1448:    SERVER_NAME='localhost.localdomain:5000'
tests/test_basic.py:1463:  rv = client.get('/', 'http://localhost.localdomain:5000')
tests/test_basic.py:1466:  rv = client.get('/', 'https://localhost.localdomain:5000')
tests/test_reqctx.py:72:    SERVER_NAME='localhost.localdomain:5000'
tests/test_reqctx.py:85:        'http://localhost.localdomain:5000/'
tests/test_reqctx.py:89:        'http://foo.localhost.localdomain:5000/'
tests/test_reqctx.py:97:      "('localhost.localdomain:5000') does not match the "

可以看到在flask/app.py 以及cli.py中有指定。那么根据启动命令flask run 实际上是启动了一个http server,然后监听了一个本地端口,等待连接。那么看看是否有相应的参数。

renjg@renjg-HP-Compaq-Pro-6380-MT:~/WorkSpace/python/django/flask$ flask --help
Traceback (most recent call last):
 File "/usr/local/lib/python2.7/dist-packages/flask/cli.py", line 529, in list_commands
  rv.update(info.load_app().cli.list_commands(ctx))
 File "/usr/local/lib/python2.7/dist-packages/flask/cli.py", line 384, in load_app
  'Could not locate a Flask application. You did not provide '
NoAppException: Could not locate a Flask application. You did not provide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module was not found in the current directory.
Usage: flask [OPTIONS] COMMAND [ARGS]...
 
 A general utility script for Flask applications.
 
 Provides commands from Flask, extensions, and the application. Loads the
 application defined in the FLASK_APP environment variable, or from a
 wsgi.py file. Setting the FLASK_ENV environment variable to 'development'
 will enable debug mode.
 
  $ export FLASK_APP=hello.py
  $ export FLASK_ENV=development
  $ flask run
 
Options:
 --version Show the flask version
 --help   Show this message and exit.
 
Commands:
 routes Show the routes for the app.
 run   Runs a development server.
 shell  Runs a shell in the app context.
renjg@renjg-HP-Compaq-Pro-6380-MT:~/WorkSpace/python/django/flask$ flask run --help
Usage: flask run [OPTIONS]
 
 Run a local development server.
 
 This server is for development purposes only. It does not provide the
 stability, security, or performance of production WSGI servers.
 
 The reloader and debugger are enabled by default if FLASK_ENV=development
 or FLASK_DEBUG=1.
 
Options:
 -h, --host TEXT         The interface to bind to.
 <strong> -p, --port INTEGER       The port to bind to.</strong>
 --cert PATH           Specify a certificate file to use HTTPS.
 --key FILE           The key file to use when specifying a
                 certificate.
 --reload / --no-reload     Enable or disable the reloader. By default
                 the reloader is active if debug is enabled.
 --debugger / --no-debugger   Enable or disable the debugger. By default
                 the debugger is active if debug is enabled.
 --eager-loading / --lazy-loader
                 Enable or disable eager loading. By default
                 eager loading is enabled if the reloader is
                 disabled.
 --with-threads / --without-threads
                 Enable or disable multithreading.
 --help             Show this message and exit.

可以看到有-p这个参数,是指定端口的,默认是5000,那么尝试修改一下。

renjg@renjg-HP-Compaq-Pro-6380-MT:~/WorkSpace/python/django$ env FLASK_APP=index.py flask run -p 5001
 * Serving Flask app "index.py"
 * Environment: production
  WARNING: Do not use the development server in a production environment.
  Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5001/ (Press CTRL+C to quit)

还一个5001的端口就成功了,由此可知,当出现一个我们不知道该如何解决问题的时候,我们可以尝试着自己分析源码,得到想要的结果。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python中为feedparser设置超时时间避免堵塞
Sep 28 Python
使用Protocol Buffers的C语言拓展提速Python程序的示例
Apr 16 Python
详解Python编程中包的概念与管理
Oct 16 Python
python结合selenium获取XX省交通违章数据的实现思路及代码
Jun 26 Python
python利用MethodType绑定方法到类示例代码
Aug 27 Python
浅谈flask源码之请求过程
Jul 26 Python
Python使用sqlalchemy模块连接数据库操作示例
Mar 13 Python
处理Selenium3+python3定位鼠标悬停才显示的元素
Jul 31 Python
Python中Flask-RESTful编写API接口(小白入门)
Dec 11 Python
Python 实现数组相减示例
Dec 27 Python
使用python客户端访问impala的操作方式
Mar 28 Python
使用Python获取字典键对应值的方法
Apr 26 Python
python pandas获取csv指定行 列的操作方法
Jul 12 #Python
Python3 执行Linux Bash命令的方法
Jul 12 #Python
Flask-WTF表单的使用方法
Jul 12 #Python
解决Python中pandas读取*.csv文件出现编码问题
Jul 12 #Python
python的debug实用工具 pdb详解
Jul 12 #Python
Flask配置Cors跨域的实现
Jul 12 #Python
python调用webservice接口的实现
Jul 12 #Python
You might like
PHP获取当前文件所在目录 getcwd()函数
2009/05/13 PHP
PHP多线程抓取网页实现代码
2010/07/22 PHP
浅析php中常量,变量的作用域和生存周期
2013/08/10 PHP
Windows下PHP开发环境搭建教程(Apache+PHP+MySQL)
2016/06/13 PHP
PHP购物车类Cart.class.php定义与用法示例
2016/07/20 PHP
PHP简单计算两个时间差的方法示例
2017/06/20 PHP
Laravel框架查询构造器简单示例
2019/05/08 PHP
js 异步处理进度条
2010/04/01 Javascript
js计算字符串长度包含的中文是utf8格式
2013/10/15 Javascript
JavaScript sup方法入门实例(把字符串显示为上标)
2014/10/20 Javascript
javascript 动态创建表格
2015/01/08 Javascript
浅谈javascript 函数属性和方法
2015/01/21 Javascript
BOM系列第二篇之定时器requestAnimationFrame
2016/08/17 Javascript
AngularJS的ng-click传参的方法
2017/06/19 Javascript
nodejs 最新版安装npm 的使用详解
2018/01/18 NodeJs
vue.js中created方法作用
2018/03/30 Javascript
vue组件实现进度条效果
2018/06/06 Javascript
Vue实现页面添加水印功能
2019/11/09 Javascript
JavaScript实现滑动门效果
2020/01/18 Javascript
Python采集腾讯新闻实例
2014/07/10 Python
python实现绘制树枝简单示例
2014/07/24 Python
Python的requests网络编程包使用教程
2016/07/11 Python
Python整型运算之布尔型、标准整型、长整型操作示例
2017/07/21 Python
python 巧用正则寻找字符串中的特定字符的位置方法
2018/05/02 Python
Numpy中矩阵matrix读取一列的方法及数组和矩阵的相互转换实例
2018/07/02 Python
python打开windows应用程序的实例
2019/06/28 Python
python 轮询执行某函数的2种方式
2020/05/03 Python
解决python图像处理图像赋值后变为白色的问题
2020/06/04 Python
出纳工作岗位责任制
2014/02/02 职场文书
中学生个人自我评价
2014/02/06 职场文书
《老山界》教学反思
2014/04/08 职场文书
建筑安全生产目标责任书
2014/07/23 职场文书
幼儿园教师暑期培训心得体会
2016/01/09 职场文书
2016高校自主招生自荐信范文
2016/01/28 职场文书
2022新作动画《福星小子》释出宣传影片 加入内田真礼&宫野真守配音演出
2022/04/08 日漫
nginx之内存池的实现
2022/06/28 Servers