简体   繁体   English

Flask 应用程序:尝试对字典进行 jsonify

[英]flask application: trying to jsonify a dictionary

Background Info背景信息

I'm trying to write my first flask / python REST API.我正在尝试编写我的第一个 Flask/python REST API。 So far, I have a GET that connects to a redis database and tries to convert a dictionary to json... and then return those results.到目前为止,我有一个 GET 连接到 redis 数据库并尝试将字典转换为 json ......然后返回这些结果。

Problem问题

When I try to call jsonify on my dict object, it fails with the following error:当我尝试在我的 dict 对象上调用 jsonify 时,它失败并出现以下错误:

Traceback (most recent call last):
  File "/usr/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/usr/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/var/www/localhost/htdocs/widgets/widgets.py", line 51, in get_profile
    return jsonify(res_dict)
  File "/usr/lib/python3.6/site-packages/flask/json.py", line 263, in jsonify
    (dumps(data, indent=indent, separators=separators), '\n'),
  File "/usr/lib/python3.6/site-packages/flask/json.py", line 123, in dumps
    rv = _json.dumps(obj, **kwargs)
  File "/usr/lib/python3.6/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "/usr/lib/python3.6/json/encoder.py", line 201, in encode
    chunks = list(chunks)
  File "/usr/lib/python3.6/json/encoder.py", line 430, in _iterencode
    yield from _iterencode_dict(o, _current_indent_level)
  File "/usr/lib/python3.6/json/encoder.py", line 376, in _iterencode_dict
    raise TypeError("key " + repr(key) + " is not a string")
TypeError: key b'email1' is not a string

The code looks like this:代码如下所示:

 20 def get_db_profile(mailbox):
 21     """ connects to redis and queries for profile """
 22     try:
 23         my_redis = redis.Redis(connection_pool=POOL)
 24         response = my_redis.hgetall(55555)
 25         logging.info(response.keys())
 26         logging.info(response.items())
 27         #response = '123455555'
 28         return response
 29     except Exception as ex:
 30         return "Error:", ex

47 @application.route("/widgets/api/<int:mailbox>", methods=['GET'])
48 def get_profile(mailbox):
49     res_dict = get_db_profile(mailbox)
50 #    return application.response_class(jsonify(res_dict), content_type='application/json')
51     return jsonify(res_dict)
52 #    return '12345'
53

I added some logging as you can see on line 25 to see what the keys() look like.我添加了一些日志,如您在第 25 行看到的那样,以查看 keys() 的样子。 this is what I see in the log file:这是我在日志文件中看到的:

lab-1:/var/www/localhost/htdocs/widgets# cat /tmp/widgets.log
root - INFO - dict_keys([b'email1', b'email2'])

REDIS Data Redis数据

This is how I created the redis data:这就是我创建 redis 数据的方式:

127.0.0.1:6379[5]> hmset 55555 email1 johndoe@hotmail.com email2 jd@yahoo.com
OK
127.0.0.1:6379[5]>

Questions问题

Should i be able to convert from dict object to json string?我应该能够从 dict 对象转换为 json 字符串吗? What is the 'b' in the log files?日志文件中的“b”是什么?

lab-1:/var/www/localhost/htdocs/widgets# cat /tmp/widgets.log
root - INFO - dict_keys([b'email1', b'email2'])
root - INFO - dict_items([(b'email1', b'johndoe@hotmail.com'), (b'email2', b'jd@yahoo.com')])

How do I send back a proper JSON response?如何发回正确的 JSON 响应?

EDIT 1编辑 1

I found this question/answer: How to parse python b' string containing dict and based on that I tried to change my logic to look like this:我找到了这个问题/答案: How to parse python b' string contains dict并基于此我试图将我的逻辑更改为如下所示:

47 @application.route("/pvmailprofiles/api/<int:mailbox>", methods=['GET'])
48 def get_profile(mailbox):
49     res_dict = get_db_profile(mailbox)
50 #    return application.response_class(jsonify(res_dict), content_type='application/json')
51     #return jsonify(res_dict)
52     return res_dict[b'email1']
53 #    return '12345'
54

Line 52 - you can see that as a test I've hardcoded the 'b' and then the key name.第 52 行 - 您可以看到作为测试,我已经硬编码了 'b',然后是键名。 And it works - it returns the specific email address.它有效 - 它返回特定的电子邮件地址。 But I need to find a way to "just" convert everything to json and return to callee.但我需要找到一种方法来“只是”将所有内容转换为 json 并返回给被调用者。

Have you tried first importing json like so你有没有试过像这样先导入json

import json

and then doing然后做

json.dumps(myDict)

and then to load it again if needed.然后在需要时再次加载它。

json.loads(response.text)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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