赞
踩
Quart 是一个基于 Python 的异步 Web 框架,灵感来自 Flask。它结合了 Flask 的易用性和成熟度,并添加了对 Python 异步特性的支持。使用Quart你可以:
Quart 旨在提供一个类似于 Flask 的简单且灵活的 Web 框架,同时支持 Python 的异步功能(async 和 await)。这使得 Quart 能够处理高并发和异步 I/O 操作,适用于需要处理大量并发连接的应用程序,如实时 Web 应用和微服务。
安装: python的版本必须大于3.8。
pip install quart
pip install python
from quart import Quart, render_template, websocket app = Quart(__name__) @app.route("/") async def hello(): return await render_template("index.html") @app.route("/api") async def json(): return {"hello": "world"} @app.websocket("/ws") async def ws(): while True: await websocket.send("hello") await websocket.send_json({"hello": "world"}) if __name__ == "__main__": app.run()
Quart 允许你定义异步路由处理函数,使得处理异步 I/O 操作更加高效。
@app.route('/async')
async def async_route():
# 异步操作
await asyncio.sleep(1)
return 'This is an async route'
Quart 内置对 WebSockets 的支持,可以轻松处理实时通信。
from quart import websocket
@app.route('/ws')
async def ws():
while True:
message = await websocket.receive()
await websocket.send(f'You said: {message}')
Quart 支持中间件,可以在请求处理之前或之后执行一些操作。
@app.before_request
async def before_request():
print("This runs before each request")
@app.after_request
async def after_request(response):
print("This runs after each request")
return response
Quart 支持蓝图,用于模块化应用程序的路由和视图。
from quart import Blueprint
bp = Blueprint('example', __name__)
@bp.route('/example')
async def example():
return 'This is an example route'
app.register_blueprint(bp, url_prefix='/bp')
安装:
pip install uvicorn
运行: 在项目根目录下运行以下命令,这里 app:app 表示在 app.py 文件中有一个名为 app 的 Quart 应用实例。
uvicorn app:app
安装:
pip install hypercorn
部署: 指定端口和启用自动重载
hypercorn app:app --bind 0.0.0.0:8000 --reload
概述:这段代码创建了一个基于 Quart 框架的异步 Web 应用程序,暴露了一个 POST 接口 /aiops。该接口接收 JSON 请求,提取其中的 prompt 字段,并调用 run_query 函数处理这个 prompt。主要功能如下:
from quart import Quart, request, jsonify from querySLSLog import run_query from loguru import logger import logging from querySLSLog import run_query app = Quart(__name__) logger.add('app.log') app.logger.disabled = True werkzeug_logger = logging.getLogger('werkzeug') werkzeug_logger.disabled = True @app.route('/aiops', methods=['POST']) async def run_code(): data = await request.json prompt = data.get('prompt') if not prompt: logger.error(f"提取prompt失败: {request.data.decode('utf-8')}") return jsonify({'error': 'No prompt provided'}), 400 logger.info(f"prompt: {prompt}") try: result = await run_query(prompt) logger.info(f"result: {result}") result = result.content return jsonify(result) except Exception as e: error = f"调用run_query方法失败: {e}" logger.error(error) return jsonify(error) if __name__ == '__main__': app.run(host='0.0.0.0', port=6789)
参考文章:
Quart 是一个强大且灵活的异步 Web 框架,适用于需要高并发和异步 I/O 操作的应用程序。它结合了 Flask 的简单性和 Python 异步特性的优势,是开发现代 Web 应用和微服务的一个有力工具。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。