i want to create a simple web application who use a connection to a vCenter Server, and i want to pass the variable connection between pages, instead of recreate this connection on every page.
This is the code:
#!/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)
i want to reuse the c variable (the connection to the server) in other pages, and the object who derived from this variable for example esxi (list of object).
if i run the code, flask say: global name 'esxi' is not defined
How can i do this?
In flask you can store variables on your app object and reuse them later. Example:
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]
Related
I am trying to build a web app with login and signup in the nav-bar/header. When I open the web app using index.html, the login and signup option shows at the top (in nav-bar) but when I do python -m flask run, it never shows that login/signup option. I will attach a snippet of my app.py
from distutils.log import debug
from operator import imod
from pickle import FALSE
import re
from flask import Flask,render_template,url_for,redirect,flash,request
from flask_sqlalchemy import SQLAlchemy
import os
from flask_login import LoginManager,login_user,login_required,logout_user,current_user
from flask_migrate import Migrate
from forms import RegistrationForm,LoginForm
from models import User
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
app = Flask(__name__)
#* ATTACHING DATABASE TO PROJECT FOR USER CREATION
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydb.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
#* ENCRYPTING THE PASSWORD text
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
# GENERATING SECRET-KEY
SECRET_KEY = os.urandom(32)
app.config['SECRET_KEY'] = SECRET_KEY
# CREATING THE MIGRATIONS
migrate = Migrate(app, db)
# login Manager
login_manager = LoginManager()
login_manager.login_view = 'login'
login_manager.init_app(app)
#login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
#app.route('/',methods=['GET'])
def index():
return render_template("index.html",user=current_user)
#app.route('/how_to_play')
#login_required
def how_to_play():
return render_template("how_to_play.html")
#app.route('/play')
def play():
return render_template("play.html")
#app.route('/register', methods = ['POST','GET'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
hashed_password = bcrypt.generate_password_hash(form.password1.data).decode('utf-8')
user = User(username =form.username.data, email = form.email.data,password=hashed_password)
db.session.add(user)
db.session.commit()
return redirect(url_for('login'))
return render_template('registration/registration.html', form=form)
#app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user and bcrypt.check_password_hash(user.password, form.password.data):
login_user(user)
return render_template("index.html",user=current_user)
flash('Invalid email address or Password.')
return render_template('registration/login.html', form=form)
#app.route("/logout")
def logout():
logout_user()
return render_template("index.html",user=current_user)
#app.route('/share/score/', methods = ['GET'])
def share_score():
return render_template('share_score.html')
if __name__ == "__main__":
app.run(debug=True)
Not sure where I am going wrong. Any idea would be appreciated.
Because Flask template doesn't load navbar. Route in Flask doesn't work like route in HTML. In HTML we only need add route like src="/navbar.html", but if the route isn't added in code in Flask, it does not appear when render template.
So you can follow this step https://www.geeksforgeeks.org/navigation-bars-in-flask/
**Python code I used**
As you can see in this python code I am trying to redirect the plotly graph template in flask app.
# Step – 1(import necessary library)
from flask import (Flask, render_template, request, redirect, session)
import pandas as pd
import plotly.express as px
import matplotlib.pyplot as plt
from flask.helpers import url_for
# Step – 2 (configuring your application)
app = Flask(__name__)
app.secret_key = 'xyz'
# step – 3 (creating a dictionary to store information about users)
user = {"username": "abc", "password": "123"}
# Step – 4 (creating route for login)
#app.route('/', methods=['POST', 'GET'])
def login():
if (request.method == 'POST'):
username = request.form.get('username')
password = request.form.get('password')
if username == user['username'] and password == user['password']:
session['user'] = username
return redirect('/New_temp')
return "<h1>Wrong username or password</h1>"
return render_template("login.html")
# Step -5(creating route for dashboard and logout)
#app.route('/New_temp')
def home():
if ('user' in session and session['user'] == user['username']):
return render_template('New_temp.html')
#app.route('/graph', methods=['POST'])
def graph():
return render_template('Machine_graph.html')
pass
#subprocess.call('Machine_graph.html')
#return home()
return '<h1>You are not logged in.</h1>'
# Step -7(run the app)
if __name__== '__main__':
app.run(debug=True)
Pass your Flask app into Dash object with the 'server' parameter.
dash_app = Dash(__name__, server=app, url_base_pathname='/dash/')
I am trying to integrate a Dash app into an existing Flask program with Flask-Login. If I add server=server to the Dash instance every route (even ones that don't exist!!!), except the specified routes in run (ie. /home, /login), take me to the Dash app.
Example:
localhost:500/ - Takes me to Dash app
localhost:5000/home - Takes me to home route
localhost:5000/da - Takes me to Dash App
If I remove the server=server from the Dash instance, all the path's work as I would like, but when I pull up the dashboard at localhost:5000/test I get the error 'Error Loading Layout'.
If I add a url_base_pathname='/base/' to the dash instance, the routes work, but the dashboard bypasses my login.
Code Files:
server.py:
from flask import Flask
server = Flask(__name__,instance_relative_config=False)
server.config['SECRET_KEY'] = 'secretkey'
run.py:
from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user
from server import server
from dashboard import app as app_1
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from werkzeug.serving import run_simple
server.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///login.db'
db = SQLAlchemy(server)
login_manager = LoginManager()
login_manager.init_app(server)
class User(UserMixin,db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(30), unique=True)
password = db.Column(db.String(30))
#login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
#server.route('/login')
def login():
return render_template('login.html')
#server.route('/homepage', methods=['POST'])
def homepage():
username = request.form['username']
password = request.form['password']
user = User.query.filter_by(username=username,password=password).first()
if not user:
return 'User not Found'
else:
login_user(user)
return render_template('homepage.html')
#server.route('/logout')
def logout():
logout_user()
return index()
#server.route('/')
#server.route('/home')
def index():
return render_template('index.html')
#server.route('/test')
#login_required
def dashboard():
return redirect('/dash1')
app = DispatcherMiddleware(server, {
'/dash1': app_1.server})
if __name__ == '__main__':
run_simple('0.0.0.0', 5000, app, use_reloader=True, use_debugger=True)
dashboard.py
import dash
import dash_html_components as html
from server import server
app = dash.Dash(__name__)
app.layout = html.Div('Dashboard Page')
I would appreciate any insight on this. I've been scouring the internet for the past 2 days and can't solve this. Ultimately, the best solution would be if I can figure out why there is a layout error when server=server is removed because the entire app functions other than that.
Thanks
I have a very basic flask application that I have deployed to Heroku. I am trying to define a variable that I can change when a specific function is executed. For example, if I have a variable logged_in=True, I want to be able to change it to logged_in=False when the route #app.route('/logout') is executed. Here is the code:
import os
from flask import Flask, session, request, redirect, url_for, flash, g
from flask import render_template
from flask_session import Session
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config['logged_in']=True
Session(app)
# Redirect to /login route
#app.route('/')
def index():
return redirect(url_for("login"))
# Open main login page
#app.route("/login", methods=["POST","GET"])
def login():
return render_template("login.html")
# Verify login credentials
#app.route("/login_check",methods=["POST"])
def login_check():
return redirect(url_for("main_page"),code=307) if app.config['logged_in']==True else render_template("not_logged_in.html")
#app.route("/main_page", methods=["POST"])
def main_page():
return render_template("main_page.html",name="Main page")
#app.route("/log_out", methods=["POST"])
def log_out():
app.config['logged_in']=False
return redirect(url_for("login"))
if __name__ == '__main__':
app.run(debug=True)
When I launch the app locally, the value of logged_in is set to False when logout is executed and does not change if login is triggered again. However, when I deploy the app to Heroku, the value of logged_in goes back True when login is triggered again (it's weird, the value changes sometimes, but not always).
How can I set the value of logged_in so that it does not change until I update it with a function? I tried to use session.config['logged_in']instead of app.config['logged_in'], but I had the same issue. Ideally, I want the value to be unique for each session.
Thank you
If you want to store one value to each session. No sql like redis is recommendation.
import os
from flask import Flask, session, request, redirect, url_for, flash, g
from flask import render_template
from flask_session import Session
import redis
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
app.config['SESSION_TYPE'] = 'redis'
app.config['SESSION_REDIS'] = redis.from_url('127.0.0.1:6379')
# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config['logged_in']=True
Session(app)
# Redirect to /login route
#app.route('/')
def index():
return redirect(url_for("login"))
# Open main login page
#app.route("/login", methods=["POST","GET"])
def login():
return render_template("login.html")
# Verify login credentials
#app.route("/login_check",methods=["POST"])
def login_check():
return redirect(url_for("main_page"),code=307) if app.config['logged_in']==True else render_template("not_logged_in.html")
#app.route("/main_page", methods=["POST"])
def main_page():
return render_template("main_page.html",name="Main page")
#app.route("/log_out", methods=["POST"])
def log_out():
session['key'] = 'False'
return redirect(url_for("login"))
if __name__ == '__main__':
app.run(debug=True)
I have the following code to run a Flask server:
import os
from flask import Flask, url_for, request, render_template, redirect, flash, session
from bokeh.embed import autoload_server
from bokeh.client import pull_session
app = Flask(__name__)
#app.route('/login', methods = ['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if valid_login(request.form['username'], request.form['password']):
flash("Succesfully logged in")
session['username'] = request.form.get('username')
return redirect(url_for('welcome'))
else:
error = 'Incorrect username and password'
return render_template('login.html', error = error)
#app.route('/logout')
def logout():
session.pop('username', None)
return redirect(url_for('login'))
def valid_login(username, password):
if username == password:
return True
else:
return False
#app.route('/')
def welcome():
if 'username' in session:
return render_template('welcome.html', username = session['username'])
else:
return redirect(url_for('login'))
#app.route('/Gapminder')
def gapminder():
if 'username' in session:
sessione = pull_session(app_path = "/main")
bokeh_script = autoload_server(None, app_path = "/main", session_id=sessione.id)
return render_template("gapminder.html", bokeh_script = bokeh_script)
else:
return redirect(url_for('login'))
if __name__ == '__main__':
host = os.getenv('IP', 'locahost')
port = int(os.getenv('PORT', 5000))
app.debug = True
app.secret_key = '\xc9ixnRb\xe40\xd4\xa5\x7f\x03\xd0y6\x01\x1f\x96\xeao+\x8a\x9f\xe4'
app.run(host = host, port = port)
I run the bokeh server chart with
bokeh serve main.py --allow-websocket-origin=localhost:5000 --host *
and the flask server with
python run_flask.py
Well, I can see the bokeh reder in my local enviroment at the address
localhost:5006/main
and also the flask web page with the bokeh chart, also rendered and working ok at
localhost:5000
The problem is when I try to access fro another machine in the same local network. I can see the bokeh render chart at
ip:5006/main.
The flask web page
ip:5000
is also ok except the bokeh renderer, I can't see it.
can you help me please? Thanks a lot.