Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hi i used your repo in flask it give error "KeyError: 'userid'" #13

Closed
kartikdanidhariya opened this issue Aug 19, 2016 · 26 comments
Closed

Comments

@kartikdanidhariya
Copy link

hi i setup all file in my virtual env but it return error

KeyError
KeyError: 'userid'
Traceback is

Traceback (most recent call last):
File "/home/vrs/Flask/big-commerce/lib/python2.7/site-packages/flask/app.py", line 1836, in call
return self.wsgi_app(environ, start_response)
File "/home/vrs/Flask/big-commerce/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/home/vrs/Flask/big-commerce/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/vrs/Flask/big-commerce/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/home/vrs/Flask/big-commerce/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/vrs/Flask/big-commerce/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/vrs/Flask/big-commerce/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/home/vrs/Flask/big-commerce/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functionsrule.endpoint
File "/home/vrs/Flask/big-commerce/hello-world-app-python-flask/app.py", line 238, in index
user = User.query.filter_by(id=flask.session['userid']).first()
File "/home/vrs/Flask/big-commerce/lib/python2.7/site-packages/werkzeug/local.py", line 368, in
getitem = lambda x, i: x._get_current_object()[i]
KeyError: 'userid'

how can i solve this error

@bookernath
Copy link
Contributor

This is because you're missing a userid in your session. Mostly likely this is because you tried to open the app directly instead of loading it via the BigCommerce control panel. You'll want to connect the app to the BigCommerce app store by setting it up on devtools.bigcommerce.com with the correct callback and load URL, then try loading it from within BigCommerce. The readme has some details on that.

@Johnathanrs
Copy link

Johnathanrs commented Aug 15, 2018

Booker I did this. It still doesn't work. I opened it directly and through the control panel. It is generating a Internal Server Error. Can you provide documentation that better goes over this or a example? Every documentation link that I have found is broken or unrelated.

@bookernath
Copy link
Contributor

bookernath commented Aug 15, 2018

@Johnathanrs what logs do you see server-side when you get an internal server error?

@Johnathanrs
Copy link

Johnathanrs commented Aug 15, 2018

Booker,

The SSL certificate used to load resources from https://c.la4-c2-dfw.salesforceliveagent.com will be distrusted in M70. Once distrusted, users will be prevented from loading these resources. See https://g.co/chrome/symantecpkicerts for more information.

s3.amazonaws.com/:1 Failed to load resource: the server responded with a status of 403 
(Forbidden)
VM464:4 Uncaught TypeError: Cannot read property 'get' of undefined
at k (<anonymous>:4:19)
at initNewOptimizelyIntegration (<anonymous>:4:120)
at initOptimizelyIntegration (<anonymous>:4:169)
at <anonymous>:4:204
at gtm.js?id=GTM-D9S9:3710
at Object.c [as __html] (gtm.js?id=GTM-D9S9:3712)
at Yb (gtm.js?id=GTM-D9S9:3601)
at h (gtm.js?id=GTM-D9S9:3633)
at gtm.js?id=GTM-D9S9:3624
at Array.<anonymous> (gtm.js?id=GTM-D9S9:3635)
at Array.<anonymous> (gtm.js?id=GTM-D9S9:3634)
at he (gtm.js?id=GTM-D9S9:3641)
at ie (gtm.js?id=GTM-D9S9:3641)
at d (raven.js:522)


<Error>
<Code>AccessDenied</Code>
<Message>Access Denied</Message>
<RequestId>8D456834DDB8B0BC</RequestId>
<HostId> ***HIDDEN***
</HostId>
</Error>

I should make a note that I ran it both locally and deployed it through heroku. It works in neither stage. I also ran the PHP version, and it worked fine, so it tells me that their is a problem here specifically with the python tutorial app.

@bookernath
Copy link
Contributor

bookernath commented Aug 15, 2018

This appears to be an error log from within the browser itself - do you have a server side error log?

If you're using heroku, you can get this by causing the issue (get the server error on your screen) and then running heroku logs -a your-app-name in the heroku CLI and looking at the most recent output

@Johnathanrs
Copy link

2018-08-15T02:06:37.340803+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request
2018-08-15T02:06:37.340804+00:00 app[web.1]: rv = self.dispatch_request()
2018-08-15T02:06:37.340806+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request
2018-08-15T02:06:37.340807+00:00 app[web.1]: return self.view_functionsrule.endpoint
2018-08-15T02:06:37.340809+00:00 app[web.1]: File "/app/app.py", line 280, in index
2018-08-15T02:06:37.340811+00:00 app[web.1]: storeuser = StoreUser.query.filter_by(id=flask.session['storeuserid']).first()
2018-08-15T02:06:37.340812+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/werkzeug/local.py", line 377, in
2018-08-15T02:06:37.340814+00:00 app[web.1]: getitem = lambda x, i: x._get_current_object()[i]
2018-08-15T02:06:37.340823+00:00 app[web.1]: KeyError: 'storeuserid'
2018-08-15T02:06:37.341279+00:00 app[web.1]: 10.35.245.163 - - [15/Aug/2018:02:06:37 +0000] "GET / HTTP/1.1" 500 - "-" "-"

@bookernath
Copy link
Contributor

bookernath commented Aug 15, 2018

I'm curious if your database is initialized - if you installed via the heroku button, this should have happened automatically.

Do you see any tables in your database, and do you see a store's details in them?

If you don't see any tables, try logging into the dyno (heroku run python -a your-app-name) and then running:

from app import db
db.create_all()

@Johnathanrs
Copy link

Johnathanrs commented Aug 15, 2018

No change. You are welcome to run up a trial yourself real fast or you can also have access to my accounts and see if you can get a trial working. I have nothing sensitive on them right now.

@bookernath
Copy link
Contributor

I'm trying to spin it up locally to see if I can replicate your issue; I've only used heroku with this app in recent years because it absorbs a lot of the complexity around the installation process. :)

What are your callback URLs when you're using it locally? Are you using something like ngrok for tunneling? Is your app URL env variable different from your callback URL, perhaps it's localhost?

It would seem that you're getting at least this far:

https://github.com/bigcommerce/hello-world-app-python-flask/blob/master/app.py#L181-L182

But by the time you get here, flask can't access the session cookie:

https://github.com/bigcommerce/hello-world-app-python-flask/blob/master/app.py#L280

This could happen if the hostname changed between the callback and the index, as we wouldn't have access to the cookie.

@bookernath bookernath reopened this Aug 15, 2018
@Johnathanrs
Copy link

Johnathanrs commented Aug 15, 2018

Yes I tried using ngrok and I changed my local variables and did a echo to verify that they were pulling correctly. I used localhost and 0.0.0.0 including different ports.

I don't understand though how this would impact heroku however because I am hosting it through them. As long as the user enters in the proper API callbacks that is generated through the website, which I did and re-tried 3 times, it should go through no problem seeing how you created the heroku launch. I also verified that I was doing the process correctly through a PHP install and it worked just fine when I deployed it. I am new to Heroku but it does the installation process for you. I can understand me doing something wrong locally, but again when I deploy it through heroku, how would the this deployment become affected by any of this?

@bookernath
Copy link
Contributor

Yeah the specific error you're seeing is flask saying "hey we couldn't find (this value) in the session cookie", probably because there was no session cookie. So now we're back to the frontend, figuring out if the cookie is available in the right place...

You might try opening your app URL directly and checking for this cookie:

image

@Johnathanrs
Copy link

Johnathanrs commented Aug 15, 2018

This takes us back to my original post. I think you are right. I think that the flask session object is getting loaded because of this function:
api.oauth_fetch_token(client_secret, code, context, scope, redirect_uri) -- fetches and returns an access token for your application. As a side effect, configures api to be ready for use.

I think the access is getting denied because it isn't properly being generated, but I don't know enough about Oauth to recreate this on my own and see what these fields require.

I tried generating this on my own and did it step-by-step through the shell and got hit with a error, but I am not sure on how to invoke this because I don't know what these fields represent.

@bookernath
Copy link
Contributor

I tried setting my ngrok URL as my APP_URL and it works:

DEBUG=True
LISTEN_HOST=localhost
LISTEN_PORT=5000
APP_URL=https://3d40e897.ngrok.io
APP_CLIENT_ID=(my client ID)
APP_CLIENT_SECRET=(my client secret)
SESSION_SECRET=(long random string)
DATABASE_PATH=data/hello_world.db

@Johnathanrs
Copy link

Johnathanrs commented Aug 15, 2018

Internal Server Error: 'storeuserid'
(This page threw an exception: 'KeyError' object has no attribute 'headers')

Is what i'm seeing when I click on your URL

@bookernath
Copy link
Contributor

Do your URLs in the dev tools area match?

Mine:

image

Note that changes here may need a hard refresh, and even a minute or two to be reflected.

@Johnathanrs
Copy link

Johnathanrs commented Aug 15, 2018

I have it set to store owner, but everything else is the same. I didn't think that would impact anything, but do you want me to adjust it to multiple users? Yes, they match the settings from heroku though.

@bookernath
Copy link
Contributor

Multiple users shouldn't really matter.

So just to confirm, you're trigger the app install flow from "my draft apps"?

https://your-store-url.com/manage/marketplace/apps/my-apps/drafts and clicking install?

@Johnathanrs
Copy link

screen shot 2018-08-14 at 7 56 52 pm

![screen shot 2018-08-14 at 7 59 39 pm](https://user-images.githubusercontent.com/4458906/44129351-9d081294-9ffc-11e8-92e2-5f06cdfa08e4.png)

@bookernath
Copy link
Contributor

bookernath commented Aug 15, 2018

Here's a problem:

https://user-images.githubusercontent.com/4458906/44129351-9d081294-9ffc-11e8-92e2-5f06cdfa08e4.png

You need to replace the value of APP_URL with https://secondgo.herokuapp.com

Check out the instructions page here: http://secondgo.herokuapp.com/instructions (disappears when you turn off debug)

@Johnathanrs
Copy link

screen shot 2018-08-14 at 8 03 28 pm

@Johnathanrs
Copy link

Johnathanrs commented Aug 15, 2018

I added the value, re-launched dynos, no change.

@bookernath
Copy link
Contributor

In your screenshot you're just loading the URL; can you also try the install from within the store?

https://your-store-url.com/manage/marketplace/apps/my-apps/drafts (replace store URL with your own, probably works best if you're already logged in)

You want to be logged in as the store owner account on the store, and using the same email you use for devtools.

@Johnathanrs
Copy link

Johnathanrs commented Aug 15, 2018

Okay got you. It's working! Thank you booker!

You might want to update your tutorial with the app details, I found a few other posts online that had the same error when trying to run this up. Thank you so much for your time!

@bookernath
Copy link
Contributor

Sure, and thank you for highlighting your experience so we can improve the readme and docs!

@bookernath
Copy link
Contributor

We've pushed some readme updates in #25

Closing.

@sreeragct
Copy link

Hi There,

I am also getting the same error while hosting the site in heroku. could you please help me out to resolve the issue.

Here is my code below

from common.database import Database
from models.blog import Blog
from models.post import Post
from models.user import User

from flask import Flask, render_template, request, session, make_response

app = Flask(name) # 'main'

app.secret_key='secret123'

@app.route('/')
def home_template():
return render_template('home.html')

@app.route('/login')
def login_template():
return render_template('login.html')

@app.route('/register')
def register_template():
return render_template('register.html')

@app.before_first_request
def initialize_database():
Database.initialize()

@app.route('/auth/login', methods=['POST'])
def login_user():
email = request.form['email']
password = request.form['password']

if User.login_valid(email, password):
    User.login(email)
else:
    session['email'] = None

return render_template("profile.html", email=session['email'])

@app.route('/auth/register', methods=['POST','GET'])
def register_user():
email = request.form['email']
password = request.form['password']

User.register(email, password)

return render_template("profile.html", email=session['email'])

@app.route('/blogs/string:user_id')
@app.route('/blogs')
def user_blogs(user_id=None):
if user_id is not None:
user = User.get_by_id(user_id)
else:
user = User.get_by_email(session['email'])

blogs = user.get_blogs()

return render_template("user_blogs.html", blogs=blogs, email=user.email)

@app.route('/blogs/new', methods=['POST', 'GET'])
def create_new_blog():
if request.method == 'GET':
return render_template('new_blog.html')
else:
title = request.form['title']
description = request.form['description']
user = User.get_by_email(session['email'])

    new_blog = Blog(user.email, title, description, user._id)
    new_blog.save_to_mongo()

    return make_response(user_blogs(user._id))

@app.route('/posts/string:blog_id')
def blog_posts(blog_id):
blog = Blog.from_mongo(blog_id)
posts = blog.get_posts()

return render_template('posts.html', posts=posts, blog_title=blog.title, blog_id=blog._id)

@app.route('/posts/new/string:blog_id', methods=['POST', 'GET'])
def create_new_post(blog_id):
if request.method == 'GET':
return render_template('new_post.html', blog_id=blog_id)
else:
title = request.form['title']
content = request.form['content']
user = User.get_by_email(session['email'])

    new_post = Post(blog_id, title, content, user.email)
    new_post.save_to_mongo()

    return make_response(blog_posts(blog_id))

if name == 'main':
app.run( debug=True)

Uers.py

import datetime
import uuid
from flask import session
from common.database import Database
from models.blog import Blog

author = 'jslvtr'

class User(object):
def init(self, email, password, _id=None):
self.email = email
self.password = password
self._id = uuid.uuid4().hex if _id is None else _id

@classmethod
def get_by_email(cls, email):
    data = Database.find_one("users", {"email": email})
    if data is not None:
        return cls(**data)

@classmethod
def get_by_id(cls, _id):
    data = Database.find_one("users", {"_id": _id})
    if data is not None:
        return cls(**data)

@staticmethod
def login_valid(email, password):
    # Check whether a user's email matches the password they sent us
    user = User.get_by_email(email)
    if user is not None:
        # Check the password
        return user.password == password
    return False

@classmethod
def register(cls, email, password):
    user = cls.get_by_email(email)
    if user is None:
        # User doesn't exist, so we can create it
        new_user = cls(email, password)
        new_user.save_to_mongo()
        session['email'] = email
        return True
    else:
        # User exists :(
        return False

@staticmethod
def login(user_email):
    # login_valid has already been called
    session['email'] = user_email

@staticmethod
def logout():
    session['email'] = None

def get_blogs(self):
    return Blog.find_by_author_id(self._id)

def new_blog(self, title, description):
    blog = Blog(author=self.email,
                title=title,
                description=description,
                author_id=self._id)

    blog.save_to_mongo()

@staticmethod
def new_post(blog_id, title, content, date=datetime.datetime.utcnow()):
    blog = Blog.from_mongo(blog_id)
    blog.new_post(title=title,
                  content=content,
                  date=date)

def json(self):
    return {
        "email": self.email,
        "_id": self._id,
        "password": self.password
    }

def save_to_mongo(self):
    Database.insert("users", self.json())

The error i am getting is as follows:

[2020-01-06 10:45:24,955] ERROR in app: Exception on /auth/register [POST]
2020-01-06T10:45:24.957774+00:00 app[web.1]: Traceback (most recent call last):
2020-01-06T10:45:24.957777+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 2446, in wsgi_app
2020-01-06T10:45:24.957778+00:00 app[web.1]: response = self.full_dispatch_request()
2020-01-06T10:45:24.957781+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1951, in full_dispatch_request
2020-01-06T10:45:24.957783+00:00 app[web.1]: rv = self.handle_user_exception(e)
2020-01-06T10:45:24.957785+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1820, in handle_user_exception
2020-01-06T10:45:24.957787+00:00 app[web.1]: reraise(exc_type, exc_value, tb)
2020-01-06T10:45:24.957789+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise
2020-01-06T10:45:24.957792+00:00 app[web.1]: raise value
2020-01-06T10:45:24.957794+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1949, in full_dispatch_request
2020-01-06T10:45:24.957796+00:00 app[web.1]: rv = self.dispatch_request()
2020-01-06T10:45:24.957798+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1935, in dispatch_request
2020-01-06T10:45:24.957800+00:00 app[web.1]: return self.view_functionsrule.endpoint
2020-01-06T10:45:24.957802+00:00 app[web.1]: File "/app/app.py", line 55, in register_user
2020-01-06T10:45:24.957804+00:00 app[web.1]: return render_template("profile.html", email=session['email'])
2020-01-06T10:45:24.957806+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/werkzeug/local.py", line 378, in
2020-01-06T10:45:24.957808+00:00 app[web.1]: getitem = lambda x, i: x._get_current_object()[i]
2020-01-06T10:45:24.957810+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/sessions.py", line 84, in getitem
2020-01-06T10:45:24.957812+00:00 app[web.1]: return super(SecureCookieSession, self).getitem(key)
2020-01-06T10:45:24.957820+00:00 app[web.1]: KeyError: 'email'
2020-01-06T10:45:24.958890+00:00 app[web.1]: 10.35.212.74 - - [06/Jan/2020:10:45:24 +0000] "POST /auth/register HTTP/1.1" 500 290 "https://test-on-you.herokuapp.com/register" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants