I've already created a working CRUD app with the backend done in Python-Flask and Python-PyMongo, but now I need to migrate the backend from Flask to Tornado. There isn't very much up to date documentation online for Tornado, and bear in mind also that I just started learning web dev two weeks ago. My Flask backend looks like this:
from flask import Flask, request, jsonify
from flask_pymongo import PyMongo, ObjectId
from flask_cors import CORS
app = Flask(__name__)
app.config["MONGO_URI"]="mongodb srv://<user>:<pass>@cluster0.f0zvq.mongodb.net/myFirstDatabase?retryWrites=true&w=majority"
mongo = PyMongo(app)
CORS(app)
db = mongo.db.users
#GET and POST responses
@app.route('/users', methods=['GET', 'POST'])
def createUser():
if request.method == "GET":
users = []
for doc in db.find():
users.append({
'_id': str(ObjectId(doc['_id'])),
'username': doc['username'],
'firstName': doc['firstName'],
'lastName': doc['lastName'],
'dob': doc['dob']
})
return jsonify(users)
elif request.method == "POST":
id = db.insert_one({
'username': request.json['username'],
'firstName': request.json['firstName'],
'lastName': request.json['lastName'],
'dob': request.json['dob']
})
return jsonify({'id': str(id.inserted_id), 'msg': 'User Added Successfully!'})
{...}
if __name__ == "__main__":
app.run(debug=True)
So my attempt at migrating it to Tornado (based on what I could find online) is something like this:
import tornado.ioloop
import tornado.web
import urllib.parse
from bson.json_util import dumps
from bson import ObjectId
from pymongo import MongoClient
cluster = MongoClient("mongodb srv://<user>:<pass>@cluster0.vsuex.mongodb.net/myFirstDatabase?retryWrites=true&w=majority")
db = cluster["test"]
collection = db["test"]
class UserHandler(tornado.web.RequestHandler):
#This one is working
def get(self):
users = []
for doc in collection.find():
users.append({
'_id': str(doc['_id']),
'username': doc['username'],
'firstName': doc['firstName'],
'lastName': doc['lastName'],
'dob': doc['dob']
})
self.write(json.dumps(users))
def post(self):
body = urllib.parse.urlparse(self.request.body)
for key in body:
#having trouble at this line
body[key] = body[key][0]
id = collection.insert_one({
"username": body["username"],
"firstName": body["firstName"],
"lastName": body["lastName"],
"dob": body["dob"]
})
self.write(dumps({'id': str(id.inserted_id), 'msg': 'User Added Successfully!'}))
{...}
def make_app():
return tornado.web.Application([
(r"/users", UserHandler)
],
debug = True,
autoreload = True)
if __name__ == "__main__":
app = make_app()
port = 8888
app.listen(port)
print(f"