I’m new to python and have been put on a task of building out a spreadsheet parser. I’ve created a python script that reads an xlsx file and parses the data. I have an Nginx server set up that this will be hosted on. I need this script to be an API endpoint so I can pass the parsed data back as JSON. I have been reading about WSGI for production server and have tried to follow the route of building that out. I am able to serve a path on the server and have it output the wsgi python script. The script has the following:
def application(environ, start_response):
status = '200 OK'
html = '<html>n'
'<body>n'
' Hooray, mod_wsgi is workingn'
'</body>n'
'</html>n'
response_header = [('Content-type','text/html')]
start_response(status, response_header)
return [html]
I’m a little confused as to how to receive a request and send back json with my excel parser class? Thanks and I hope I’m being clear. I do have a flask server that works, but I do not know how to have it constantly running to serve my endpoint:
app = Flask(__name__)
@app.route(‘/parser/direct_energy’, methods=[‘GET’])
def get_data():
return jsonify(commissions_data)
if name == ‘main‘:
app.run(host=’0.0.0.0’)
4
Answers
UPDATE
I got things working throug NGinx, flask, and GUnicorn. However, my flask app is only working when I go to '/'. If I go to a route such as /parser/de/v1 I get a 404 Not Found.
Here is my setup for NGinx:
You don’t want to use raw WSGI for this.
Use a package such as FastAPI (or Flask) to make everything easier for you.
For instance, using FastAPI, an app with an endpoint to receive a binary (Excel) file and return a JSON response is approximately
See:
I use
python/flask
for development &gunicorn
for production.To get it to accept HTTP requests, I use function decorators. Its the most common way.
So here, the url
/epp/api/v1.0/request
acceptsPOST
ed JSON and returns JSONWhen you run
flask
in dev mode it listens onhttp://127.0.0.1:5000
https://github.com/james-stevens/epp-restapi/blob/master/epprest.py
https://github.com/james-stevens/dnsflsk/blob/master/dnsflsk.py
These are both
python/flask
projects of mine. Feel free to copy. They each run multiple instances of the python code in a single container load-balanced bynginx
– pretty neat combination.my
nginx.conf
looks slightly different, partly becuase I am running multiple WSGI instances, then gettingnginx
to load-balance over themBut with this, all the URLs are passed to the python/wsgi