加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

在JSON中对数据进行编码之前,如何将数据从SQLite数据库中读取到

发布时间:2020-12-16 22:12:57 所属栏目:Python 来源:网络整理
导读:我是python的初学者并使用SQLite.所以请耐心等待我.我不完全确定我应该提供多少信息,因此我决定提供与我认为相关的代码.就像俗话说的那样;比抱歉更安全. 基本上,我所拥有的是一个python脚本,运行一个对等社交网络Web应用程序的樱桃服务器.我有一种方法可以记

我是python的初学者并使用SQLite.所以请耐心等待我.我不完全确定我应该提供多少信息,因此我决定提供与我认为相关的代码.就像俗话说的那样;比抱歉更安全.

基本上,我所拥有的是一个python脚本,运行一个对等社交网络Web应用程序的樱桃服务器.我有一种方法可以记录我对我的个人资料所做的三种更新;新帖子,新照片或新活动.

每个更新包含以下字段:

messageID: A 16 letter string containing a unique identifier
creator: My user name
created: A time stamp,UNIX Epoch time,of when the update took place
body: A short message about the update.
Link: A link to the update. e.g.. "/gallery/photo5"
Type: type 1 means new post,2 means photo,3 means event.

我已将这些字段设置为使用SQLite创建的数据库中的表的列,这是我用来执行此操作的方法:

    @cherrypy.expose
    def writeUpdate(self,type=None):
        """This method is called whenever a change takes place on the Acebook
        It takes an input 'type' to know what kind of update it is.
        The method then make appropriet change to the 'Updates' database
        """

        con = lite.connect('static/database/Updates.db')
        messageID = self.randomword()
        creator = trueUser
        created = time.time()
        if type == 1:
            link = "/homepage"
            body = "New Status Update"
        elif type == 2:
            link = "/portfolio"
            body = "New Photo Update"
        elif type ==3:
            link = "/event"
            body = "New Event Update"
        else:
            link = "/homepage"
            body = "If you are seeing this,something is not quite right with by server"

        with con:

            cur = con.cursor() 
            cur.execute("CREATE TABLE IF NOT EXISTS Updates(messageID TEXT,creator TEXT,created INT,link TEXT,type INT,body TEXT)")   
            cur.execute("INSERT INTO Updates VALUES(?,?,?)",(messageID,creator,created,link,type,body))

            "Debugging check"
            cur.execute('select * from Updates')
            print "The Updates database now contains:"
            for row in cur:
                print row


        return          

我有另一种方法,我的朋友可以打电话来获取我最新更新的新闻.这种方法是:

@cherrypy
def getActivity(self,minutes=48*60):
“”” Return any updates since last time this user requested them. Optional argument returns the last updates in the given time period instead.
“””
# current_user = getAuthenticatedUser(): # if not current_user:
# return “Please Authenticate”
# updates = getUpdatesByUser(current_user)

ExampleUpdate = [ {
‘messageID’: “ccog001-1332889924-839”,‘creator’: “ccog001”,‘created’: 1332889924,‘link’: “/updates?id=839”,‘type’: 1,‘body’: “Hello,is anybody out there?”
},{
‘messageID’: “ccog001-1332890482-840”,‘created’: 1332890482,‘link’: “/updates?id=840”,‘body’: “Seriously,is this thing on?” }
]


reply = json.dumps(updates)
return reply

我的问题是,如何将数据库的各个行读入单独的字典,然后将所有字典组合成变量Example Update的格式,然后使用json.dumps对其进行编码?

或者,在将字典写入数据库之前,首先将messageID,created …等编写到字典中可能会更容易吗?所以我最终得到的数据库只包含一列词典?如果是这样,代码会是什么样的?

我很新,所以请在答案中详细说明,最好附上代码和评论以帮助我理解.

非常感谢你的时间

最佳答案
执行SELECT语句后,列名称存储在Cursor.description中.根据docs,此列表中的每个条目都是一个7元组,其中第一个元素由列的名称填充.

您可以提取列名称并形成一个dict,如下所示:

cur.execute('select * from Updates')

# extract column names
column_names = [d[0] for d in cur.description]

for row in cur:
  # build dict
  info = dict(zip(column_names,row))

  # dump it to a json string
  reply = json.dumps(info)

在这里,zip获取两个列表column_names和row,并将它们按元素一起拼接到元组列表中. dict然后把它变成一个准备让json转储的字典.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读