简体   繁体   中英

Migrating a Python Backend from Flask to Tornado

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"🌐 Server is listening on port {8888}")
    #start server on current thread
    tornado.ioloop.IOLoop.current().start()

The error I'm getting so far from Postman when I attempt to post some data is:

line 56, in post
body[key] = body[key][0]
TypeError: tuple indices must be integers or slices, not bytes

Any help is appreciated, thanks!

Solved the function for POST requests:

    async def post(self):
        user = tornado.escape.json_decode(self.request.body)
        id = await collection.insert_one({
            "username": user["username"],
            "firstName": user["firstName"],
            "lastName": user["lastName"],
            "dob": user["dob"]
        })
        self.set_header('Content-Type', 'application/json')
        return self.write({'id': str(id.inserted_id), 'msg': 'User Added 
Successfully!'})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM