error in Flask-Admin while extending template "admin/master.html" - python

I'm new to Flask and while following some youtube tutorials for Flask-Admin, I came across the fact that we need to create the admin panel by extending the template in "admin/index.html"
The instructor said that the 'admin/master.html' is an implicit file and we don't need to create it but do need to extend it.
But I'm getting a error message that says that the template "admin/master.html" couldn't be found.
How do I work this problem out?
This is the error log
[2023-01-05 23:13:42,958] ERROR in app: Exception on /admin/ [GET]
Traceback (most recent call last):
File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/flask/app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/flask/app.py", line 1822, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/flask/app.py", line 1820, in full_dispatch_request
rv = self.dispatch_request()
File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/flask/app.py", line 1796, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
File "/SSD_Data/DevFile/AayushPokharel/app/admin/routes.py", line 7, in adminRoute
return render_template("admin/index.html")
File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/flask/templating.py", line 147, in render_template
return _render(app, template, context)
File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/flask/templating.py", line 130, in _render
rv = template.render(context)
File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/jinja2/environment.py", line 1301, in render
self.environment.handle_exception()
File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/jinja2/environment.py", line 936, in handle_exception
raise rewrite_traceback_stack(source=source)
File "/SSD_Data/DevFile/AayushPokharel/app/templates/admin/index.html", line 1, in top-level template code
{% extends 'admin/master.html' %} {% block body %}
File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/flask/templating.py", line 62, in get_source
return self._get_source_fast(environment, template)
File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/flask/templating.py", line 98, in _get_source_fast
raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: admin/master.html
127.0.0.1 - - [05/Jan/2023 23:13:42] "GET /admin/ HTTP/1.1" 500 -
This is my admin template
<!--app/templates/admin/index.html-->
{% extends 'admin/master.html' %} {% block body %}
<p>This is Admin Page</p>
{% endblock %}
my admin init blueprint
# app/admin/__init__.py
from flask import Blueprint
from flask_admin.contrib.sqla import ModelView
from app.extensions import admin, db
from app.models.user import User
bp = Blueprint("admin", __name__)
admin.add_view(ModelView(User, db.session))
from app.admin import routes
my admin routes
# app/admin/routes.py
from flask import render_template
from app.admin import bp
#bp.route("/")
def adminRoute():
return render_template("admin/index.html")
my main app file
# app/__init__.py
# Regular Imports
from flask import Flask
# Config Import
from config import Config
# Extensions' Imports
from app.extensions import db
from app.extensions import login_manager
# Blueprints' Imports
from app.main import bp as main_bp
from app.admin import bp as admin_bp
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
# Initialize Flask extensions here
db.init_app(app)
login_manager.init_app(app)
# Register blueprints here
app.register_blueprint(main_bp)
app.register_blueprint(admin_bp, url_prefix="/admin")
# Returning created App Instance
return app

Related

jinja2.exceptions.UndefinedError: '_' is undefined

I am using flask_babel for localization of a python project.
When extracting translatable strings from templates, which is put in {{ _('') }} , i am getting the following error. If anyone of you can solve it, please share the solution here. thanks in advance.
Traceback (most recent call last):
File "/home/lungsang/.local/lib/python3.8/site-packages/flask/app.py", line 2069, in __call__
return self.wsgi_app(environ, start_response)
File "/home/lungsang/.local/lib/python3.8/site-packages/flask/app.py", line 2054, in wsgi_app
response = self.handle_exception(e)
File "/home/lungsang/.local/lib/python3.8/site-packages/flask/app.py", line 2051, in wsgi_app
response = self.full_dispatch_request()
File "/home/lungsang/.local/lib/python3.8/site-packages/flask/app.py", line 1501, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/lungsang/.local/lib/python3.8/site-packages/flask/app.py", line 1499, in full_dispatch_request
rv = self.dispatch_request()
File "/home/lungsang/.local/lib/python3.8/site-packages/flask/app.py", line 1485, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "/mnt/c/Users/Lungsang/Desktop/new-pyrrha/pyrrha/app/main/views/index.py", line 34, in index
return render_template_with_nav_info('main/index.html')
File "/mnt/c/Users/Lungsang/Desktop/new-pyrrha/pyrrha/app/main/views/utils.py", line 60, in render_template_with_nav_info
return render_template(template, **kwargs)
File "/home/lungsang/.local/lib/python3.8/site-packages/flask/templating.py", line 147, in render_template
return _render(
File "/home/lungsang/.local/lib/python3.8/site-packages/flask/templating.py", line 128, in _render
rv = template.render(context)
File "/home/lungsang/.local/lib/python3.8/site-packages/jinja2/environment.py", line 1289, in render
self.environment.handle_exception()
File "/home/lungsang/.local/lib/python3.8/site-packages/jinja2/environment.py", line 924, in handle_exception
raise rewrite_traceback_stack(source=source)
File "/mnt/c/Users/Lungsang/Desktop/new-pyrrha/pyrrha/app/templates/main/index.html", line 1, in top-level template code
{% extends 'layouts/base.html' %}
File "/mnt/c/Users/Lungsang/Desktop/new-pyrrha/pyrrha/app/templates/layouts/base.html", line 36, in top-level template code
{% block content %}{% endblock %}
File "/mnt/c/Users/Lungsang/Desktop/new-pyrrha/pyrrha/app/templates/main/index.html", line 5, in block 'content'
<h1>{{ _('Welcome to Pyrrha !') }}</h1>
File "/home/lungsang/.local/lib/python3.8/site-packages/jinja2/utils.py", line 81, in from_obj
if hasattr(obj, "jinja_pass_arg"):
jinja2.exceptions.UndefinedError: '_' is undefined
#MAIN APP FILE
from flask_login import current_user
from flask import request , Flask
from flask_babel import Babel
from .utils import render_template_with_nav_info
from .. import main
from ...models import Corpus
from ...utils.pagination import int_or
app = Flask(__name__)
app.config['BABEL_DEFAULT_LOCALE'] = 'en'
babel = Babel(app)
#babel.localeselector
def get_locale():
#return request.accept_languages.best_match(['es', 'fr', 'en'])
return 'bo_CN'
#main.route('/')
def index():
if current_user.is_authenticated and not
current_user.is_anonymous:
corpora = Corpus.for_user(current_user, _all=False).paginate(
page=int_or(request.args.get("page"), 1),
per_page=20 # ToDo: Should it be hardcoded ?
)
return render_template_with_nav_info("main/index_loggedin.html", corpora=corpora)
return render_template_with_nav_info('main/index.html')
TEMPLATE FILE (index.html)
{% extends 'layouts/base.html' %}
{% block content %}
<div class="ui text container">
<h1>{{ _('Welcome to Pyrrha !') }}</h1>
<p>Pyrrha is a simple Python Flask WebApp to fasten the post-correction of lemmatized and morpho-syntactic tagged corpora.</p>
<p>It is under active development at the École Nationale des Chartes and can
be found on github.</p>
<p>To cite it in a paper, please use the information available on Zenodo</p>
</div>
{% endblock %}
After applying the following codes in init.py module, its working fine. Thank you
babel = Babel(app)
#babel.localeselector
def get_locale():
return 'es'
remove the "_" in the h1 tag in the template's file

How to use Flask Login with Blueprints

I'm trying to use LoginManager for my flask application. When I run the application and open the index page, it says the following
File "...\python38-32\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "...\python38-32\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "...\python38-32\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "...\python38-32\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "...\python38-32\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "...\python38-32\lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "...\root\project\user_auth\routes.py", line 18, in index
return render_template('index.html', title='Welcome')
File "...\python38-32\lib\site-packages\flask\templating.py", line 137, in render_template
return _render(
File "...\python38-32\lib\site-packages\flask\templating.py", line 120, in _render
rv = template.render(context)
File "...\python38-32\lib\site-packages\jinja2\environment.py", line 1090, in render
self.environment.handle_exception()
File "...\python38-32\lib\site-packages\jinja2\environment.py", line 832, in handle_exception
reraise(*rewrite_traceback_stack(source=source))
File "...\python38-32\lib\site-packages\jinja2\_compat.py", line 28, in reraise
raise value.with_traceback(tb)
File "...\root\project\user_auth\templates\index.html", line 1, in top-level template code
{% extends "base.html" %}
File "...\root\project\user_auth\templates\base.html", line 13, in top-level template code
{% if current_user.is_anonymous %}
File "...\python38-32\lib\site-packages\jinja2\environment.py", line 471, in getattr
return getattr(obj, attribute)
jinja2.exceptions.UndefinedError: 'current_user' is undefined
Here is my structure
root /
config.py
|project/
| __init__.py
| user_auth/
| __init__.py
| app.py
| routes.py
In the app/init.py file, it is the following
from flask import Flask
from config import Config
app = Flask(__name__)
app.config.from_object(Config)
from .user_auth.routes import user_auth_bp
app.register_blueprint(user_auth_bp, url_prefix="")
From the user_auth init.py file is
from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask import current_app
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login = LoginManager(app)
login.login_view = '.login'
app.config['SECRET_KEY'] = 'trial'
from ..user_auth import routes, models
This is the user_auth/routes.py file
from ..user_auth import app, db
from flask_login import login_required
from ..user_auth.forms import RegistrationForm, LoginForm
from flask import request, render_template, flash, redirect, url_for, Blueprint
from werkzeug.urls import url_parse
from flask_login import logout_user
from flask_login import current_user, login_user
from ..user_auth.models import User
from flask import Blueprint
user_auth_bp = Blueprint('user_auth', __name__, template_folder='templates')
#user_auth_bp.route('/')
#user_auth_bp.route('/index')
def index():
return render_template('index.html', title='Welcome')
#user_auth_bp.route('/register', methods=["POST", "GET"])
def register():
form = RegistrationForm()
if form.validate_on_submit():
print("validated")
# Create User Model
username = form.username.data
password = form.password.data
email = form.email.data
newUser = User(username=username,email=email)
newUser.set_password(password)
db.session.add(newUser)
db.session.commit()
return redirect(url_for('.index'))
else:
return render_template('register.html', title='Welcome', form=form)
... (Other paths)
I am running Windows and used the following command
set FLASK_APP=project
I then use
flask run
Thank you in advance for the help.
You can try to search same problem
UndefinedError: 'current_user' is undefined
Check the init file:
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.init_app(app)
from .models import User
#login_manager.user_loader
def load_user(user_id):
user = User.query.filter_by(id=user_id).first()
And strure, i think you should do like that

gunicorn when started using supervisor throws database error, works properly when manually started?

I have a simple flash website created and deployed in a server with Nginx as frontend and gunicorn as backend to run the python code. With this setup everything is working fine. However, if i run the server using supervisor module, I'm getting below error. I have ensured all the environment variables are accessible, they are placed in .bashrc under home directory.
Not sure what am missing. My python code is deployed in server inside a pipenv virtual environment. supervisor was started within the virtualenv only. Not sure if it has any relevance.
error log with supervisor
[2020-11-10 05:45:29,604] ERROR in app: Exception on /home [GET]
Traceback (most recent call last): File
"/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/sqlalchemy/util/_collections.py",
line 1020, in call
return self.registry[key] KeyError: 139749229659968
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask/app.py",
line 2447, in wsgi_app
response = self.full_dispatch_request() File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask/app.py",
line 1952, in full_dispatch_request
rv = self.handle_user_exception(e) File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask/app.py",
line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb) File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask/_compat.py",
line 39, in reraise
raise value File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask/app.py",
line 1950, in full_dispatch_request
rv = self.dispatch_request() File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask/app.py",
line 1936, in dispatch_request
return self.view_functionsrule.endpoint File "/home/anandraj/FlaskProject/Proj2/main/routes.py", line 12, in home
posts = Post.query.order_by(Post.date_posted.desc()).paginate(page=page,
per_page=7) File
"/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 514, in get
return type.query_class(mapper, session=self.sa.session()) File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/sqlalchemy/orm/scoping.py",
line 78, in call
return self.registry() File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/sqlalchemy/util/collections.py",
line 1022, in call
return self.registry.setdefault(key, self.createfunc()) File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/sqlalchemy/orm/session.py",
line 3300, in call
return self.class(**local_kw) File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 138, in init
bind = options.pop('bind', None) or db.engine File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 943, in engine
return self.get_engine() File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 962, in get_engine
return connector.get_engine() File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 555, in get_engine
options = self.get_options(sa_url, echo) File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 570, in get_options
self._sa.apply_driver_hacks(self._app, sa_url, options) File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 883, in apply_driver_hacks
if sa_url.drivername.startswith('mysql'): AttributeError: 'NoneType' object has no attribute 'drivername'
Supervisor config
cat /etc/supervisor/conf.d/supervisord.conf
[program:Proj2]
directory=/home/<user>/FlaskProject
command=/home/<user>/.local/share/virtualenvs/FlaskProject->tLcktdEC/bin/gunicorn -w 3 run:app
user=<user>
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
stderr_logfile=/var/log/flaskblog/Proj2Flask.err.log
stdout_logfile=/var/log/flaskblog/Proj2Flask.out.log
Error while querying DB
~/FlaskProject/Proj2/main$ cat routes.py
from flask import render_template, request, Blueprint
from Proj2.models import Post
main = Blueprint('main', __name__)
#main.route("/")
#main.route("/home")
def home():
page = request.args.get('page', 1, type=int)
posts = Post.query.order_by(Post.date_posted.desc()).paginate(page=page, per_page=7)
return render_template('home.html', posts=posts)
#main.route("/about")
def about():
return render_template('about.html', title='Anandraj')
How my app is initialized?
~/FlaskProject/Proj2$ cat __init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail
from Proj2.config import Config
db = SQLAlchemy()
bcrypt = Bcrypt()
login_mgr = LoginManager()
login_mgr.login_view = 'users.login'
login_mgr.login_message_category = 'info'
mail = Mail()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
bcrypt.init_app(app)
login_mgr.init_app(app)
mail.init_app(app)
from Proj2.users.routes import users
from Proj2.posts.routes import posts
from Proj2.main.routes import main
from Proj2.errors.handler import errors
app.register_blueprint(users)
app.register_blueprint(posts)
app.register_blueprint(main)
app.register_blueprint(errors)
return app(FlaskProject)
Can you post your supervisor config file? My guess here is that it's related to your PATH definition...
EDIT (12/Nov): After seeing you're supervisor config file I noticed that you haven't set the environment path.
A list of key/value pairs in the form KEY="val",KEY2="val2" that will be placed in the supervisord process’ environment (and as a result in all of its child process’ environments)
from: https://docs.red-dove.com/supervisor/configuration.html
Can you try adding this to your configuration file? This will define your PATH as "/usr/bin/" for the environment that runs your gunicorn. If that doesn't work, please try use the path from where your virtualenv is running.
environment=PATH="/usr/bin"

How to use flask_jwt_extended with blueprints?

I'm trying to build a blog as a portfolio sample using python3 and flask and flask_jwt_extended.
I can create a single file like this and it will run:
from flask_jwt_extended import (create_access_token, get_jwt_identity, JWTManager, jwt_required, get_raw_jwt)
from flask import Flask, request, Blueprint
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'this-is-super-secret'
app.config['JWT_BLACKLIST_ENABLED'] = True
app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access']
jwt = JWTManager(app)
#app.route(....)
#jwt required
But when I try to use Blueprint, it will not register the JWTManager
Here is my user.py file:
from flask_jwt_extended import (create_access_token, get_jwt_identity, JWTManager, jwt_required, get_raw_jwt)
from flask import Flask, request, Blueprint
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'this-is-super-secret'
app.config['JWT_BLACKLIST_ENABLED'] = True
app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access']
jwt = JWTManager(app)
user_blueprint = Blueprint('user_blueprint', __name__)
#user_blueprint.route(....)
#jwt required
here is my app.py:
from user import *
app = Flask(__name__)
app.register_blueprint(user_blueprint)
Now when I try to run app.py, this it returns a 500 (Internal Error) and will log this to the log file:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/flask_jwt_extended/utils.py", line 127, in _get_jwt_manager
return current_app.extensions['flask-jwt-extended']
KeyError: 'flask-jwt-extended'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.6/dist-packages/flask/_compat.py", line 35, in reraise
raise value
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/ali/Desktop/cetia_api/user.py", line 63, in login
return create_token(user_inputs)
File "/home/ali/Desktop/cetia_api/user_functions.py", line 103, in create_token
access_token = create_access_token(identity=data, expires_delta=expires)
File "/usr/local/lib/python3.6/dist-packages/flask_jwt_extended/utils.py", line 156, in create_access_token
jwt_manager = _get_jwt_manager()
File "/usr/local/lib/python3.6/dist-packages/flask_jwt_extended/utils.py", line 129, in _get_jwt_manager
raise RuntimeError("You must initialize a JWTManager with this flask "
RuntimeError: You must initialize a JWTManager with this flask application before using this method
Could someone please tell me what to do? I tried EVERYTHING for the last 3 days. its been 20 hours of debugging and it's still not fixed
You need to use the same app in every location. Currently you are creating an app in your users.py file, and a different app in you app.py file.
Generally you will want to use the flask application factory pattern to do this (https://flask.palletsprojects.com/en/1.1.x/patterns/appfactories/). An example might look something like this:
extensions.py
from flask_jwt_extended import JWTManager
jwt = JWTManager()
users.py
from flask_jwt_extended import (create_access_token, get_jwt_identity, jwt_required, get_raw_jwt)
from flask import Flask, request, Blueprint
user_blueprint = Blueprint('user_blueprint', __name__)
#user_blueprint.route(....)
#jwt_required
app.py
from extensions import jwt
from users import users_blueprint
def create_app():
app = Flask(__name__)
app.secret_key = 'ChangeMe!'
app.config['JWT_BLACKLIST_ENABLED'] = True
app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access']
jwt.init_app(app)
app.register_blueprint(user_blueprint)
return app
main.py
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run()

pywintypes.com error when running pyad.adgroup on flask

I am creating a simple app in Python 3.5.2 that authenticates users via Active Directory and applies additional rules based on a user's group membership. The app can successfully authenticate users using the win32security package, and tries to obtain group membership info using pyad.
My problem: I get a pywintypes.com_error message when running the code on my Flask app, preventing me from getting group membership info.
When I run the backend code separately on an iPython console, it works fine. I am able to query group membership. However, when it is part of a Flask app, an error pops out. I have isolated the problem to this part of the code (DN information masked):
group = adgroup.ADGroup.from_dn('CN=someCN,OU=someOU1,OU=someOU2,
DC=test,DC=domain,DC=com,DC=somecountry')
group_members = sum([member.get_attribute("sAMAccountName")
for member in group.get_members()],[])
Has anyone encountered this before? I cannot think of why the code won't run in Flask (though I have just started learning Flask) but it will run in the console.
Code Reference:
I have 3 Python files for my Flask app and an html file in the templates folder.
run.py
from app import app
import os
app.secret_key = os.urandom(16)
app.run(debug=True)
init.py
from flask import Flask
app = Flask(__name__)
from app import views
views.py
from app import app
from flask import Flask, flash, render_template, request, session
import win32security as win32
from pyad import adgroup
#app.route("/")
def home():
if not session.get("logged_in"):
return render_template("login.html")
else:
return "You are currently logged in."
#app.route("/login", methods=["GET","POST"])
def login():
#initialize variables
username = request.form["username"]
password = request.form["password"]
DOMAIN = "test.domain.com.somecountry"
error = None
group = adgroup.ADGroup.from_dn('CN=someCN,OU=someOU1,OU=someOU2,DC=test,DC=domain,DC=com,DC=somecountry')
group_members = sum([member.get_attribute("sAMAccountName") for member in group.get_members()],[])
if username in group_members:
try:
token = win32.LogonUser(username, DOMAIN, password,
win32.LOGON32_LOGON_NETWORK,
win32.LOGON32_PROVIDER_DEFAULT)
is_auth = bool(token)
if is_auth:
session["logged_in"] = True
except:
error = "Incorrect credentials. Please try again."
else:
error = "You are not permitted to access this."
return render_template("login.html", error=error)
login.html
<!doctype html>
<title>Login Test</title>
{% block body %}
{% if session["logged_in"] %}
<p>You are currently logged in.</p>
{% else %}
<form action="/login" method="POST">
<input type="username" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="submit" value="Log In">
</form>
<li>{{error}}</li>
{% endif %}
{% endblock %}
This is the error traceback:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 2000, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1991, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1567, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\user\Documents\test\app\views.py", line 23, in login
group = adgroup.ADGroup.from_dn('CN=someCN,OU=someOU1,OU=someOU2,DC=test,DC=domain,DC=com,DC=somecountry')
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\pyad\adobject.py", line 131, in from_dn
return cls(distinguished_name, None, options)
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\pyad\adobject.py", line 88, in __init__
self.__set_adsi_obj()
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\pyad\adobject.py", line 76, in __set_adsi_obj
self._ldap_adsi_obj = self.adsi_provider.getObject('', self.__ads_path)
File "<COMObject ADsNameSpaces>", line 2, in getObject
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147221020), None)
I was able to mitigate this error by running my same code in a python2 32bit environment.
Not sure if this is an option, but worth a shot.

Categories