简体   繁体   中英

Python/Flask - Object of type "TypeError' is not JSON serializable

I am using python/flask to build a simple login page for my website and am having trouble verifying the hash pulled from my DB. When I submit the form, I get an internal server error. The apache logs show "Object of type "TypeError' is not JSON serializable." I've created multiple users so it doesn't appear to be related to a single hash. Any help is appreciated

app.route("/login/",methods=['GET','POST'])
def loginpage():
    error=''
    try:
        c,conn= connectorConnection()
        if request.method == 'POST':
            c.execute("select * from users where username = ('%s')" % 
                      request.form['username'])
            data = c.fetchone()
            if sha256_crypt.verify(request.form['password'], data):
                session['logged_in'] = True
                session['username'] = request.form['username']
                flash(' you are now logged in')
                return redirect(url_for('home'))
            else:
                error = 'Invalid Credentials'

        gc.collect()

        return render_template('login.html',error=error)

Stracktrace:

Traceback (most recent call last):
  File "C:\Users\Tank\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\Tank\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1816, in full_dispatch_request
    return self.finalize_request(rv)
  File "C:\Users\Tank\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1833, in finalize_request
    response = self.process_response(response)
  File "C:\Users\Tank\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 2114, in process_response
    self.session_interface.save_session(self, ctx.session, response)
  File "C:\Users\Tank\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\sessions.py", line 375, in save_session
    val = self.get_signing_serializer(app).dumps(dict(session))
  File "C:\Users\Tank\AppData\Local\Programs\Python\Python36\lib\site-packages\itsdangerous\serializer.py", line 166, in dumps
    payload = want_bytes(self.dump_payload(obj))
  File "C:\Users\Tank\AppData\Local\Programs\Python\Python36\lib\site-packages\itsdangerous\url_safe.py", line 42, in dump_payload
    json = super(URLSafeSerializerMixin, self).dump_payload(obj)
  File "C:\Users\Tank\AppData\Local\Programs\Python\Python36\lib\site-packages\itsdangerous\serializer.py", line 133, in dump_payload
    return want_bytes(self.serializer.dumps(obj, **self.serializer_kwargs))
  File "C:\Users\Tank\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\json\tag.py", line 296, in dumps
    return dumps(self.tag(value), separators=(',', ':'))
  File "C:\Users\Tank\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\json\__init__.py", line 179, in dumps
    rv = _json.dumps(obj, **kwargs)
  File "C:\Users\Tank\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "C:\Users\Tank\AppData\Local\Programs\Python\Python36\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Users\Tank\AppData\Local\Programs\Python\Python36\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:\Users\Tank\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\json\__init__.py", line 81, in default
    return _json.JSONEncoder.default(self, o)
  File "C:\Users\Tank\AppData\Local\Programs\Python\Python36\lib\json\encoder.py", line 180, in default
    o.__class__.__name__)
TypeError: Object of type 'TypeError' is not JSON serializable
127.0.0.1 - - [18/Feb/2019 20:23:40] "[1m[35mPOST /login/ HTTP/1.1[0m" 500 -
app.route("/login/",methods=['GET','POST'])
def loginpage():
    try:
        your code here
    except Exception as e:
        print(e)  
        # Now you can see what the real issue is...
        return json.dumps({'success':True}), 200, 
                          {'ContentType':'application/json'}) 

After adding a try/except per balderman's suggestion, the error showed "hash must be unicode or bytes, not tuple" . It turns out my password table in my database was too short (45 chars). Altering the table to allow 200 chars allowed the full hash to be inserted. Thanks for the help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM