说明
全局应用对象
作用
需求
系统最多支持100个用户
公共配置
app.MAX_USER_NUM = <span class="hljs-number">100</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DefaultConfig</span><span class="hljs-params">()</span>:</span>
<span class="hljs-comment">#公共配置</span>
MAX_USER_NUM = <span class="hljs-number">3</span>
全局数据
app.USER_NUM = <span class="hljs-number">0</span>
概述
在任何视图中可以使用current_app变量访问到全局app对象
作用
app对象上的公共配置与全局数据可以在视同中通过current_app对象访问
使用
<span class="hljs-keyword">from</span> flask <span class="hljs-keyword">import</span> current_app
<span class="hljs-meta">@myApp.route("/register/", methods=["POST"])</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">register</span><span class="hljs-params">()</span>:</span>
<span class="hljs-comment"># 假设系统最多支持100个用户</span>
<span class="hljs-comment"># 判断系统中有多少个用户,是否超过上限</span>
<span class="hljs-comment"># if app.USER_NUM == app.MAX_USER_NUM:</span>
<span class="hljs-comment"># return "用户到上限,无法注册"</span>
<span class="hljs-comment"># if current_app.USER_NUM == current_app.MAX_USER_NUM:</span>
<span class="hljs-comment"># return "用户到上限,无法注册"</span>
<span class="hljs-comment"># else:</span>
<span class="hljs-comment"># current_app.USER_NUM += 1</span>
<span class="hljs-keyword">if</span> current_app.USER_NUM == current_app.config[<span class="hljs-string">"MAX_USER_NUM"</span>]:
<span class="hljs-keyword">return</span> <span class="hljs-string">"用户到上限,无法注册"</span>
<span class="hljs-keyword">else</span>:
current_app.USER_NUM += <span class="hljs-number">1</span>
<span class="hljs-keyword">return</span> <span class="hljs-string">"获取到了post参数"</span>