季布, 2023-08-25 18:18 采纳率: 35.1%
浏览 17
已结题

flask使用async await处理异步任务


class generatePs(Resource):
    async def post(self):
        data1 = request.get_data()
        data = json.loads(data1)
        uuid = data.get('uuid')
        current_id = data.get('current_id')
        tasks = []
        try:
            mt_obj = Outline.query.filter(Outline.uuid == uuid,
                                          Outline.current_name == current_id).first()

            task = asyncio.create_task(mt_deal(mt_obj))
            tasks.append(task)
            #
            task = asyncio.create_task(ib_deal(mt_obj))
            tasks.append(task)

            task = asyncio.create_task(ea_deal(mt_obj))
            tasks.append(task)

            task = asyncio.create_task(rp_deal(mt_obj))
            tasks.append(task)

            task = asyncio.create_task(generateAb(mt_obj))
            tasks.append(task)

            await asyncio.wait(tasks,timeout=None)

            return {'code': 200, 'message': 'success'}
        except Exception as e:
            return {'code': 400, 'message': str(e)}

async def ib_deal(obj):
    ibcontent_experience = eval(obj.ib)['ibexperience']
    ibcontent = eval(obj.ib)['ibcontent']
    iblinear = eval(obj.ib)['iblinear']
    linear_content = "You are encouraged to use a non-linear narrative to make your story focus on highlighting the skills and lessons of %s learned from the whole career and how they have shaped your growth." % ibcontent
    prompt = ""
    for experience in ibcontent_experience:
        if experience['label'] == '1':
                prompt += "As a student, please use following materials to write a within 200 words statement of your work experience. To make your statement compelling, use ornate and embellished language. Begin your statement with a simple sentence or phrase that declares your motivation for your professional involvements. There is a specific important rule you must follow: DO NOT mention the name of positions more than once in the statement. \n For the %s, you should not just simply follow the above material but expand with more details including providing the following information autonomously: Your responsibilities; The challenges you faced and how you overcame them; Methodologies you adapted to complete your duties; What you learned and gained in terms of skill and knowledge." % experience.get(
                    "content", "")
        else:
                prompt += "As a student, please use following materials to write a within 200 words statement of your work experience. To make your statement compelling, use ornate and embellished language. Begin your statement with a simple sentence or phrase that declares your motivation for your professional involvements. There is a specific important rule you must follow: DO NOT mention the name of positions more than once in the statement. \n For the %s, write in a sense of paraphrase and reorganize the above materials in the way of STAR" % experience.get(
                    "content", "")
        if iblinear == '1':
            prompt += linear_content
        dataload = {'prompt': prompt}
        ib_result = await requests.post(openai_url, json=dataload, headers=headers)
        obj.ibgpt = ib_result.text
        db.session.commit()

运行报错

    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type coroutine is not JSON serializable

  • 写回答

1条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2023-08-25 23:56
    关注

    【以下回答由 GPT 生成】

    优化后的代码如下所示:

    from flask import Flask, request, jsonify
    from flask_restful import Resource, Api
    import asyncio
    import json
    
    app = Flask(__name__)
    api = Api(app)
    
    
    class GeneratePs(Resource):
        async def post(self):
            data = json.loads(request.get_data())
            uuid = data.get('uuid')
            current_id = data.get('current_id')
            tasks = []
            try:
                mt_obj = Outline.query.filter(Outline.uuid == uuid, Outline.current_name == current_id).first()
    
                tasks.append(mt_deal(mt_obj))
                tasks.append(ib_deal(mt_obj))
                tasks.append(ea_deal(mt_obj))
                tasks.append(rp_deal(mt_obj))
                tasks.append(generateAb(mt_obj))
    
                await asyncio.gather(*tasks)
    
                return {'code': 200, 'message': 'success'}
            except Exception as e:
                return {'code': 400, 'message': str(e)}
    
    
    async def mt_deal(obj):
        # Perform some async tasks related to mt_obj
        # ...
    
    
    async def ib_deal(obj):
        # Perform some async tasks related to ib_obj
        # ...
    
    
    async def ea_deal(obj):
        # Perform some async tasks related to ea_obj
        # ...
    
    
    async def rp_deal(obj):
        # Perform some async tasks related to rp_obj
        # ...
    
    
    async def generateAb(obj):
        # Perform some async tasks related to generateAb_obj
        # ...
    
    
    api.add_resource(GeneratePs, '/generate_ps')
    
    if __name__ == '__main__':
        app.run()
    

    解释:

    1. 创建GeneratePs类继承自Resource类,用于处理POST请求。
    2. post方法中,首先解析请求中的数据,然后创建一个空的任务列表tasks
    3. 通过查询数据库获取mt_obj对象。
    4. 将每个异步任务添加到任务列表中,使用append方法。这里假设mt_dealib_dealea_dealrp_dealgenerateAb函数都是异步的。
    5. 使用asyncio.gather方法来并发地运行所有异步任务,并等待它们全部完成。
    6. 如果出现异常,捕获并返回错误信息。
    7. 如果没有异常,返回成功的响应。
    8. 创建每个异步任务的函数mt_dealib_dealea_dealrp_dealgenerateAb,根据需要执行与任务相关的异步操作。

    这样,我们通过使用asyncawait关键字,以及asyncio库中的方法,可以在Flask中处理异步任务。


    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 8月29日
  • 修改了问题 8月25日
  • 修改了问题 8月25日
  • 修改了问题 8月25日
  • 展开全部

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来