文档章节

flask的run的运行参数含义

o
 osc_g8254g7s
发布于 2019/08/19 18:32
字数 1311
阅读 18
收藏 0

精选30+云产品,助力企业轻松上云!>>>

https://www.cnblogs.com/shengulong/p/8111221.html

直接阅读源代码吧:

在flask的app.py里,查看run函数的定义

 
def run(self, host=None, port=None, debug=None, **options):
        """Runs the application on a local development server.  If the
        :attr:`debug` flag is set the server will automatically reload
        for code changes and show a debugger in case an exception happened.
     debug模式可以在代码变化后自动快速重启应用,使变化生效,同时在代码异常时打印出调试代码 
        If you want to run the application in debug mode, but disable the
        code execution on the interactive debugger, you can pass
        ``use_evalex=False`` as parameter.  This will keep the debugger's
        traceback screen active, but disable code execution.
        use_evalex参数的含义是,在代码错误时,仍然抛出错误栈,但是同时又(安全考虑)避免代码执行,这样,你在页面错误时,能看到堆栈信息,但是又没有办法使用console
        .. admonition:: Keep in Mind

           Flask will suppress any server error with a generic error page
           unless it is in debug mode.  As such to enable just the
           interactive debugger without the code reloading, you have to
           invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.
           Setting ``use_debugger`` to `True` without being in debug mode
           won't catch any exceptions because there won't be any to
           catch.
      在debug模式下,如果不使用代码变化后快速重启应用使修改代码生效的功能的话,使用参数use_reloader=False。在非debug模式下使用use_debugger参数是不会获取异常栈的 .. versionchanged:: 0.10 The default port is now picked from the ``SERVER_NAME`` variable. :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to have the server available externally as well. Defaults to ``'127.0.0.1'``. :param port: the port of the webserver. Defaults to ``5000`` or the port defined in the ``SERVER_NAME`` config variable if present. :param debug: if given, enable or disable debug mode. See :attr:`debug`. :param options: the options to be forwarded to the underlying Werkzeug server. See :func:`werkzeug.serving.run_simple` for more information. """
flask的run函数实际是调用了Werkzeug的run_simple函数,因此还有一些可用参数,可以通过options参数传递给run_simple函数
from werkzeug.serving import run_simple if host is None: host = '127.0.0.1' if port is None: server_name = self.config['SERVER_NAME'] if server_name and ':' in server_name: port = int(server_name.rsplit(':', 1)[1]) else: port = 5000 if debug is not None: self.debug = bool(debug) options.setdefault('use_reloader', self.debug) options.setdefault('use_debugger', self.debug) try: run_simple(host, port, self, **options) finally: # reset the first request information if the development server # resetted normally. This makes it possible to restart the server # without reloader and that stuff from an interactive shell. self._got_first_request = False
复制代码

 

参考wekzeug的serving.py代码

复制代码
def run_simple(hostname, port, application, use_reloader=False,
               use_debugger=False, use_evalex=True,
               extra_files=None, reloader_interval=1,
               reloader_type='auto', threaded=False, processes=1, request_handler=None, static_files=None, passthrough_errors=False, ssl_context=None): """Start a WSGI application. Optional features include a reloader, multithreading and fork support. This function has a command-line interface too:: python -m werkzeug.serving --help

 


    .. versionadded:: 0.5
       `static_files` was added to simplify serving of static files as well
       as `passthrough_errors`.

    .. versionadded:: 0.6
       support for SSL was added.

    .. versionadded:: 0.8
       Added support for automatically loading a SSL context from certificate
       file and private key.

    .. versionadded:: 0.9
       Added command-line interface.

    .. versionadded:: 0.10
       Improved the reloader and added support for changing the backend
       through the `reloader_type` parameter.  See :ref:`reloader`
       for more information.

    :param hostname: The host for the application.  eg: ``'localhost'``
    :param port: The port for the server.  eg: ``8080``
    :param application: the WSGI application to execute
    :param use_reloader: should the server automatically restart the python
                         process if modules were changed?
    :param use_debugger: should the werkzeug debugging system be used?
    :param use_evalex: should the exception evaluation feature be enabled?
    :param extra_files: a list of files the reloader should watch
                        additionally to the modules.  For example configuration
                        files.
    :param reloader_interval: the interval for the reloader in seconds.
    :param reloader_type: the type of reloader to use.  The default is
                          auto detection.  Valid values are ``'stat'`` and
                          ``'watchdog'``. See :ref:`reloader` for more
                          information.
    :param threaded: should the process handle each request in a separate
                     thread?
这个参数的含义是:是否为每个请求开启一个线程 :param processes: if greater than 1 then handle each request in a new process up to this maximum number of concurrent processes.
这个参数的含义是:是否为每一个请求开启一个进程,直到达到设置的并发进程的最大值 :param request_handler: optional parameter that can be used to replace the default one. You can use this to replace it with a different :class:`~BaseHTTPServer.BaseHTTPRequestHandler` subclass. :param static_files: a dict of paths for static files. This works exactly like :class:`SharedDataMiddleware`, it's actually just wrapping the application in that middleware before serving. :param passthrough_errors: set this to `True` to disable the error catching. This means that the server will die on errors but it can be useful to hook debuggers in (pdb etc.)
这个参数将会禁止获取错误信息,但是也意为着一旦出现错误,服务器就会挂掉。这个参数在pdb调试时,很有用处 :param ssl_context: an SSL context for the connection. Either an :class:`ssl.SSLContext`, a tuple in the form ``(cert_file, pkey_file)``, the string ``'adhoc'`` if the server should automatically create one, or ``None`` to disable SSL (which is the default).
  https的设置:默认是None """ if use_debugger: from werkzeug.debug import DebuggedApplication application = DebuggedApplication(application, use_evalex) if static_files: from werkzeug.wsgi import SharedDataMiddleware application = SharedDataMiddleware(application, static_files) def log_startup(sock): display_hostname = hostname not in ('', '*') and hostname or 'localhost' if ':' in display_hostname: display_hostname = '[%s]' % display_hostname quit_msg = '(Press CTRL+C to quit)' port = sock.getsockname()[1] _log('info', ' * Running on %s://%s:%d/ %s', ssl_context is None and 'http' or 'https', display_hostname, port, quit_msg) def inner(): try: fd = int(os.environ['WERKZEUG_SERVER_FD']) except (LookupError, ValueError): fd = None srv = make_server(hostname, port, application, threaded, processes, request_handler, passthrough_errors, ssl_context, fd=fd) if fd is None: log_startup(srv.socket) srv.serve_forever() if use_reloader: # If we're not running already in the subprocess that is the # reloader we want to open up a socket early to make sure the # port is actually available. if os.environ.get('WERKZEUG_RUN_MAIN') != 'true': if port == 0 and not can_open_by_fd: raise ValueError('Cannot bind to a random port with enabled ' 'reloader if the Python interpreter does ' 'not support socket opening by fd.') # Create and destroy a socket so that any exceptions are # raised before we spawn a separate Python interpreter and # lose this ability. address_family = select_ip_version(hostname, port) s = socket.socket(address_family, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((hostname, port)) if hasattr(s, 'set_inheritable'): s.set_inheritable(True) # If we can open the socket by file descriptor, then we can just # reuse this one and our socket will survive the restarts. if can_open_by_fd: os.environ['WERKZEUG_SERVER_FD'] = str(s.fileno()) s.listen(LISTEN_QUEUE) log_startup(s) else: s.close() # Do not use relative imports, otherwise "python -m werkzeug.serving" # breaks. from werkzeug._reloader import run_with_reloader run_with_reloader(inner, extra_files, reloader_interval, reloader_type) else: inner()
复制代码

 

 

o
粉丝 0
博文 500
码字总数 0
作品 0
私信 提问
加载中
请先登录后再评论。
Flask:文件配置方式实践及其中的各种问题记录

Windows 10家庭中文版,Python 3.6.4,Flask 1.0.2, 提示: 1.请查看本文后面的“18-07-17 11:18重大纠正” ! 2.flask run命令运行时传入参数给create_app的方法也有了,参考后面的18-07-1...

osc_vg6s3gcq
2018/07/17
5
0
18. docker 容器部署 python-redis

编写 Vagrantfile 并创建虚拟机 并虚拟机绑定外部 192.168.205.10:8888 ip:port # -- mode: ruby -- # vi: set ft=ruby : Vagrant.require_version ">= 1.6.0" boxes = [ { :name => "docker......

osc_c847shr3
2019/08/12
1
0
docker学习之快速入门

docker是一个容器,在这个容器中可以运行镜像,就好像tomcat可以运行war包一样,我们可以把项目打包成一个镜像,丢到docker里面,让它运行,同时一台物理机器可以运行多个docker容器,且他们...

Java自学之路
07/12
1
1
Flask学习笔记-PyCharm配置使用Flask-Script启动以及开启Debug模式

在PyCharm中安装Flask-Script 在上一篇文章中介绍过的如何安装Flask的插件非常方便,点击“+”号检索“flask-script”安装即可。 代码中使用Flask-Script from flask.ext.script import Man...

ykbj
2016/02/22
4.3K
2
flask学习(四):debug模式

一. 设置debug模式 1. flask 1.0之前 在app.run()中传入一个关键字参数debug,app.run(debug=True),就设置当前项目为debug模式 2. flask 1.0之后 flask更新到1.0以后,不支持使用debug=Tru...

osc_f49nm0tf
2018/09/10
2
0

没有更多内容

加载失败,请刷新页面

加载更多

聚焦餐饮行业,研究院昨发布数据显示

谈话,聚焦餐饮行业,研究院昨发布数据显示,今年上半年,全国餐饮行业招聘需求增长46.18%,平均月薪6387元.随着餐饮行业的快速发展,"如何留人"也成为餐饮企业的思考题. 记者了解到,中国饭店协会...

点击fojewio
50分钟前
20
0
3·15晚会曝光上海氪信、招财旺旺SDK包泄露隐私 后台上传交易验证码敏感信息

来源 | 央视 7月16日,央视3·15晚会曝光国美易卡、美的空调遥控器、姨妈日历、银码头等50多款软件中内嵌的SDK包读取、上传用户隐私问题。上海氪信信息技术有限公司、北京招财旺旺信息技术有...

镭射财经
59分钟前
14
0
名称=''的无效表单控件不可聚焦 - An invalid form control with name='' is not focusable

问题: I have an acute problem on my website. 我的网站上有一个严重的问题。 In Google Chrome some customers are not able to proceed to my payment page. 在Google Chrome浏览器中,某......

技术盛宴
今天
14
0
Hacker News 简讯 2020-07-17

更新时间: 2020-07-17 01:01 Let’s avoid talk of ‘chemical imbalance’: it’s people in distress - (psyche.co) 让我们避免谈论“化学失衡”:这是处于困境中的人们 得分:260 | 评论:...

FalconChen
今天
92
0
【LeetCode】 59 在排序数组中查找元素的第一个和最后一个位置

题目: 解题思路: 二分法 https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/solution/zai-pai-xu-shu-zu-zhong-cha-zhao-yuan-su-de-di-yi-/ 代......

JaneRoad
昨天
17
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部