0

我想创建一个使用与 vCenter Server 的连接的简单 Web 应用程序,并且我想在页面之间传递变量连接,而不是在每个页面上重新创建此连接。

这是代码:

#!/bin/env python
from flask import Flask, request, redirect, render_template, session
from flask import Flask, request, redirect, render_template, session
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField
from wtforms.validators import DataRequired
from modulo import MyForm
from pyVim import connect
from pyVim.connect import SmartConnectNoSSL, Disconnect
from pyVmomi import vim


app = Flask(__name__)



@app.route('/')
def index():
 return redirect('/submit')

@app.route('/submit', methods=('GET', 'POST')) #ENTER USERNAME AND PASSWORD, SAVE ON /SUCCESS
def submit():
    form = MyForm()
    if form.validate_on_submit():
        return redirect('/success')
    return render_template('submit.html', form=form)

@app.route('/success', methods=('GET', 'POST'))    #ESTABILISH CONNECTION USING USERNAME AND PASSWORD CREDENTIALS
def success():
  form = MyForm()
 username = form.username.data
 password = form.password.data
 c = SmartConnectNoSSL(host='10.116.xxx.xxx', user=username, pwd=password)
 datacenter = c.content.rootFolder.childEntity[0]
 clusters = datacenter.hostFolder
 cluster = clusters.childEntity[0]
 esxi = cluster.host
 return render_template('success.html', esxi=esxi)

@app.route('/hosts', methods=('GET', 'POST'))
def hosts():
 macchine = request.form.getlist('host')
 for i in esxi: 
  for x in macchine:
   if i.name == x:
    do something..
     return FINISH


if __name__ == '__main__':
    app.secret_key='Secret'
    app.debug = True
    app.run(host = '0.0.0.0', port = 3000)

我想在其他页面中重用 c 变量(与服务器的连接),以及从该变量派生的对象,例如 esxi(对象列表)。

如果我运行代码,烧瓶会说:未定义全局名称“esxi”

我怎样才能做到这一点?

4

1 回答 1

1

在烧瓶中,您可以将变量存储在您的应用程序对象上并在以后重用它们。例子:

    app = Flask(__name__)
    app.c = SmartConnectNoSSL(host='10.116.xxx.xxx', user=username, pwd=password)

    # You can now reuse the connection like so
    datacenter = app.c.content.rootFolder.childEntity[0]
于 2020-07-14T19:59:56.137 回答