[FastAPI框架入门 基本使用, 模版渲染, form表单数据交互, 上传文件, 静态文件配置]
安装pip3 install fastapi [all]
pip3 install unicorn
pip3 install aiofiles
pip3 install HTMLResponse
pip3 install Response
pip3 install shapely
pip3 install starlette
pip3 install requests
pip3 install orjson # json 解析
pip3 install jinja2 #默认模板设置
pip3 install python-multipart #表单支持
基本使用(不能同时支持,get, post方法等要分开写)@app.get('/') # 点get就支持get请求
def read_root():
return {"hello":'world'}
模版渲染#!/usr/bin/python
# -*- coding:utf-8 -*-
import subprocess
import urllib.request
import platform
import socket,requests
import os, sys, json, datetime, time
import urllib.request
from fastapi.responses import HTMLResponse
from starlette.requests import Request
from starlette.responses import Response
from fastapi import FastAPI, Form
from fastapi import Cookie
from starlette.templating import Jinja2Templates
from starlette.staticfiles import StaticFiles
app = FastAPI()
templates = Jinja2Templates(directory="C:\\Users\\xxxx\\PycharmProjects\\FastAPI-kelan\\venv1")
@app.post("/user/")
async def create_cookie(request: Request, username: str = Form(...), password: str = Form(...)):
print('username',username)
print('password',password)
if username=='admin' and password=='admin':
return templates.TemplateResponse('index2.html', {'request': request, 'username': username})
else:
return {'status':'failed','username':username , 'password': password}
@app.get("/")
async def main(request: Request):
return templates.TemplateResponse('login.html', {'request': request})
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host='192.168.120.26', port=8886)index2.html
Titlehellokugou
login.html
Username
Password
fastapi本身是没有模版渲染功能的,需要你借助于第三方的模版工具
该框架默认情况下也是借助于jinja2来做模版渲染(flask也是使用jinja2, 如果用过flask, 默认是装过jinja2)
form表单数据交互&