Key Error when deploying Flask App to heroku - flask

I deployed my App to Heroku and it is showing me a 'keyError' regarding 'items'. My code runs perfectly fine locally but won't on Heroku. Does someone know how I can fix that?
Thank you very much!
My Code:
def getbooktitle():
if request.method == "POST":
file = request.files['image']
img = Image.open(file.stream)
booktitle = pytesseract.image_to_string(img)
api_key = "myapikey"
url = f"https://www.googleapis.com/books/v1/volumes?q={booktitle}&key={api_key}"
response = requests.get(url)
json_response = response.json()
volume_info = json_response['items'][0]['volumeInfo']
title = volume_info.get('title')
author = volume_info.get('authors')
imageslink = volume_info['imageLinks']
smallimage = imageslink['smallThumbnail']
return jsonify({"books": [{'title': title, 'author': author[0], 'imageLink': smallimage}]})
View logs:
2021-07-20T15:50:16.826905+00:00 app[web.1]: [2021-07-20 15:50:16,823] ERROR in app: Exception on /getbook [POST]
2021-07-20T15:50:16.826914+00:00 app[web.1]: Traceback (most recent call last):
2021-07-20T15:50:16.826915+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/app.py", line 2070, in wsgi_app
2021-07-20T15:50:16.826915+00:00 app[web.1]: response = self.full_dispatch_request()
2021-07-20T15:50:16.826917+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/app.py", line 1515, in full_dispatch_request
2021-07-20T15:50:16.826917+00:00 app[web.1]: rv = self.handle_user_exception(e)
2021-07-20T15:50:16.826918+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/app.py", line 1513, in full_dispatch_request
2021-07-20T15:50:16.826918+00:00 app[web.1]: rv = self.dispatch_request()
2021-07-20T15:50:16.826919+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/app.py", line 1499, in dispatch_request
2021-07-20T15:50:16.826919+00:00 app[web.1]: return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
2021-07-20T15:50:16.826920+00:00 app[web.1]: File "/app/app.py", line 21, in getbooktitle
2021-07-20T15:50:16.826921+00:00 app[web.1]: volume_info = json_response["items"][0]["volumeInfo"]
2021-07-20T15:50:16.826922+00:00 app[web.1]: KeyError: 'items'

Are you using config variables in Heroku?
If you are, make sure there are no hyphens in your config variables. I had the same issue.. app was running perfectly fine locally, but on Heroku it would bring back a KeyError. I was stumped for hours. Once I changed the hyphens to underscores, it worked perfecty fine.

Related

AttributeError: 'MultiDict' object has no attribute 'iteritems' when moving from localhost to heroku

I am getting the following error. When running on localhost all works fine.
2022-08-13T14:17:31.683406+00:00 app[web.1]: [2022-08-13 14:17:31,682] ERROR in app: Exception on /create [GET]
2022-08-13T14:17:31.683432+00:00 app[web.1]: Traceback (most recent call last):
2022-08-13T14:17:31.683433+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/flask/app.py", line 2525, in wsgi_app
2022-08-13T14:17:31.683433+00:00 app[web.1]: response = self.full_dispatch_request()
2022-08-13T14:17:31.683434+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/flask/app.py", line 1822, in full_dispatch_request
2022-08-13T14:17:31.683434+00:00 app[web.1]: rv = self.handle_user_exception(e)
2022-08-13T14:17:31.683435+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/flask/app.py", line 1820, in full_dispatch_request
2022-08-13T14:17:31.683435+00:00 app[web.1]: rv = self.dispatch_request()
2022-08-13T14:17:31.683436+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/flask/app.py", line 1796, in dispatch_request
2022-08-13T14:17:31.683436+00:00 app[web.1]: return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
2022-08-13T14:17:31.683436+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/flask_login/utils.py", line 290, in decorated_view
2022-08-13T14:17:31.683437+00:00 app[web.1]: return current_app.ensure_sync(func)(*args, **kwargs)
2022-08-13T14:17:31.683438+00:00 app[web.1]: File "/app/app.py", line 235, in create
2022-08-13T14:17:31.683438+00:00 app[web.1]: form = dynamic.process(CreateRecord, post)
2022-08-13T14:17:31.683439+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/wtforms_dynamic_fields/wtforms_dynamic_fields.py", line 110, in process
2022-08-13T14:17:31.683440+00:00 app[web.1]: for field, data in post.iteritems():
2022-08-13T14:17:31.683440+00:00 app[web.1]: AttributeError: 'MultiDict' object has no attribute 'iteritems'
My create code is:
elif request.method == "GET":
post = MultiDict()
cfv = customfields.find({"parentRecord": current_user.user_json["_id"]})
dynamic = WTFormsDynamicFields()
for value in cfv:
if value['fieldType'] == "Text Field":
post.add(value['fieldName'], "")
dynamic.add_field(value['fieldName'], value['fieldName'], StringField, render_kw={"placeholder": "Enter " + value['fieldName']})
elif value['fieldType'] == "Date Field":
post.add(value['fieldName'], "")
dynamic.add_field(value['fieldName'], value['fieldName'], DateField)
elif value['fieldType'] == "Email Field":
post.add(value['fieldName'], "")
dynamic.add_field(value['fieldName'], value['fieldName'], EmailField, render_kw={"placeholder": "Enter " + value['fieldName']})
dynamic.add_validator(value['fieldName'], Email)
form = dynamic.process(CreateRecord, post)
return render_template('create.html', form=form, auth=current_user.is_authenticated)
I am puzzled primarily because, as mentioned above, when running on the default flask dev webserver the app works perfectly fine without throwing code. I have deployed the app on Heroku and am now getting the error below.
This was solved by creating a new class
from werkzeug.datastructures import ImmutableMultiDict
class Dict:
'''Wrapper klass because iteritems no longer available in Python3.7 dict'''
def __init__(self, mapping):
self.mapping = ImmutableMultiDict(mapping)
def iteritems(self):
return self.mapping.items()
def __getattr__(self, attr):
return getattr(self.mapping, attr)
def __iter__(self):
return dict.__iter__(self.mapping)
And then adding post = Dict(post) prior to my process event.

Why is my flask app inserting the same data several times into postgres despite precautions?

I'm working on a hobby project - a chess calendar that finds strongest tournaments for me to participate in link to GitHub.
It's a flask app that scrapes a tournament aggregator, finds the strongest tournaments and shows them to the visitor.
Everything works beautifully locally, but I've been having trouble with the version that I deploy on Heroku. How do I fix it?
Specifically, despite taking several precautions, my app ends up trying to insert the same data into postgres several times, which leads to a UniqueViolation error.
My precautions are the following:
On startup, I truncate the tables in my db.
I only insert the data if the tables are empty.
The insertion happens inside a begin/commit/rollback block as advised in documentation.
I drop duplicates in my data to make sure that it's not where the duplicates come from.
None of this helps though, the app still behaves like it's inserting the same data several times into the db and returning an error :(
I made sure to have the same versions of postgres both locally and on heroku.
(relevant part of) models.py:
db = SQLAlchemy()
def setup_db(app):
database_name = 'tournaments'
default_database_path = get_database_uri('jim_potato', os.environ.get("PASSWORD"), 'localhost:5432', database_name)
database_path = os.getenv('DATABASE_URL', default_database_path)
database_path = database_path.replace("postgres://", "postgresql://", 1)
app.config["SQLALCHEMY_DATABASE_URI"] = database_path
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.app = app
db.init_app(app)
db_truncate_or_create_all()
def db_truncate_or_create_all():
inspector_gadget = inspect(db.engine)
if inspector_gadget.has_table("player"): # truncate the table if it's there
db.session.query(Player).delete()
db.session.query(Tournament).delete()
db.session.commit()
else:
db.create_all()
class Tournament(db.Model):
__tablename__ = 'tournament'
id = Column(Integer, primary_key=True)
title = Column(String(200))
url = Column(String(80), unique=True)
time_control = Column(String(80))
status = Column(String(80))
start_date = Column(db.Date)
end_date = Column(db.Date)
(relevant part of) app.py:
def create_app(app_environment=None):
app = Flask(__name__)
if app_environment is None:
app.config.from_object(config[os.getenv('FLASK_ENV', 'dev')])
else:
app.config.from_object(config[app_environment])
setup_db(app)
CORS(app)
db.app.logger.info(f"rows in tournament: {db.session.query(Tournament).count()}")
with Session(db.engine) as session, session.begin():
if session.query(Tournament).first() is None:
tournaments = pd.read_csv(TOURNAMENT_DATA_PATH).drop_duplicates(subset=['url'])
players = pd.read_csv(FULL_DATA_PATH)
for i, tournament_row in tournaments.iterrows():
day, month = tournament_row.start.split('-')
day, month = int(day), int(month)
tournament = Tournament(
title=tournament_row["name"],
url=tournament_row["url"],
time_control=tournament_row["type"],
status=tournament_row["status"],
start_date=date(datetime.now().year, month, day),
end_date=date(datetime.now().year, month, day)
)
session.add(tournament)
session.flush()
for j, player in players[players['id'] == i].iterrows():
player = (Player(
tournament_id=tournament.id,
name=player['name'],
title=player['title'],
rating=player['rating'],
year_of_birth=player['year_of_birth']
))
session.add(player)
error details (from heroku logs):
2022-03-25T14:45:23.014943+00:00 app[web.1]: Traceback (most recent call last):
2022-03-25T14:45:23.014944+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker
2022-03-25T14:45:23.014944+00:00 app[web.1]: worker.init_process()
2022-03-25T14:45:23.014944+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process
2022-03-25T14:45:23.014945+00:00 app[web.1]: self.load_wsgi()
2022-03-25T14:45:23.014945+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi
2022-03-25T14:45:23.014945+00:00 app[web.1]: self.wsgi = self.app.wsgi()
2022-03-25T14:45:23.014946+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi
2022-03-25T14:45:23.014946+00:00 app[web.1]: self.callable = self.load()
2022-03-25T14:45:23.014947+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load
2022-03-25T14:45:23.014947+00:00 app[web.1]: return self.load_wsgiapp()
2022-03-25T14:45:23.014947+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp
2022-03-25T14:45:23.014948+00:00 app[web.1]: return util.import_app(self.app_uri)
2022-03-25T14:45:23.014948+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 412, in import_app
2022-03-25T14:45:23.014948+00:00 app[web.1]: app = app(*args, **kwargs)
2022-03-25T14:45:23.014948+00:00 app[web.1]: File "/app/app.py", line 59, in create_app
2022-03-25T14:45:23.014949+00:00 app[web.1]: session.flush()
2022-03-25T14:45:23.014949+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 3363, in flush
2022-03-25T14:45:23.014949+00:00 app[web.1]: self._flush(objects)
2022-03-25T14:45:23.014950+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 3503, in _flush
2022-03-25T14:45:23.014950+00:00 app[web.1]: transaction.rollback(_capture_exception=True)
2022-03-25T14:45:23.014950+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/util/langhelpers.py", line 70, in __exit__
2022-03-25T14:45:23.014951+00:00 app[web.1]: compat.raise_(
2022-03-25T14:45:23.014951+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 207, in raise_
2022-03-25T14:45:23.014951+00:00 app[web.1]: raise exception
2022-03-25T14:45:23.014952+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 3463, in _flush
2022-03-25T14:45:23.014952+00:00 app[web.1]: flush_context.execute()
2022-03-25T14:45:23.014952+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/orm/unitofwork.py", line 456, in execute
2022-03-25T14:45:23.014952+00:00 app[web.1]: rec.execute(self)
2022-03-25T14:45:23.014953+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/orm/unitofwork.py", line 630, in execute
2022-03-25T14:45:23.014953+00:00 app[web.1]: util.preloaded.orm_persistence.save_obj(
2022-03-25T14:45:23.014953+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/orm/persistence.py", line 244, in save_obj
2022-03-25T14:45:23.014953+00:00 app[web.1]: _emit_insert_statements(
2022-03-25T14:45:23.014954+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/orm/persistence.py", line 1221, in _emit_insert_statements
2022-03-25T14:45:23.014954+00:00 app[web.1]: result = connection._execute_20(
2022-03-25T14:45:23.014954+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1614, in _execute_20
2022-03-25T14:45:23.014954+00:00 app[web.1]: return meth(self, args_10style, kwargs_10style, execution_options)
2022-03-25T14:45:23.014955+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/sql/elements.py", line 325, in _execute_on_connection
2022-03-25T14:45:23.014955+00:00 app[web.1]: return connection._execute_clauseelement(
2022-03-25T14:45:23.014955+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1481, in _execute_clauseelement
2022-03-25T14:45:23.014955+00:00 app[web.1]: ret = self._execute_context(
2022-03-25T14:45:23.014956+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1845, in _execute_context
2022-03-25T14:45:23.014956+00:00 app[web.1]: self._handle_dbapi_exception(
2022-03-25T14:45:23.014956+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 2026, in _handle_dbapi_exception
2022-03-25T14:45:23.014956+00:00 app[web.1]: util.raise_(
2022-03-25T14:45:23.014956+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 207, in raise_
2022-03-25T14:45:23.014957+00:00 app[web.1]: raise exception
2022-03-25T14:45:23.014957+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1802, in _execute_context
2022-03-25T14:45:23.014957+00:00 app[web.1]: self.dialect.do_execute(
2022-03-25T14:45:23.014964+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 732, in do_execute
2022-03-25T14:45:23.014964+00:00 app[web.1]: cursor.execute(statement, parameters)
2022-03-25T14:45:23.014965+00:00 app[web.1]: sqlalchemy.exc.IntegrityError: (psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint "tournament_url_key"
2022-03-25T14:45:23.014965+00:00 app[web.1]: DETAIL: Key (url)=(http://chessarbiter.com/turnieje/open.php?turn=2022/ti_93&n=) already exists.
2022-03-25T14:45:23.014965+00:00 app[web.1]:
2022-03-25T14:45:23.014966+00:00 app[web.1]: [SQL: INSERT INTO tournament (title, url, time_control, status, start_date, end_date) VALUES (%(title)s, %(url)s, %(time_control)s, %(status)s, %(start_date)s, %(end_date)s) RETURNING tournament.id]
2022-03-25T14:45:23.014967+00:00 app[web.1]: [parameters: {'title': 'VI Memoriał Józefa Matwija - całoroczny turniej drabinkowy', 'url': 'http://chessarbiter.com/turnieje/open.php?turn=2022/ti_93&n=', 'time_control': 'klasyczne', 'status': 'trwający', 'start_date': datetime.date(2022, 1, 5), 'end_date': datetime.date(2022, 1, 5)}]
2022-03-25T14:45:23.014967+00:00 app[web.1]: (Background on this error at: https://sqlalche.me/e/14/gkpj)
2022-03-25T14:45:23.016112+00:00 app[web.1]: [2022-03-25 14:45:23 +0000] [10] [INFO] Worker exiting (pid: 10)
2022-03-25T14:45:53.480041+00:00 app[web.1]: [2022-03-25 14:45:53 +0000] [4] [INFO] Shutting down: Master
2022-03-25T14:45:53.480084+00:00 app[web.1]: [2022-03-25 14:45:53 +0000] [4] [INFO] Reason: Worker failed to boot.
2022-03-25T14:45:53.682139+00:00 heroku[web.1]: Process exited with status 3
2022-03-25T14:45:53.745500+00:00 heroku[web.1]: State changed from up to crashed

2021-02-16 10:43:57,123 ERROR in app: Exception on / GET?

I want to embed/put a tkinter gui in a flask app, but the code i made seems not to be rendering/show and gives this error when i run my code:
[2021-02-16 10:43:57,123] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\User\untitled0.py", line 14, in my_app
File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 2369, in __init__
Widget.__init__(self, master, 'button', cnf, kw)
File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 2299, in __init__
(widgetName, self._w) + extra + self._options(cnf))
File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 1326, in _options
v = self._register(v)
File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 1372, in _register
self.tk.createcommand(name, f)
RuntimeError: main thread is not in main loop
127.0.0.1 - - [16/Feb/2021 10:43:57] "GET / HTTP/1.1" 500 -
also when i want to run the flask web server it shows Internal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
from flask import Flask
from webbrowser import open
app = Flask(__name__)
root = Tk()
root.title("Tkinter")
#app.route('/')
def my_app():
def click():
l = Label(root, text = "You Clicked!").pack()
b = Button(root, text = "Click Me!", command = click).pack()
return(root)
if __name__ == '__main__':
open('http://127.0.0.1:5000/')
app.run()
#root.mainloop()

Authlib client error: State not equal in request and response

I'm trying to implement authlib client and server. I took example OAuth2.0 example and making my own client authorization on Flask site following tutorial. This is my code:
from flask import Flask, redirect, url_for, session, request
from authlib.flask.client import OAuth
from authlib.client.errors import OAuthException
APP_ID = 'KBtRDO3r2HETjw4TcLznthoj'
APP_SECRET = '3g4C6nbJcTIYX3jyCIEmf6KE8h8pzxUhjy6ArlY3AEgj1snv'
app = Flask('testa_client')
app.debug = True
app.secret_key = 'development'
oauth = OAuth()
oauth.init_app(app)
remote = oauth.register(
'testa',
client_id=APP_ID,
client_secret=APP_SECRET,
# request_token_params={'scope': 'base'},
base_url='http://127.0.0.1:5000',
access_token_url='http://127.0.0.1:5000/auth/token',
authorize_url='http://127.0.0.1:5000/auth/connect'
)
#app.route('/')
def index():
return redirect(url_for('login'))
#app.route('/login')
def login():
callback = url_for(
'websa_authorized',
next=request.args.get('next') or request.referrer or None,
_external=True
)
return remote.authorize_redirect(callback=callback)
#app.route('/login/authorized')
def websa_authorized():
resp = remote.authorize_access_token()
if resp is None:
return 'Access denied: reason=%s error=%s' % (
request.args['error_reason'],
request.args['error_description']
)
if isinstance(resp, OAuthException):
return 'Access denied: %s' % resp.message
session['oauth_token'] = (resp['access_token'], '')
me = remote.get('/user/me')
return 'Logged in as id=%s name=%s redirect=%s' % \
(me.data['id'], me.data['name'], request.args.get('next'))
app.run(port=9001)
Server code as I said almost the same as in https://github.com/authlib/example-oauth2-server repository.
When I'm trying to make an authorization I'm getting to the authorization server (on port 5000) and confirm that I allow access. But when I got redirect back to the client site on page http://127.0.0.1:9001/login/authorized?code=...&state=... (on 9001) I'm getting the error:
127.0.0.1 - - [20/Jun/2018 09:33:12] "GET /login/authorized?code=1jw8niqDdzSLpnYHGvT1NIulTwRdVoy22UNm3G4xEaTOWE9Y&state=JUuJtmnseITz8WZYaDeHcAsiIL6KfS HTTP/1.1" 500 -
Traceback (most recent call last):
File "/Users/xen/envs/auth-s4eELiZl/lib/python3.6/site-packages/flask/app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/xen/envs/auth-s4eELiZl/lib/python3.6/site-packages/flask/app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "/Users/xen/envs/auth-s4eELiZl/lib/python3.6/site-packages/flask/app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/xen/envs/auth-s4eELiZl/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/Users/xen/envs/auth-s4eELiZl/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/Users/xen/envs/auth-s4eELiZl/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/xen/envs/auth-s4eELiZl/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/xen/envs/auth-s4eELiZl/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/Users/xen/envs/auth-s4eELiZl/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/xen/envs/auth-s4eELiZl/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/xen/Dev/auth/client_example/client_testa.py", line 52, in testa_authorized
resp = remote.authorize_access_token()
File "/Users/xen/envs/auth-s4eELiZl/lib/python3.6/site-packages/authlib/flask/client/oauth.py", line 257, in authorize_access_token
raise MismatchingStateError()
authlib.client.errors.MismatchingStateError: mismatching_state: CSRF Warning! State not equal in request and response.
What can be wrong? Both parts use Authlib 0.8.
I've spent a lot of time to find an error in my code. The problem was not in the code, but in the way I use it. I accessed both applications by local IP address 127.0.0.1 and different ports. Browser mix sessions and cookies for such related URIs. I give another local domain name (http://test:9001 in my case) for the service and that fixed my problem.
When you work with OAuth don't use the local address and same domains.

python flask microframework not able to use session variable

from flask import Flask,redirect
from flask import session
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
#app.route('/signup', methods = ['POST'])
def signup():
email = 'xxxx'
session['email'] = email
print session['email']
print("The email address is '" + email + "'")
return redirect('/')
#app.route('/unregister', methods = ['POST'])
def unregister():
print "session check"
print session['email']
return 'We have removed from the list!'
if __name__ == '__main__':
app.secret_key = '#d\xe9X\x00\xbe~Uq\xebX\xae\x81\x1fs\t\xb4\x99\xa3\x87\xe6.\xd1_'
app.debug = True
app.run()
When I run this I am able to run a server on http://127.0.0.1:5000/. The problem I am facing is that I am able to use session in signup but not able to use it in unregister. I am using it through curl:
curl -X POST http://127.0.0.1:5000/unregister
I see this error:
127.0.0.1 - - [07/Apr/2016 16:06:08] "POST /unregister HTTP/1.1" 500 -
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ,
File "/usr/local/lib/python2.7/site-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1820, in
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/site-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1403, in
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/site-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/site-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/site-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/site-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/site-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/pvelumul/ACI/workspace/acitoolkit/applications/snapback/helloworld.py", line 20, in unregister
print session['email']
File "/usr/local/lib/python2.7/site-packages/Werkzeug-0.11.4-py2.7.egg/werkzeug/local.py", line 373, in <lambda>
__getitem__ = lambda x, i: x._get_current_object()[i]
KeyError: 'email'
You're missing a salient part:
When you assign a session variable, like this: session['email'] = email, Flask saves that info in the browser's cookie. Hence, it can only be read through the browser.
You are trying to read the session using a cURL POST request. But, the command line is different from the browser, which means cURL cannot has no access to the browser.
That way, reading session['email'] will return a KeyError which means, email is not present.
The proper way to read a session variable is when running the app in the browser, not through a command line request.
Also, you should use session.get('email') which returns None if the key is not present, rather than throw an error.
The problem I am facing is that I am able to use session in signup but not able to use it in unregister
When you visit /signup from the command line, you are only assigning to the session object in memory, which is no longer available after the code has finished running.