I wrote the following sample script for learning purposes:
import requests
import json
import pyodbc
import os
import sys
source_url = 'https://jsonplaceholder.typicode.com/posts/'
query_posts_response = requests.get(source_url)
if (query_posts_response.status_code == 200):
posts = json.loads(query_posts_response.content.decode('utf-8'))
db_connection = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
"Server=(local);"
"Database=sandbox;"
"Trusted_Connection=yes;")
sys_devnull = open(os.devnull, 'w')
sys_stdout_original = sys.stdout
sys.stdout = sys_devnull
db_cursor = db_connection.cursor()
for post in posts:
db_cursor.execute("INSERT INTO dbo.Posts(id, title) VALUES (?, ?)", post['id'], post['title'])
db_connection.commit()
db_connection.close()
sys.stdout = sys_stdout_original
I'm grabbing content from a REST API, and I'm inserting it into a relational table.
I write scripts in other languages, but this is my first Python script. I don't know what I don't know. I'm looking for a critique. I realize I was lazy on the database call and didn't create an exception handler. That said, is this the generally accepted way to interface with a REST endpoint and interact with a database?
Concerning output of db_cursor.execute()
, see the following:
sys.stdout
during the database operations? \$\endgroup\$ – 200_success Oct 24 '18 at 21:34execute()
call generated all this jibber jabber so I piped it to /dev/null. Probably doesn't make sense in a script? \$\endgroup\$ – Adam Oct 24 '18 at 21:36execute()
should be silent. It doesn't ever make sense to squelch stdout. \$\endgroup\$ – 200_success Oct 24 '18 at 21:37execute()
is not silent - see revised post. \$\endgroup\$ – Adam Oct 25 '18 at 18:54