首页 > 其他分享 >FastAPI搭建Web服务器

FastAPI搭建Web服务器

时间:2023-11-06 23:55:57浏览次数:53  
标签:Web FastAPI app jpg html images 服务器 data Response

FastAPI搭建Web服务器

1、基于FastAPI之web站点开发

# 第一步:导入模块
from fastapi import FastAPI
# 导入响应报文Response模块
from fastapi import Response
# 导入服务器uvicorn模块
import uvicorn

# 第二步:创建FastAPI对象
app = FastAPI()

# 第三步:通过@app路由装饰器收发数据
# @app.get(参数) : 按照GET方式接受请求数据
# 请求资源的 url路径
@app.get("/index.html")
def main():
    with open('source/html/index.html','rb') as f:
        data = f.read()
    # return 返回响应数据
    # Response(content = data, media_type = 'text/html')
    # 参数1:响应数据
    # 参数2:数据格式
    return Response(content = data, media_type = 'text/html')

# 第四步:运行服务器
# 参数1:框架对象
# 参数2:ip地址
# 参数3:端口号
uvicorn.run(app,host = '127.0.0.1', port = 8000)

运行结果:

image-20231023173420260

2、Web服务器和浏览器的通讯流程

实际上Web服务器和浏览器的通讯流程并不是一次性完成的,这里html代码中也会有访问服务器的代码,比如请求图片资源。

image-20231023173950023

  • 浏览器在访问index.html后,浏览器多次请求了0.jpg、1.jpg等资源

这些jpg的访问都是来自index.html

image-20231023175435275

3、浏览器访问Web服务器的通讯流程

image-20231023175521968

浏览器访问Web服务器的通讯流程

  1. 浏览器 (127.0.0.1/index.html) ==> 向Web服务器请求index.html
  2. Web服务器 (返回index.html) ==> 浏览器
  3. 浏览器解析index.html发现需要0.jpg ==>发送请求给 Web服务器请求0.jpg
  4. Web服务器 收到请求返回0.jpg ==> 浏览器 接受0.jpg

通讯过程能够成功的前提

浏览器发送的0.jpg请求, Web服务器可以做出响应, 也就是代码如下

# 当浏览器发出对图片 0.jpg请求的时候,函数返回相应资源
@app.get('/images/0.jpg')
def get_image():
    with open('source/images/0.jpg', 'rb') as f:
        data = f.read()
    return Response(content=data, media_type='jpg')

4、加载图片资源

那么当html文件中存在多个需要的加载的图片,那么代码要向如下所写的吗?

# 导入FastAPI模块
from fastapi import FastAPI
# 导入响应报文Response模块
from fastapi import Response
# 导入服务器uvicorn模块
import uvicorn

# 创建FastAPI框架对象
app = FastAPI()


@app.get("/images/0.jpg")
def func_01():
    with open("source/images/0.jpg", "rb") as f:
        data = f.read()
        print(data)
    return Response(content=data, media_type="jpg")


@app.get("/images/1.jpg")
def func_02():
    with open("source/images/1.jpg", "rb") as f:
        data = f.read()
    return Response(content=data, media_type="jpg")


@app.get("/images/2.jpg")
def func_03():
    with open("source/images/2.jpg", "rb") as f:
        data = f.read()
    return Response(content=data, media_type="jpg")


@app.get("/images/3.jpg")
def func_04():
    with open("source/images/3.jpg", "rb") as f:
        data = f.read()
    return Response(content=data, media_type="jpg")


@app.get("/images/4.jpg")
def func_05():
    with open("source/images/4.jpg", "rb") as f:
        data = f.read()
    return Response(content=data, media_type="jpg")


@app.get("/images/5.jpg")
def func_06():
    with open("source/images/5.jpg", "rb") as f:
        data = f.read()
    return Response(content=data, media_type="jpg")


@app.get("/images/6.jpg")
def func_07():
    with open("source/images/6.jpg", "rb") as f:
        data = f.read()
    return Response(content=data, media_type="jpg")


@app.get("/gdp.html")
def func_08():
    with open("source/html/gdp.html") as f:
        data = f.read()
    return Response(content=data, media_type="text/source")


@app.get("/index.html")
def main():
    with open("source/html/index.html") as f:
        data = f.read()
    # return 返回响应数据
    # Response(content=data, media_type="text/source"
    # 参数1: 响应数据
    # 参数2: 数据格式
    return Response(content=data, media_type="text/html")


# 运行服务器
# 参数1: 框架对象
# 参数2: IP地址
# 参数3: 端口号
uvicorn.run(app, host="127.0.0.1", port=8000)

对以上代码观察,会发现每一张图片0.jpg、1.jpg、2.jpg就需要一个函数对应, 如果我们需要1000张图片那就需要1000个函数对应, 显然这样做代码的重复太多了。

5、基于Web请求的FastAPI通用装置

# 当请求为 /images/0.jpg时,path ==> 0.jpg
@app.get('/images/{path}')
# 注意这里的参数要设置为{path}
# path:str 指定path为字符串类型的数据
def get_pic(path:str):
    # 这里open()的路径就是 ==> f'source/images/0.jpg'
    with open('source/images/{path}', 'rb') as f:
        data = f.read()
	return Response(content = data, media_type = 'jpg')

  • 同理,申请不同的页面的请求资源时,也可以使用path作为参数传入,而实现代码的复用。

完整代码:

# 导入FastAPI模块
from fastapi import FastAPI
# 导入响应报文Response模块
from fastapi import Response
# 导入服务器uvicorn模块
import uvicorn

# 创建FastAPI框架对象
app = FastAPI()


# 当请求为 /images/0.jpg 时, path ==> 0.jpg
@app.get("/images/{path}")
# 注意这里的参数需要设置为 path
# path : str ==> 指定path为字符串类型的数据
def get_pic(path: str):
    # 这里open()的路径就是 ==> f"source/images/0.jpg"
    with open(f"source/images/{path}", "rb") as f:
        data = f.read()
    # return 返回响应数据
    # Response(content=data, media_type="jpg")
    # 参数1: 响应数据
    # 参数2: 数据格式
    return Response(content=data, media_type="jpg")


@app.get("/{path}")
def get_html(path: str):
    with open(f"source/html/{path}", 'rb') as f:
        data = f.read()
    # return 返回响应数据
    # Response(content=data, media_type="text/source"
    # 参数1: 响应数据
    # 参数2: 数据格式
    return Response(content=data, media_type="text/html")


# 运行服务器
# 参数1: 框架对象
# 参数2: IP地址
# 参数3: 端口号
uvicorn.run(app, host="127.0.0.1", port=8000)

标签:Web,FastAPI,app,jpg,html,images,服务器,data,Response
From: https://www.cnblogs.com/luoluoange/p/17814105.html

相关文章

  • javaweb-- Mybatis参数传递
     Mybatis提供了ParamNameResolver类进行封装 传入多个参数时,mybatis会将参数封装成Map集合map.put("arg0",参数值1)map.put("param1",参数值1)map.put("arg1",参数值2)map.put("param2",参数值2) ......
  • websec / passwd dict / passwd dict / pwd dict / mima
    s 序号项目描述备注11400多万个弱口令密码字典下载https://www.perfcode.com/p/password-dictionary.html该密码字典包含1400多万个密码,包含弱密码、常用密码、短密码等组合,适合暴力猜解使用;该文件来源于Kali系统下的密码字典文件;如果你使用Kali系统,该密码字典......
  • JavaScript--Web API
    DOMDOM(DocumentObjectModel——文档对象模型)是用来呈现以及与任意HTML或XML文档交互的API。DOM是浏览器提供的一套专门用于操作网页内容的功能作用:开发网页内容特效和实现用户交互DOM树DOM节点节点是文档树的组成部分,每一个节点都是一个DOM对象,主要分为......
  • 云服务器相关操作
    当涉及到云服务器的操作时,以下是一些常见的任务和操作:创建云服务器实例:选择云服务提供商(如AWS、Azure、GoogleCloud等),登录到其控制台,按照相关文档和界面指引创建云服务器实例。您需要选择实例类型、操作系统、存储选项和网络配置等。远程连接到云服务器:一旦创建了云服务器......
  • 恒创科技:高效解决香港服务器负载过高的方法
    ​当我们在使用香港服务器时,有时会遇到服务器负载过高的问题。这会导致网站加载速度变慢甚至无法正常使用。为了解决这个问题,我们需要采取一些高效的方法来提升服务器的负载能力。1.考虑对服务器进行升级维护。通过增加硬件资源,如CPU、内存和存储空间等,可以提高服务器的......
  • javaWeb&springMVC
    Servlet1:servlet定义servlet是开发动态web的一门技术,通过servlet实现与用户的动态交互。2:使用方式(1)javaWeb中只需要继承HttpServlet接口,重写其中的doGet和doPost方法即可编写一个servlet;写好servlet程序后需要在web.xml文件中编写映射,相当于将我们缩写的servlet注册到web服务......
  • 08. 并发TCP服务器
    一、并发TCP服务器  我们使用线程的方式实现并发TCP服务器。fromsocketimportsocketfromsocketimportAF_INET,SOCK_STREAM,SOL_SOCKET,SO_REUSEADDRfromtimeimportctimefromthreadingimportThreadHOST="127.0.0.1"PORT=8080ADDRESS=(HOST,PORT......
  • 记一次对某变异webshell的分析
    0x01前言在某活动中捕获到一个变异的webshell(jsp文件格式),如图1.1所示。样本webshell的大致功能是通过加载字节码来执行恶意代码,整个webshell的核心部分逻辑是在字节码中。样本文件下载链接:https://github.com/webraybtl/webshell1图1.1变异webshell样本直接通过冰蝎、哥斯拉、天......
  • 重命名myclipse中web项目名称的过程
    1打开myclipse2最顶层项目上右键,Refactor,新名,3最顶层项目上右键,propterties,MyEclipse,Web,context-root:/新名4替换.css,.js,.jsp中全部的"/旧名/"5修改apache的配置,/etc/httpd/conf/httpd.conf ProxyPass/新名/http://111.111.111.111:8080/新名/ ProxyPas......
  • mac os 编译webrtc 报错screen_capturer_mac.mm:500:5: error: 'CGDisplayStreamStop'
    ../../modules/desktop_capture/mac/screen_capturer_mac.mm:462:11:error:'CGDisplayStreamUpdateGetRects'isonlyavailableonmacOS13.0ornewer[-Werror,-Wunguarded-availability-new]462|CGDisplayStreamUpdateGetRects(updateRef,kC......