Reputation: 37
Question. I would like to create a REST API for the data stored in an Azure SQL DB that will allow me to do GET and POST operation using Python. Currently I managed to print the results of my query on the terminal but how do I convert it to JSON format and allow it to run 24/7 on linux (perhaps change port?)? Below is my script:
import pyodbc
from flask import Flask, jsonify, request
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class Energy(Resource):
def get(self):
server = 'testserver.database.windows.net'
database = 'testdb'
username = 'admin'
password = '735t'
driver= '{ODBC Driver 13 for SQL Server}'
connexion = pyodbc.connect('DRIVER='+driver+';PORT=1433;SERVER='+server+';PORT=1443;DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = connexion.cursor()
cursor.execute("SELECT TOP (100) * FROM [dbo].[Power_Meter]")
row = cursor.fetchone()
while row:
GeneratedCode = str(row[0])
ReportedDate = str(row[1])
print (str(row[0]) + " " + str(row[1]))
row = cursor.fetchone()
rest_row = jsonify(row)
return rest_row
api.add_resource(Energy, '/DPM')
if __name__ == '__main__':
app.run(debug=True)
and this is the output result on localhost:5000/DPM
null
Can anyone suggest me how to go about solving this issue? Thanks
Upvotes: 1
Views: 254
Reputation: 19225
If you want to run your script 24/7 on Linux, you could execute it as a background task. Using nohup python sql.py>> test.log &
man nohup
nohup - run a command immune to hangups, with output to a non-tty
& to the command line to run in the background:
If you want to change port, just change like below:
app.run(host='0.0.0.0',port=5000)
I suggest you could store output to a file. Then you could parse data to json format.
Upvotes: 1