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.
Related
**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/')
New to Flask and Python. I've cloned a github Flask chat app example and am trying to get a referrer URL (i.e. the URL the user was in before going into my app). However, when I run the app locally, the referrer link always come back as None if the request comes from an external URL. If it is sent from within the app, I am getting the right referrer URL.
Here's the relevant bits of code. I've tried looking at previous questions, but couldn't find a solution.
My routing logic:
from flask import session, redirect, url_for, render_template, request
from . import main
from .forms import LoginForm
#main.before_request
def before_request():
print("Ref1:", request.referrer)
print("Ref2:", request.values.get("url"))
#main.route('/', methods=['GET', 'POST'])
def index():
form = LoginForm()
ip_address = request.access_route[0] or request.remote_addr
print("ip_addr:", ip_address)
if form.validate_on_submit():
session['name'] = form.name.data
session['room'] = form.room.data
return redirect(url_for('.chat'))
elif request.method == 'GET':
form.name.data = session.get('name', '')
form.room.data = session.get('room', '')
return render_template('index.html', form=form)
#main.route('/chat')
def chat():
name = session.get('name', '')
room = session.get('room', '')
if name == '' or room == '':
return redirect(url_for('.index'))
return render_template('chat.html', name=name, room=room)
My main app code is:
#!/bin/env python
from app import create_app, socketio
app = create_app(debug=True)
if __name__ == '__main__':
socketio.run(app)
Would really appreciate any advice.
Thanks!
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]
I have built a website using flask (www.csppdb.com). Sometimes when I log in as one user, log out, then login as another user I still see pages from the first user I logged in as. This problem is immediately fixed when the page is refreshed. I think this is called "caching" if I am not mistaken. Is there any way I could disable this on a site wide level so that every page that is visited needs a new refresh?
It would be like sharing your computer with a friend. He logs into Facebook, then logs out. Now you log in on his computer and you see his profile... (awkward). After you refresh the page the problem is fixed.
Here is some of my code. I was using flask-login but I then tried to "roll my own"
from flask.ext.mysql import MySQL
import os
from flask import Flask, request, jsonify, session, url_for, redirect, \
render_template, g, flash
from data import *
from werkzeug import check_password_hash, generate_password_hash
import config
app = Flask(__name__)
mysql = MySQL()
app.config['MYSQL_DATABASE_HOST'] = os.environ['MYSQL_DATABASE_HOST'] if 'MYSQL_DATABASE_HOST' in os.environ else config.MYSQL_DATABASE_HOST
app.config['MYSQL_DATABASE_PORT'] = os.environ['MYSQL_DATABASE_PORT'] if 'MYSQL_DATABASE_PORT' in os.environ else config.MYSQL_DATABASE_PORT
app.config['MYSQL_DATABASE_USER'] = os.environ['MYSQL_DATABASE_USER'] if 'MYSQL_DATABASE_USER' in os.environ else config.MYSQL_DATABASE_USER
app.config['MYSQL_DATABASE_PASSWORD'] = os.environ['MYSQL_DATABASE_PASSWORD'] if 'MYSQL_DATABASE_PASSWORD' in os.environ else config.MYSQL_DATABASE_PASSWORD
app.config['MYSQL_DATABASE_DB'] = os.environ['MYSQL_DATABASE_DB'] if 'MYSQL_DATABASE_DB' in os.environ else config.MYSQL_DATABASE_DB
mysql.init_app(app)
if 'SECRET_KEY' in os.environ: app.config['SECRET_KEY'] = os.environ['SECRET_KEY']
else: app.config['SECRET_KEY'] = os.urandom(24)
def connect_db(): return mysql.connect()
def check_auth():
g.user = None
if 'username' in session:
g.user = get_user(session['username'])
return
return redirect(url_for('login'))
#app.route('/')
def home():
if 'username' in session: return redirect(url_for('main'))
return render_template('home.html')
def connect_db(): return mysql.connect()
#app.teardown_request
def teardown_request(exception):
if exception: print exception
g.db.close()
#app.before_request
def before_request():
print session.keys(), session.values()
print("before request")
print ('username' in session, "in session?")
g.db = connect_db()
g.user = None
if "username" in session:
g.user = get_user(session['username'])
#app.route('/login/', methods=['GET', 'POST'])
def login():
"""Logs the user in."""
if 'username' in session:
return redirect(url_for('main'))
error = None
if request.method == 'POST':
print("login hit")
user = get_user(request.form['username'])
if user is None:
error = 'Invalid username'
print error
elif not check_password_hash(user.password, request.form['password']):
error = 'Invalid password'
print error
else:
flash('You were logged in')
print "logged in"
session['username'] = request.form['username']
g.user = request.form['username']
print error, "error"
return redirect(url_for('main'))
return render_template('login.html', error=error)
Setting the cache to be max-age=0 fixed it.
#app.after_request
def add_header(response):
"""
Add headers to both force latest IE rendering engine or Chrome Frame,
and also to cache the rendered page for 10 minutes.
"""
response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'
response.headers['Cache-Control'] = 'public, max-age=0'
return response
To stop browser caching on these sort of pages you need to set some HTTP response headers.
Cache-Control: no-cache, no-store
Pragma: no-cache
Once you do this then the browser wont cache those pages. I dont know how to do this with "flask" so I will leave that as an exercise for you :)
This question shows how to add a response header Flask/Werkzeug how to attach HTTP content-length header to file download
I'm trying to complete the Flask tutorial between this and this to have something very simple using CodernityDB instead of sqllite, and I need to execute the app to be able to study all the CodernityDB methods I need. But the server is not working properly, the localhost tell me there is an Internal error, but I can't figure out the way to debug it.
Here is my code (flaskr.py), the templates are here:
from __future__ import with_statement
from flask import Flask, request, session, g, redirect, url_for, \
abort, render_template, flash
from CodernityDB.database_thread_safe import ThreadSafeDatabase
from CodernityDB.database import RecordNotFound
# configuration
DATABASE = '/tmp/flaskr.db'
DEBUG = True
SECRET_KEY = 'development key'
# pending
USER = 'admin'
PASSWORD = 'default'
app = Flask(__name__)
##app.config.from_object(__name__)
cdb = ThreadSafeDatabase(DATABASE)
if cdb.exists():
cdb.open()
cdb.reindex()
else:
from database_indexes import WithXIndex
cdb.create()
cdb.add_index(WithXIndex(cdb.path, 'x'))
#app.before_request
def before_request():
g.db = cdb
#app.route('/')
def show_entries():
## return "Hello World! This is powered by Python Backend."
cur = db.get('x',10,with_doc=True)
entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]
return render_template('show_entries.html', entries=entries)
#app.route('/add', methods=['POST'])
def add_entry():
## return "Add new entry"
if not session.get('logged_in'):
abort(401)
g.db.insert(dict(x=request.form['title'], name=request.form['text']))
flash('New entrey was succesfully posted')
return redirect(url_for('show_entries'))
#app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != app.config['USERNAME']:
error = 'Invalid username'
elif request.form['password'] != app.config['PASSWORD']:
error = 'Invalid password'
else:
session['logged_in'] = True
flash('You were logged in')
return redirect(url_for('show_entries'))
return render_template('login.html', error=error)
#app.route('/logout')
def logout():
session.pop('logged_in', None)
flash('You were logged out')
return redirect(url_for('show_entries'))
if __name__ == '__main__':
app.run()
## app.run(host='0.0.0.0')
## app.run(debug= True)
## app.run(host='127.0.0.1', port=5000)
database_indexes.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from CodernityDB.hash_index import HashIndex
from CodernityDB.tree_index import TreeBasedIndex
from hashlib import md5
class WithXIndex(HashIndex):
def __init__(self, *args, **kwargs):
kwargs['key_format'] = 'I'
super(WithXIndex, self).__init__(*args, **kwargs)
def make_key_value(self, data):
a_val = data.get("x")
if a_val is not None:
return a_val, None
return None
def make_key(self, key):
return key
I didn't create the environment variable because I want to use another approach for the configuration, maybe a file, and the config.from_object is commented because when I executed it with it shows Restarting with stat.