FastAPI学习(⼆)——FastAPI+Jinjia2模板渲染⽹页(跳转返回渲染页⾯)⽂章⽬录
通过前⾯的学习,现在我们来看看如何渲染⽹页,别总是⼀串原始字母。
官⽅⽂档位置:
(B站学习⽹址)
⼀、简单实现
⾸先,必须注意的是,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
quests import Request
from starlette.staticfiles import StaticFiles
plating import Jinja2Templates
app = FastAPI()
# 创建⼀个templates(模板)对象,以后可以重⽤。
templates = Jinja2Templates(directory="templates")
# Request在路径操作中声明⼀个参数,该参数将返回模板。
# 使⽤templates您创建的渲染并返回TemplateResponse,并request在Jinja2“上下⽂” 中将⽤作键值对之⼀。@("/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、浏览器输⼊
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="cdn.jsdelivr/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg 32OmUcww7on3RYdg4Va+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 con tent. 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 mas sa 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, tort
or mauris condimentum nibh, ut fermentum mas
sa 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, t ellus 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="leapis/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="cdn.jsdelivr/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mC WNIpG9mGCD8wGNIcPD7Txa"crossorigin="anonymous"></script>
</body>
</html>
3、main.py代码:
from fastapi import FastAPI
import uvicorn as u
quests import Request
from starlette.staticfiles import StaticFiles
plating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@("/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、浏览器输⼊
127.0.0.1:8080/items/super888888

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。