将 Python 后端从 Flask 迁移到 Tornado

Migrating a Python Backend from Flask to Tornado

我已经创建了一个工作的 CRUD 应用程序,后端在 Python-Flask 和 Python-PyMongo 中完成,但现在我需要将后端从 Flask 迁移到 Tornado。没有太多关于 Tornado 的最新在线文档,并且请记住我两周前才开始学习网络开发。我的 Flask 后端看起来像这样:

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)

所以我尝试将它迁移到 Tornado(基于我在网上找到的内容)是这样的:

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()

当我尝试 post 一些数据时,我从 Postman 得到的错误是:

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

感谢任何帮助,谢谢!

解决了 POST 个请求的功能:

    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!'})