Advertisement
Guest User

Untitled

a guest
May 4th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.87 KB | None | 0 0
  1. import simplejson
  2.  
  3. from sqlobject import *
  4.  
  5. # Replace this with the URI for your actual database
  6. connection = connectionForURI('sqlite:/:memory:')
  7. sqlhub.processConnection = connection
  8.  
  9. # This defines the columns for your database table. See SQLObject docs for how it
  10. # does its conversions for class attributes <-> database columns (underscores to camel
  11. # case, generally)
  12.  
  13. class Song(SQLObject):
  14.  
  15. name = StringCol()
  16. artist = StringCol()
  17. album = StringCol()
  18.  
  19. # Create fake data for demo - this is not needed for the real thing
  20. def MakeFakeDB():
  21. Song.createTable()
  22. s1 = Song(name="B Song",
  23. artist="Artist1",
  24. album="Album1")
  25. s2 = Song(name="A Song",
  26. artist="Artist2",
  27. album="Album2")
  28.  
  29. def Main():
  30. # This is an iterable, not a list
  31. all_songs = Song.select().orderBy(Song.q.name)
  32.  
  33. songs_as_dict = []
  34.  
  35. for song in all_songs:
  36. song_as_dict = {
  37. 'name' : song.name,
  38. 'artist' : song.artist,
  39. 'album' : song.album}
  40. songs_as_dict.append(song_as_dict)
  41.  
  42. print simplejson.dumps(songs_as_dict)
  43.  
  44.  
  45. if __name__ == "__main__":
  46. MakeFakeDB()
  47. Main()
  48.  
  49. import json
  50. import psycopg2
  51.  
  52. def db(database_name='pepe'):
  53. return psycopg2.connect(database=database_name)
  54.  
  55. def query_db(query, args=(), one=False):
  56. cur = db().cursor()
  57. cur.execute(query, args)
  58. r = [dict((cur.description[i][0], value)
  59. for i, value in enumerate(row)) for row in cur.fetchall()]
  60. cur.connection.close()
  61. return (r[0] if r else None) if one else r
  62.  
  63. my_query = query_db("select * from majorroadstiger limit %s", (3,))
  64.  
  65. json_output = json.dumps(my_query)
  66.  
  67. >>> json_output
  68. '[{"divroad": "N", "featcat": null, "countyfp": "001",...
  69.  
  70. >>> j2 = query_db("select * from majorroadstiger where fullname= %s limit %s",
  71. ("Mission Blvd", 1), one=True)
  72.  
  73. >>> j2 = json.dumps(j2)
  74. >>> j2
  75. '{"divroad": "N", "featcat": null, "countyfp": "001",...
  76.  
  77. qry = "Select Id, Name, Artist, Album From MP3s Order By Name, Artist"
  78. # Assumes conn is a database connection.
  79. cursor = conn.cursor()
  80. cursor.execute(qry)
  81. rows = [x for x in cursor]
  82. cols = [x[0] for x in cursor.description]
  83. songs = []
  84. for row in rows:
  85. song = {}
  86. for prop, val in zip(cols, row):
  87. song[prop] = val
  88. songs.append(song)
  89. # Create a string representation of your array of songs.
  90. songsJSON = json.dumps(songs)
  91.  
  92. import sqlite3
  93. import json
  94.  
  95. DB = "./the_database.db"
  96.  
  97. def get_all_users( json_str = False ):
  98. conn = sqlite3.connect( DB )
  99. conn.row_factory = sqlite3.Row # This enables column access by name: row['column_name']
  100. db = conn.cursor()
  101.  
  102. rows = db.execute('''
  103. SELECT * from Users
  104. ''').fetchall()
  105.  
  106. conn.commit()
  107. conn.close()
  108.  
  109. if json_str:
  110. return json.dumps( [dict(ix) for ix in rows] ) #CREATE JSON
  111.  
  112. return rows
  113.  
  114. print get_all_users()
  115.  
  116. [(1, u'orvar', u'password123'), (2, u'kalle', u'password123')]
  117.  
  118. print get_all_users( json_str = True )
  119.  
  120. [{"password": "password123", "id": 1, "name": "orvar"}, {"password": "password123", "id": 2, "name": "kalle"}]
  121.  
  122. from contextlib import closing
  123. from datetime import datetime
  124. import json
  125. import MySQLdb
  126. DB_NAME = 'x'
  127. DB_USER = 'y'
  128. DB_PASS = 'z'
  129.  
  130. def get_tables(cursor):
  131. cursor.execute('SHOW tables')
  132. return [r[0] for r in cursor.fetchall()]
  133.  
  134. def get_rows_as_dicts(cursor, table):
  135. cursor.execute('select * from {}'.format(table))
  136. columns = [d[0] for d in cursor.description]
  137. return [dict(zip(columns, row)) for row in cursor.fetchall()]
  138.  
  139. def dump_date(thing):
  140. if isinstance(thing, datetime):
  141. return thing.isoformat()
  142. return str(thing)
  143.  
  144.  
  145. with closing(MySQLdb.connect(user=DB_USER, passwd=DB_PASS, db=DB_NAME)) as conn, closing(conn.cursor()) as cursor:
  146. dump = {}
  147. for table in get_tables(cursor):
  148. dump[table] = get_rows_as_dicts(cursor, table)
  149. print(json.dumps(dump, default=dump_date, indent=2))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement