1

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

13
  • app.run(host='0.0.0.0',port=5000) could you modify your port. Commented Dec 6, 2017 at 9:39
  • If you want to execute it 24/7 on linux. You could execute it as a background tasks. Using nohup python <file> & Commented Dec 6, 2017 at 9:41
  • You could save your script as a python file. For example, sql.py. When you execute python sql.py >>test.log. The log will save into test.log. You could parse data to json format. Commented Dec 6, 2017 at 10:02
  • Yes, you could modify port to 80. Commented Dec 6, 2017 at 10:06
  • I suggest you could save output to a file. Commented Dec 6, 2017 at 10:07

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.