文章目录
通过前面的学习,现在我们来看看如何渲染网页,别总是一串原始字母。
官方文档位置:
https://fastapi.tiangolo.com/advanced/templates/
(B站学习网址https://www.bilibili.com/video/av93282315)
一、简单实现
首先,必须注意的是,FastAPI这个Python Web框架并没有带渲染的网页模板引擎,但是也正因为如此,它可以使用任何网页模板。
官方例子是jinjia2 。
1、依赖库安装
pip install jinja2 aiofiles
aiofiles是静态网页需要的包
特别说明的是,Starlette 是一个轻量级 ASGI 框架/工具包,FastAPI一大特色。
然后,
2、建立目录
需要上图箭头目录和文件。注意,其他目录和文件都是我没找到官方这个案例时候,自己尝试拼接jinjia2的弯路。
萌新表示,仔细翻文档是硬道理!!!
然后,
3、item.html文件代码
<html>
<head>
<title>Item Details</title>
<link href="{{ url_for('static', path='/styles.css') }}" rel="stylesheet">
</head>
<body>
<h1>Item ID: {{ id }}</h1>
</body>
</html>
然后,
4、main.py文件代码
from fastapi import FastAPI
import uvicorn as u
from starlette.requests import Request
from starlette.staticfiles import StaticFiles
from starlette.templating import Jinja2Templates
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
# 创建一个templates(模板)对象,以后可以重用。
templates = Jinja2Templates(directory="templates")
# Request在路径操作中声明一个参数,该参数将返回模板。
# 使用templates您创建的渲染并返回TemplateResponse,并request在Jinja2“上下文” 中将用作键值对之一。
@app.get("/items/{id}")
async def read_item(request: Request, id: str):
return templates.TemplateResponse("item.html", {"request": request, "id": id})
if __name__ == '__main__':
u.run(app, host="127.0.0.1", port=8080)
最后跑起来,
5、浏览器输入
http://127.0.0.1:8080/items/888888
h1效果出来咯,剩下的就交给前端的框架啦。。。。
注意:看后台的话,这里没有加CSS样式错误。
二、借用bootstrap模板
1、目录结构与名称:
2、index.html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../../../favicon.ico">
<title>Jumbotron Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Custom styles for this template -->
<link href="../static/jumbotron.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<form class="navbar-form navbar-right">
<div class="form-group">
<input type="text" placeholder="Email" class="form-control">
</div>
<div class="form-group">
<input type="password" placeholder="Password" class="form-control">
</div>
<button type="submit" class="btn btn-success">Sign in</button>
</form>
</div><!--/.navbar-collapse -->
</div>
</nav>
<!-- Main jumbotron for a primary marketing message or call to action -->
<div class="jumbotron">
<div class="container">
<h1>Item ID: {{ id }}</h1>
<h1>Hello, world!</h1>
<p>This is a template for a simple marketing or informational website. It includes a large callout called a jumbotron and three supporting pieces of content. Use it as a starting point to create something more unique.</p>
<p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more »</a></p>
</div>
</div>
<div class="container">
<!-- Example row of columns -->
<div class="row">
<div class="col-md-4">
<h2>Heading</h2>
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
<p><a class="btn btn-default" href="#" role="button">View details »</a></p>
</div>
<div class="col-md-4">
<h2>Heading</h2>
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
<p><a class="btn btn-default" href="#" role="button">View details »</a></p>
</div>
<div class="col-md-4">
<h2>Heading</h2>
<p>Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.</p>
<p><a class="btn btn-default" href="#" role="button">View details »</a></p>
</div>
</div>
<hr>
<footer>
<p>© 2016 Company, Inc.</p>
</footer>
</div> <!-- /container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="../static/jquery.min.js"><\script>')</script>
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</body>
</html>
3、main.py代码:
from fastapi import FastAPI
import uvicorn as u
from starlette.requests import Request
from starlette.staticfiles import StaticFiles
from starlette.templating import Jinja2Templates
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
@app.get("/items/{id}")
async def read_item(request: Request, id: str):
return templates.TemplateResponse("index.html", {"request": request, "id": id})
if __name__ == '__main__':
u.run(app, host="127.0.0.1", port=8080)
4、浏览器输入
http://127.0.0.1:8080/items/super888888
- 1
这里使用在线css和js文件的方式,所以电脑没有联网是看不错效果的。需要本地css和js文件的方式,则按照bootstrap的开发方式即可。
5、总结
可以说,FastAPI在灵活性上非常nice,如果有更棒或者更喜欢的网页模板引擎,即可替换jinja2。由于,使用的是Starlette工具包,所以还有更加丰富的应用与功能,更多帮助,可以前往Starlette小星星(名字好可爱)官网帮助。
https://www.starlette.io/templates/