Error while creating query_string in flask - python

I have written an flask app.
This app allow users to upload images, if i run this app locally this app uploads images and saves it to the path which i have designated
Now i want to create a query string for my app where i will create urls and send it to people to upload images.
but when i run my app i receive this error
werkzeug.routing.BuildError: Could not build url for endpoint 'index'. Did you forget to specify values ['property_id']?
Traceback (most recent call last)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\prince.bhatia\Desktop\python-projects\new\app.py", line 77, in index
return render_template('index.html', property_id= property_id)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\templating.py", line 135, in render_template
context, ctx.app)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\templating.py", line 117, in _render
rv = template.render(context)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\jinja2\asyncsupport.py", line 76, in render
return original_render(self, *args, **kwargs)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\jinja2\environment.py", line 1008, in render
return self.environment.handle_exception(exc_info, True)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\jinja2\environment.py", line 780, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\jinja2\_compat.py", line 37, in reraise
raise value.with_traceback(tb)
File "C:\Users\prince.bhatia\Desktop\python-projects\new\templates\index.html", line 14, in top-level template code
{{ dropzone.create(action_view='index') }}
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask_dropzone\__init__.py", line 330, in create
action_url = url_for(action_view, **kwargs)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\helpers.py", line 356, in url_for
return appctx.app.handle_url_build_error(error, endpoint, values)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 2061, in handle_url_build_error
reraise(exc_type, exc_value, tb)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\helpers.py", line 345, in url_for
force_external=external)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\werkzeug\routing.py", line 1776, in build
raise BuildError(endpoint, values, method, self)
werkzeug.routing.BuildError: Could not build url for endpoint 'index'. Did you forget to specify values ['property_id']?
The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.
To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.
You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:
dump() shows all variables in the frame
dump(obj) dumps all that's known about the object
Below is my code:
from flask import Flask, redirect, render_template, request, session, url_for, send_file
from flask_dropzone import Dropzone
from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class
from flask_sqlalchemy import SQLAlchemy
import os
import psycopg2
import csv
app = Flask(__name__)
db = SQLAlchemy(app)
dropzone = Dropzone(app)
#app.config["SQLALCHEMY_DATABASE_URI"]="postgres://qpnwgdxnihlitm:22e4f6cbdb773f69aa468b2b7ddcd692552cb4102367ffc14c62f19403636477#ec2-54-243-223-245.compute-1.amazonaws.com:5432/d1ssufnnr78nll?sslmode=require"
app.config["SQLALCHEMY_DATABASE_URI"]= "postgresql://postgres:prince#25#localhost/images"
#app.config["SQLALCHEMY_DATABASE_URI"]='postgres://mapvmydehdyncf:7500963c956e3d5556df4a5f4fdd1a9a40f023c922bfe93194fb13b9322c86ad#ec2-23-21-165-188.compute-1.amazonaws.com:5432/d6lmau9918afdq?sslmode=require'
app.config['SECRET_KEY'] = 'supersecretkeygoeshere'
# Dropzone settings
app.config['DROPZONE_UPLOAD_MULTIPLE'] = True
app.config['DROPZONE_ALLOWED_FILE_CUSTOM'] = True
app.config['DROPZONE_ALLOWED_FILE_TYPE'] = 'image/*'
app.config['DROPZONE_REDIRECT_VIEW'] = 'results'
# Uploads settings
app.config['UPLOADED_PHOTOS_DEST'] = '/uploads'
photos = UploadSet('photos', IMAGES)
configure_uploads(app, photos)
patch_request_class(app) # set maximum file size, default is 16MB
class Data(db.Model):
__tablename__ = "image"
id=db.Column(db.Integer, primary_key=True)
link = db.Column(db.String(1000000), unique=True)
def __init__(self, link):
self.link = link
#app.route("/<string:property_id>", methods=['GET', 'POST'])
def index(property_id):
# set session for image results
if "file_urls" not in session:
session['file_urls'] = []
# list to hold our uploaded image urls
file_urls = session['file_urls']
# handle image upload from Dropszone
if request.method == 'POST':
file_obj = request.files
for f in file_obj:
file = request.files.get(f)
# save the file with to our photos folder
filename = photos.save(
file,
name=file.filename
)
# append image urls
file_urls.append(photos.url(filename))
d = file_urls.append(photos.url(filename))
for i in file_urls:
data = Data(i)
db.session.add(data)
db.session.commit()
session['file_urls'] = file_urls
return "uploading..."
# return dropzone template on GET request
return render_template('index.html', property_id= property_id)
#app.route('/results')
def results():
# redirect to home if no images to display
if "file_urls" not in session or session['file_urls'] == []:
return redirect(url_for('index'))
# set the file_urls and remove the session variable
file_urls = session['file_urls']
session.pop('file_urls', None)
dms = set(file_urls)
get_length = len(dms)
return render_template('results.html', dms=dms, get_length=get_length)
#app.route('/dashboard')
def dashboard():
conn = psycopg2.connect("dbname='images' user='postgres' password='prince#25' host='localhost' port='5432' ")
print(conn)
cur = conn.cursor()
data = cur.execute("SELECT DISTINCT link FROM image")
m_dict = cur.fetchall()
filename = "Productivity.csv"
with open("./"+filename,'w', encoding="utf-8") as csvfile:
csvfile = csv.writer(csvfile, m_dict)
csvfile.writerow(["Link"])
for i in range(0, len( m_dict )):
csvfile.writerow( m_dict[i] )
news = cur.execute("DELETE FROM image")
conn.commit()
return send_file(filename, attachment_filename="Data.csv", as_attachment=True)
if __name__=="__main__":
app.run(debug=True)
#app.run(debug=True)
this my index.html
<!DOCTYPE html>
<html>
<head>
<title>99Acres</title>
{{ dropzone.load() }}
{{ dropzone.style('border: 2px dashed #0087F7; margin: 10%; min-height: 400px;') }}
</head>
<body style="background-color:teal">
<!--<h1 style="color:white;">99Acres</h1>-->
<img align="right"src="https://img-d02.moneycontrol.co.in/news_image_files/2015/356x200/9/99acres_1902_356.jpg" width="80" height="80" alt="me">
<h1 align="center" style="color:white">Welcome to 99acres image upload website</h1>
<h3 align="center"style="color:white">Please Upload images in format[".JPG",".PNG",".JPEG"]</h3>
<h3 align="center" style="color:white">**Please Note:Maximum Total image size is 5MB</h3>
{{ dropzone.create(action_view='index') }}
<div class="list" align="center">
<strong>Our Partners:</strong> Naukri.com-
Jeevansathi Matrimonials- ICICIcommunities.org <br>
<br>
Home || About Us ||
Advertise with us || Terms and Conditions ||
Contact us || Reques1t info<br>
<br>
All rights reserved 2001 Info Edge India Ltd.
</div>
</body>
</html>
this is my results.html
<body style="background-color:teal">
<h1 align="center" style="color:white">Below Images Uploaded Successfully</h1>
Back<p>
<ul>
{% for file_url in dms %}
<img style="height: 150px" src="{{ file_url }}">
{% endfor %}
</ul>
<h1 align="center" style="color:white">You can close this page or upload more image</h1>
<h1 align="center" style="color:white">Total number of images are : {{get_length}}</h1> <br><br><br><br>
<div class="list" align="center">
<strong>Our Partners:</strong> Naukri.com-
Jeevansathi Matrimonials- ICICIcommunities.org <br>
<br>
Home || About Us ||
Advertise with us || Terms and Conditions ||
Contact us || Reques1t info<br>
<br>
All rights reserved 2001 Info Edge India Ltd.
</div>
</body>
I have read this posts:
werkzeug.routing.BuildError: Could not build url for endpoint 'success'. Did you forget to specify values ['name']?
How do you get a query string on Flask?
werkzeug.routing.BuildError: Could not build url for endpoint

render_template('index.html', property_id= property_id)
Your index.html does not use property_id. You can discard the property_id argument if index.html indeed do not need it
in index.html, line 14
dropzone.create(action_view='index')
action_url = url_for(action_view, **kwargs)
the later url_for would invoke index() method again, but missed the argument property_id, and moreover it seemed that you are making a recursive call!

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

Call mySQL rows to a Flask function and run model on them, outputting the results to a HTML table?

I want to call the rows of a column from a mySQL database table to my Flask application, so I can run my LDA topic model over them. I then want to print the LDA topics identified into a HTML table for the user to see. (I also want to visualise this data in the table, but that's another challenge). For now I just want to print the topics in a basic way.
When I run the code below and load my application, I get the following error:
TypeError: 'int' object is not iterable
Full traceback:
Traceback (most recent call last):
File "C:\Users\jeram\anaconda3\envs\my_env\lib\site-packages\flask\app.py", line 2091, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\jeram\anaconda3\envs\my_env\lib\site-packages\flask\app.py", line 2076, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\jeram\anaconda3\envs\my_env\lib\site-packages\flask\app.py", line 2073, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\jeram\anaconda3\envs\my_env\lib\site-packages\flask\app.py", line 1518, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\jeram\anaconda3\envs\my_env\lib\site-packages\flask\app.py", line 1516, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\jeram\anaconda3\envs\my_env\lib\site-packages\flask\app.py", line 1502, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "c:\Users\jeram\Documents\NCI\Semester 3\TriagatronX50\app.py", line 65, in insight
new_corpus = [common_dictionary.doc2bow(text) for text in resultValue]
TypeError: 'int' object is not iterable
This is my Python function:
#app.route('/insight', methods=['GET', 'POST'])
def insight():
if request.method == 'GET':
# if request.form['submit_button'] == 'Main Themes':
cur = mysql.connection.cursor()
resultValue = cur.execute("SELECT journal_entry FROM journals")
common_dictionary = Dictionary(common_texts)
new_corpus = [common_dictionary.doc2bow(text) for text in resultValue]
lda = gensim.models.LdaModel(new_corpus, num_topics=5, alpha='auto', eval_every=5)
main_themes = pprint(lda.print_topics())
# return render_template('insight.html', value=main_themes)
return render_template('insight.html', value=main_themes)
My HTML code:
<div class="col-xs-5">
<table id=journallist>
<form method=" ">
<th>Topics Identified</th>
<tr>
<td> {{ value }} </td>
</tr>
</form>
</table>
<input type="submit" name="submit_button" value="Main Themes" class='btn'>
</div>
Ideally I would also like to get my button working so that the function only acts when it is called, but firstly I just want to get it working at a basic level.
Any help would be greatly appreciated!

Show HTML table with Flask and render_template

I would like to show a table on a website using Google Cloud SQL and Google App Engine.
I am using Flask and pymysql. To show the result of my query I use the render_template of Flask.
I already found other similar topics here (like Topic: Listing table results to HTML with Flask), but I still get an error when I deploy my app. It seems that the error has to do with the for loop.. The error says "jinja2.exceptions.TemplateSyntaxError: tag name expected".
Here's the full error message I get:
ERROR in app: Exception on /analysis [GET]
Traceback (most recent call last): File "/env/lib/python3.7/site-packages/flask/app.py", line 2292, in wsgi_app response = self.full_dispatch_request()
File "/env/lib/python3.7/site-packages/flask/app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e)
File "/env/lib/python3.7/site-packages/flask/app.py", line 1718, in handle_user_exception reraise(exc_type, exc_value, tb)
File "/env/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise raise value
File "/env/lib/python3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request rv = self.dispatch_request()
File "/env/lib/python3.7/site-packages/flask/app.py", line 1799, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args)
File "/srv/main.py", line 61, in analysis return render_template("analysis.html", result = result)
File "/env/lib/python3.7/site-packages/flask/templating.py", line 134, in render_template return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list), File "/env/lib/python3.7/site-packages/jinja2/environment.py", line 869, in get_or_select_template return self.get_template(template_name_or_list, parent, globals)
File "/env/lib/python3.7/site-packages/jinja2/environment.py", line 830, in get_template return self._load_template(name, self.make_globals(globals))
File "/env/lib/python3.7/site-packages/jinja2/environment.py", line 804, in _load_template template = self.loader.load(self, name, globals)
File "/env/lib/python3.7/site-packages/jinja2/loaders.py", line 125, in load code = environment.compile(source, name, filename)
File "/env/lib/python3.7/site-packages/jinja2/environment.py", line 591, in compile self.handle_exception(exc_info, source_hint=source_hint)
File "/env/lib/python3.7/site-packages/jinja2/environment.py", line 780, in handle_exception reraise(exc_type, exc_value, tb)
File "/env/lib/python3.7/site-packages/jinja2/_compat.py", line 37, in reraise raise value.with_traceback(tb)
File "/srv/templates/analysis.html", line 23, in template <p class="p1"><span class="s1"><span class="Apple-tab-span"> </span>{% </span><span class="s2">for</span><span class="s1"> r </span><span class="s2">in</span><span class="s1"> result %}</span></p>
File "/env/lib/python3.7/site-packages/jinja2/environment.py", line 497, in _parse return Parser(self, source, name, encode_filename(filename)).parse()
File "/env/lib/python3.7/site-packages/jinja2/parser.py", line 901, in parse result = nodes.Template(self.subparse(), lineno=1)
File "/env/lib/python3.7/site-packages/jinja2/parser.py", line 883, in subparse rv = self.parse_statement()
File "/env/lib/python3.7/site-packages/jinja2/parser.py", line 125, in parse_statement self.fail('tag name expected', token.lineno)
File "/env/lib/python3.7/site-packages/jinja2/parser.py", line 59, in fail raise exc(msg, lineno, self.name, self.filename) jinja2.exceptions.TemplateSyntaxError: tag name expected
My Code in main.py:
import logging
import os
from flask import Flask, render_template
from flask import request
import urllib.request
from urllib.parse import parse_qs, urlparse
import platform
import pymysql
import datetime
db_user = os.environ.get('CLOUD_SQL_USERNAME')
db_password = os.environ.get('CLOUD_SQL_PASSWORD')
db_name = os.environ.get('CLOUD_SQL_DATABASE_NAME')
db_connection_name = os.environ.get('CLOUD_SQL_CONNECTION_NAME')
app = Flask(__name__)
#app.route('/analysis', methods=['GET'])
def analysis():
if os.environ.get('GAE_ENV') == 'standard':
unix_socket = '/cloudsql/{}'.format(db_connection_name)
cnx = pymysql.connect(user=db_user, password=db_password,
unix_socket=unix_socket, db=db_name)
else:
host = '127.0.0.1'
#unix_socket = '/cloudsql/{}'.format(db_connection_name)
cnx = pymysql.connect(user=db_user, password=db_password,
unix_socket=unix_socket, db=db_name)
with cnx.cursor() as cursor:
sql = 'SELECT * FROM content'
cursor.execute(sql)
result = cursor.fetchall()
cnx.close()
return render_template("analysis.html", result = result)
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080, debug=True)
File analysis.html:
<!doctype html>
<table>
<tr>
  <th>contentID</th>
  <th>timestamp</th> 
  <th>clientID</th>
  <th>content</th>
</tr>
{% for r in result %}
<tr>
  <td>{{ r[0] }}</td>
  <td>{{ r[1] }}</td> 
  <td>{{ r[2] }}</td>
  <td>{{ r[3] }}</td>
</tr>
{% endfor %}
</table>
Do you have any suggestions what I can can change to make it work?
Thanks in advance!
One way you can do this is by first have an object, or use pandas to read_csv and then use the dataframe's to_html method.
This saves a ton of time if your data is already formatted correctly:
import pandas as pd
from flask import Flask, render_template
#app.route("/table-page", methods=['GET'])
def table():
data_dic = {
'id': [100, 101, 102],
'color': ['red', 'blue', 'red']}
columns = ['id', 'color']
index = ['a', 'b', 'c']
df = pd.DataFrame(data_dic, columns=columns, index=index)
table = df.to_html(index=False)
return render_template(
"at-leaderboard.html",
table=table)
Now you take the HTML string and paste it into you template without send it as JSON or a dict needing Jinja template formating:
<html>
<body>
<div>
{{ table | safe }}
</div>
</body>
</html>
Based on the stack trace, the text editor you're using for analysis.html isn't a plain text editor. It's saving the file in some other format, making it invalid Jinja2 syntax.
So this line that you see in your editor:
{% for r in result %}
Python will see as (based on the stack trace; added some line breaks for clarity):
<p class="p1">
<span class="s1">
<span class="Apple-tab-span">
</span>
{% </span><span class="s2">for</span><span class="s1"> r </span><span class="s2">in</span><span class="s1"> result %}
</span>
</p>
To fix the problem, open the file analysis.html in a plain text editor and edit it as needed.
{% for r in result %}
<p class="p1">
<span class="s1">
<span class="Apple-tab-span">
</span>
</span><span class="s2">for</span><span class="s1"> {{ r }}</span><span class="s2">in</span><span class="s1">
</span>
</p>
{% endfor %}

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.

Flask application on google app engine - Showing database object

I'm trying to make a flask app on google app engine which shows database entries on their own page.
This is a bit of my views.py code:
#app.route('/posts/<int:id>')
def display_post(id):
post = Post.filter('id =', id)
return render_template('display_post.html', post=post)
Then my display_posts.html
{% extends "base.html" %}
{% block content %}
<ul>
<h1 id="">Post</h1>
<li>
{{ posts.title }}<br />
{{ posts.content }}
</li>
</ul>
{% endblock %}
Now when I have a post with ID 5700305828184064 and visit this page I should see the title and content:
www.url.com/posts/5700305828184064
However I get this traceback:
<type 'exceptions.AttributeError'>: type object 'Post' has no attribute 'filter'
Traceback (most recent call last):
File "/base/data/home/apps/s~smart-cove-95709/1.384741962561717132/main.py", line 4, in <module>
run_wsgi_app(app)
File "/base/data/home/runtimes/python/python_lib/versions/1/google/appengine/ext/webapp/util.py", line 99, in run_wsgi_app
run_bare_wsgi_app(add_wsgi_middleware(application))
File "/base/data/home/runtimes/python/python_lib/versions/1/google/appengine/ext/webapp/util.py", line 117, in run_bare_wsgi_app
result = application(env, _start_response)
File "/base/data/home/apps/s~smart-cove-95709/1.384741962561717132/flask/app.py", line 874, in __call__
return self.wsgi_app(environ, start_response)
File "/base/data/home/apps/s~smart-cove-95709/1.384741962561717132/flask/app.py", line 864, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/base/data/home/apps/s~smart-cove-95709/1.384741962561717132/flask/app.py", line 861, in wsgi_app
rv = self.dispatch_request()
File "/base/data/home/apps/s~smart-cove-95709/1.384741962561717132/flask/app.py", line 696, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/base/data/home/apps/s~smart-cove-95709/1.384741962561717132/blog/views.py", line 25, in display_post
post = Post.filter('id =', id)
How can I show the title and content of the entry for a given ID?
You need to create a query object first, then apply the filter to that.
q = Post.all()
post = q.filter("id =", id)
This is the first example in the GAE docs on queries.
Also, your template references the name posts, but you've passed in the name post. Change your template appropriately.

Categories