Python中使用starlette.responses.PlainTextResponse()返回纯文本数据的实例
发布时间:2024-01-07 13:14:20
starlette.responses.PlainTextResponse()是Starlette中的一个类,用于返回纯文本数据的HTTP响应。它接受一个字符串参数作为响应体,并返回一个HTTP响应对象。
下面是一个使用starlette.responses.PlainTextResponse()返回纯文本数据的实例,其中包括使用例子:
from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.routing import Route
async def hello(request):
return PlainTextResponse("Hello, World!")
routes = [
Route("/", hello),
]
app = Starlette(routes=routes)
# 启动应用
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="localhost", port=8000)
在上面的例子中,我们使用Starlette创建了一个简单的Web应用。我们定义了一个名为hello的异步函数,它接受一个request对象作为参数,并返回一个PlainTextResponse对象。
响应体中的字符串"Hello, World!"将作为参数传递给PlainTextResponse类的构造函数,生成一个包含该字符串的HTTP响应对象。我们将PlainTextResponse对象作为hello函数的返回值,从而将其作为HTTP响应发送给客户端。
我们将hello函数与根路径"/"进行关联,使得当浏览器访问根路径时,返回的响应将是"Hello, World!"的纯文本数据。
最后,我们使用uvicorn库运行这个应用并监听localhost的8000端口。
要运行上述示例,请确保已经安装了starlette和uvicorn库。可以使用以下命令安装这两个库:
pip install starlette uvicorn
然后,通过运行上述Python文件,应用将在本地启动。在浏览器中访问http://localhost:8000/,应该会看到页面上显示的纯文本"Hello, World!"。
