将python的后端从烧瓶迁移到龙卷风

发布于 2025-01-22 13:15:19 字数 2906 浏览 2 评论 0原文

我已经在Python-Flask和Python-Pymongo中创建了一个工作的CRUD应用程序,但是现在我需要将后端从烧瓶迁移到龙卷风。龙卷风在线上没有太多最新文档,还要记住我两周前才开始学习Web Dev。我的烧瓶后端看起来像这样:

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)

所以我尝试将其迁移到龙卷风(基于我在线可以找到的东西)就是这样:

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"
              

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

丢了幸福的猪 2025-01-29 13:15:19

解决了邮政请求的功能:

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

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!'})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文