在sanic中使用函数sanic.response创建响应的模块。主要有:
- text
- html
- json
- file
- stream
- file_stream
- redirect
- raw
- empty
其中日常使用比较多的依然是:text、json、html
1、text
from sanic import Sanic
from sanic.response import json, text, html
import sanic.response
app = Sanic('myapp')
@app.get("/")
async def test(request):
return text("hell, sanic!")
if __name__ == "__main__":
app.run(host="127.0.0.1", port=7890)
展示效果:
图片
2、json
from sanic import Sanic
from sanic.response import json, text, html
import sanic.response
app = Sanic('myapp')
@app.get("/")
async def test(request):
return json({"hi": "China!"})
if __name__ == "__main__":
app.run(host="127.0.0.1", port=7890)
展示效果:
图片
3、html
from sanic import Sanic
from sanic.response import json, text, html
import sanic.response
app = Sanic('myapp')
@app.get("/")
async def test(request):
return html("""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>我的主页</title>
</head>
<body>
<h2 style="color: blue">标题</h2>
</body>
</html>
""")
if __name__ == "__main__":
app.run(host="127.0.0.1", port=7890)
展示效果:
图片
4、file
from sanic import Sanic
from sanic import response
app = Sanic('myapp')
@app.get('/')
async def handle_request(request):
return await response.file('20210801.jpg')
if __name__ == "__main__":
app.run(host="127.0.0.1", port=7890)
展示效果:
image.gif
5、redirect
from sanic import Sanic
from sanic import response
app = Sanic('myapp')
@app.route('/home')
def handle_request(request):
return response.text('我的主页')
@app.route('/redirect')
def handle_request(request):
return response.redirect('/home')
if __name__ == "__main__":
app.run(host="127.0.0.1", port=7890)
展示效果:
图片
6、empty: 204 - ****请求成功了,但是没有结果返回**
from sanic import Sanic
from sanic import response
app = Sanic('myapp')
@app.get('/')
async def handle_request(request):
return response.empty()
if __name__ == "__main__":
app.run(host="127.0.0.1", port=7890)
展示效果:
图片
7、修改响应体:
from sanic import Sanic
from sanic import response
app = Sanic('myapp')
@app.route('/json')
def handle_request(request):
return response.json(
{'message': 'Hello world!'},
headers={'X-Served-By': 'sanic', "severVersion": "v1.0.1"},
status=200
)
if __name__ == "__main__":
app.run(host="127.0.0.1", port=7890)
展示效果:
图片