Flask, WTForms open multiple urls in new tab - python

I am building a small app with Flask to reboot multiple IP-based devices. I want to have a checklist of the devices that when I can go through and on submit it will open that ip/rebootpage.html. As of right now my code tries to combine all of the data from the form/rebootpage. Here is what I have so far:
app.py
from flask import Flask, render_template, redirect
from flask_wtf import FlaskForm
from wtforms import widgets,SelectMultipleField
app = Flask(__name__)
app.config['SECRET_KEY'] = "565&SDdsa7fgSdst7%6"
Test_Choices = [('10.202.214.196', '#61'), ('10.202.214.197', '#62')]
Test_Choices_NR = [('10.202.214.198', 'Net Relay 1')]
class RebootForm(FlaskForm):
available = SelectMultipleField('Available', choices=Test_Choices,
option_widget=widgets.CheckboxInput(),
widget=widgets.ListWidget(prefix_label=False))
availableNR = SelectMultipleField('Available Net Relays', choices=Test_Choices_NR,
option_widget=widgets.CheckboxInput(),
widget=widgets.ListWidget(prefix_label=False))
#app.route('/form', methods=['GET', 'POST'])
def form():
form = RebootForm()
if form.validate_on_submit():
list = '{}'.format(form.available.data).replace("'", "").replace("[", "").replace("]", "")
for each in list:
return redirect('http://{}/rc.cgi?L=uirreboot.html&c=99'.format(each))
return render_template('form.html', form=form)
if __name__ == '__main__':
app.run(debug=True)

A little asking around the IRC got me to my answer. The answer is I have to use requests (not request, there are 2 different things). My final code looks like this and works great. Note that requests makes the requests without ever opening the page.
app.py
from flask import Flask, render_template, redirect, url_for
import requests
from flask_wtf import FlaskForm
from wtforms import widgets,SelectMultipleField
app = Flask(__name__)
app.config['SECRET_KEY'] = "565&SDdsa7fgSdst7%6"
All_Selected = [('Everything', 'Entire Site')]
Test_Choices = [('10.202.214.196', '#61'), ('10.202.214.197', '#62')]
Test_Choices_NR = [('10.202.214.198', 'Net Relay 1')]
class RebootForm(FlaskForm):
all_selected = SelectMultipleField('Select All', choices=All_Selected,
option_widget=widgets.CheckboxInput(),
widget=widgets.ListWidget(prefix_label=False))
available = SelectMultipleField('Available', choices=Test_Choices,
option_widget=widgets.CheckboxInput(),
widget=widgets.ListWidget(prefix_label=False))
availableNR = SelectMultipleField('Available Net Relays', choices=Test_Choices_NR,
option_widget=widgets.CheckboxInput(),
widget=widgets.ListWidget(prefix_label=False))
#app.route('/form', methods=['GET', 'POST'])
def form():
form = RebootForm()
ugly_messages = []
if form.validate_on_submit():
ip_addresses = form.available.data
for ip_address in ip_addresses:
try:
requests.get('http://{}/rc.cgi?L=uirreboot.html&c=99'.format(ip_address))
ugly_messages.append('rebooting {}'.format(ip_address))
ugly_messages.append('Please wait 30 secs.')
except Exception:
ugly_messages.append('{} did not reboot. It may be offline.'.format(ip_address))
ip_addressesNR = form.availableNR.data
for ip_addressNR in ip_addressesNR:
try:
requests.get('http://{}/setup.cgi?L=uireboot2.html&R'.format(ip_addressNR))
ugly_messages.append('rebooting {}'.format(ip_addressNR))
ugly_messages.append('Please wait 30 secs.')
except Exception:
ugly_messages.append('{} did not reboot. It may be offline.'.format(ip_addressNR))
return "<br/>".join(ugly_messages)
return render_template('form.html', form=form)
if __name__ == '__main__':
app.run(debug=True)

Related

None value returned when trying to access variables across flask sessions

from flask import Flask, session, request, render_template
import model //model.py
app = Flask(_name__)
session.key = "randomkey"
#app.route("/", methods = ['POST', 'GET'])
def hello():
if request.method == 'POST':
//Some cide that takes input from index.html and stores in python variables
prediction = model.make_prediction(modelinput)
session["prediction"] = prediction
return render_template("index.html")
#app.route("/prediction", methods = ['POST', 'GET'])
def submit():
final_prediction = session.get("prediction", None)
return render_template("prediction.html", predic = final_prediction)
Now even though I use a session variable to pass the value between the sessions, I get a None value as the output. Why is that?
Try adding this line in your code:
from flask import Flask, session, request, render_template
import model //model.py
app = Flask(_name__)
app.config["SECRET_KEY"] = "topSecret"

I have set a secret key, but keep getting the error 'RuntimeError: A secret key is required to use CSRF.'

I am quite new with Flask, having some trouble getting this running. I have set a secret key but keep getting the same error. Any help would be greatly appreciated.
here is my code:
from flask import Flask, redirect, url_for, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField
import os
app = Flask(__name__)
SECRET_KEY = os.urandom(32)
app.config['SECRET KEY'] = 'secrfgdgret'
class LoginForm(FlaskForm):
username = StringField('username')
password = PasswordField('password')
#app.route('/')
def login():
form = LoginForm()
return render_template('login.html', form=form)
#app.route('/register')
def register():
return render_template('register.html',)
#app.route('/home')
def home():
return render_template('index.html',)
#app.route('/drive')
def drive():
return render_template('drive.html',)
#app.route('/deliver')
def deliver():
return render_template('deliver.html',)
if __name__ == '__main__':
app.run(debug=True)
As Thomas Weller suggests, add an underscore to 'SECRET KEY'-> 'SECRET_KEY' in app.config['SECRET_KEY']

Flask throws error in run_wsgi_app function

I am setting up my first Flask application and i have followed the documenation from http://flask.pocoo.org/docs/1.0/patterns/sqlite3/.
My app.py code is as follows:
from flask import Flask, g, render_template, request, jsonify
import sqlite3
app = Flask(__name__)
DATABASE = 'sql_db.db'
#app.route("/")
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)
db.row_factory = sqlite3.Row
return db
#app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
def index():
return 'It works!'
if __name__ == "__main__":
app.run(debug=True)
In the index function, I will do some queries and render a template but I can't get this basic code to work. I get the following error:
File ".../venv/lib/python2.7/site-packages/werkzeug/test.py", line 923, in run_wsgi_app
app_rv = app(environ, start_response)
TypeError: function takes exactly 1 argument (2 given)
The view function did not return a valid response. The return type must be a string, tuple, Response instance, or WSGI callable, but it was a Connection.
Any ideas?
You have #app.route("/") in wrong place. It has to be before def index().
#app.route("/")
def index():
return 'It works!'
You can even see it in doc in your link: http://flask.pocoo.org/docs/1.0/patterns/sqlite3/
this here works for me, let me know if it works.
Code:
from random import randint
from time import strftime
from flask import Flask, render_template, flash, request
from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField
from sklearn import tree
import mysql.connector
import pymysql
DEBUG = True
app = Flask(__name__, static_url_path='', static_folder='', template_folder='templates')
app.config.from_object(__name__)
app.instance_path, '/', ''
# app.config['SECRET_KEY'] = 'SjdnUends821Jsdlkvxh391ksdODnejdDw'
app.config['SECRET_KEY'] = 'owieihfwuefgw98rgw8o73rg7wgfwfgw87'
#app.route("/", methods=['GET', 'POST'])
def index():
return render_template('index.html', name = "nothing")
if __name__ == "__main__":
app.run(host='127.0.0.1', port=8080)
I think you need (app.run(host='127.0.0.1', port=8080)) but i'm not
sure
Happy codeing

Correct way to get a mongo instance in blueprints Flask

I have 3 blueprints in a flask app and the dir structure is like:
main/
__init__.py
books/
users/
authors/
apps/
Every package inisde main is a blueprint.
In my main/__init__.py i have
from flask import Flask
from flask_pymongo import PyMongo
app = Flask(__name__)
from main.users.views import users
from main.admin.views import admin
app.register_blueprint(users, url_prefix='/api/users')
MONGO_HOST = os.environ['MONGO_HOST']
MONGO_PORT = os.environ['MONGO_PORT']
app.config["MONGO_URI"] = "mongodb://{}:{}/".format(MONGO_HOST, MONGO_PORT)
mongo = PyMongo(app)
How do I access mongo inside each blueprint ? Is this even correct way of using mongo here.
in official documentation it says not to use something like db=Pymongo(app)
I guess the answer comes too late for you, but eventually it will help anyways.
I usually exclude the database-lines in an external file, e.g. database.py.
and then import the mongo instance in my app and in the blueprints, respectively. Please consider the example below. For the sake of completion and comprehension I also added other elements that make sense for the functions.
database.py
from flask_pymongo import PyMongo
mongo = PyMongo()
forms.py
from wtforms import Form
from wtforms.fields import BooleanField, PasswordField, StringField
from wtforms.validators import Email, Required
class LoginForm(Form):
email = StringField('Email', validators=[Required(), Email('Not a valid email address')])
password = PasswordField('Password',validators=[Required()])
remember = BooleanField('Remember')
authentication.py
from flask import Blueprint, redirect, render_template, request
from flask_login import LoginManager, UserMixin, current_user, login_user
from werkzeug.security import check_password_hash
from database import mongo
from forms import LoginForm
authentication = Blueprint('authentication', __name__, template_folder='templates')
login_manager = LoginManager()
login_manager.login_view = 'authentication.log_in'
#authentication.route('/login', methods=['GET', 'POST'])
def log_in():
if (current_user.is_authenticated):
return redirect(url_for('get_index'))
login_form = LoginForm(request.form)
if (request.method == 'POST'):
if (login_form.validate()):
user_collection = mongo.db.user
user = user_collection.find_one({'email':login_form.email.data})
if (user) and (check_password_hash(user['password'],
login_form.password.data)):
login_user(User(user), login_form.remember)
return redirect(url_for('get_index'))
else:
return render_template('login.html', form=login_form)
elif (request.method == 'GET'):
return render_template('login.html', form=login_form)
class User(UserMixin):
def __init__(self, user):
super()
self.id = user['_id']
self.email = user['email']
def get(user_id, mongo):
user_collection = mongo.db.user
user = user_collection.find_one({'_id':ObjectId(user_id)})
return User(user)
#login_manager.user_loader
def load_user(user_id):
return User.get(user_id, mongo)
app.py
from flask import Flask, render_template, request
from flask_login import login_required
from authentication import authentication, login_manager
from database import mongo
from forms import LoginForm
app = Flask(__name__)
app.secret_key = os.urandom(24)
app.config['MONGO_URI'] = 'mongodb:27017/app'
mongo.init_app(app)
app.register_blueprint(authentication)
login_manager.init_app(app)
#app.route('/', methods=['GET'])
#login_required
def get_index():
if (request.method == 'GET'):
render_template('index.html')
if __name__ == '__main__':
app.run(host="0.0.0.0")

Running Pyad in flask

I am attempting to run pyad in a flask app.
from flask import Flask, render_template, flash, request
from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField
from pyad import *
import folder_module
# App config.
DEBUG = True
app = Flask(__name__)
app.config.from_object(__name__)
app.config['SECRET_KEY'] = 'SECRETKEY'
class ReusableForm(Form):
uid1 = TextField('UID1:', validators=[validators.required()])
uid2 = TextField('UID2:', validators=[validators.required()])
folder = TextField('Folder Name:', validators=[validators.required()])
#app.route("/", methods=['GET', 'POST'])
def fold():
form = ReusableForm(request.form)
print(form.errors)
if request.method == 'POST':
uid1 = request.form['uid1']
uid2 = request.form['uid2']
foldername = request.form['folder']
if form.validate():
ou = pyad.adcontainer.ADContainer.from_dn("ou=Groups, dc=ad, dc=test, dc=com")
flash(ou)
else:
flash('All the form fields are required. ')
return render_template('folder.html', form=form)
if __name__ == "__main__":
app.run()
I am hoping that I can call into pyad to create a security group. But even running a query on the ad container (ou via dn in this case) gives me a win32 error. The main fail error is resulted from that line and gives the following win32types error.
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147221020), None)
I have tried running this in 32bit and 64 bit python, as well as with AD.setdefault auth.
Is there anything else I can do?
pywintypes.com error when running pyad.adgroup on flask
It looks like someone else has a similar question
I solve this error using pythoncom library inside any route.
from flask import Flask, render_template, request
import pythoncom
import pyad
#app.route('/')
def index():
pythoncom.CoInitialize()

Categories