日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

fastapi 传输文件存文件_python3 FastAPI框架入门 基本使用, 模版渲染, 数据交互,cookie使用, 上传文件, 静态文件配置...

發(fā)布時間:2023/12/10 python 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 fastapi 传输文件存文件_python3 FastAPI框架入门 基本使用, 模版渲染, 数据交互,cookie使用, 上传文件, 静态文件配置... 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

[FastAPI框架入門 基本使用, 模版渲染, form表單數(shù)據(jù)交互, 上傳文件, 靜態(tài)文件配置]

安裝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 #默認模板設(shè)置

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

Title

hellokugou

login.html

Username

Password

fastapi本身是沒有模版渲染功能的,需要你借助于第三方的模版工具

該框架默認情況下也是借助于jinja2來做模版渲染(flask也是使用jinja2, 如果用過flask, 默認是裝過jinja2)

form表單數(shù)據(jù)交互&& cookie創(chuàng)建與使用#!/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")

project_list = [{'id':1,'project': 'sk_platform_furniture'},

{'id':21,'project': 'sk_service_data_process'}]

env_list = [{'id':2,'env':'sit'},{'id':3,'env':'uat'}]

@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':

obj = templates.TemplateResponse('index2.html', {'request': request, 'username': username})

obj.set_cookie("dabaojian","nidongde",max_age=888)

return obj

#return templates.TemplateResponse('index2.html', {'request': request, 'username': username})

else:

return {'status':'failed','username':username , 'password': password}

@app.get("/")

async def main(request: Request):

tk = request.cookies.get('dabaojian')

print(tk, '---------------')

if not tk:

print('websocket@@@@@@@@@@@@@@env')

return templates.TemplateResponse('login.html', {'request': request})

else:

return templates.TemplateResponse('index2.html', {'request': request})

@app.get("/websocket/")

async def read_project(request: Request):

tk = request.cookies.get('dabaojian')

print(tk,'---------------')

if not tk:

print( 'websocket@@@@@@@@@@@@@@env')

return templates.TemplateResponse('login.html', {'request': request})

else:

print({"success----------------------------------"})

return templates.TemplateResponse('websocket_show2.html', {'request': request,'project_list':project_list,'env_list':env_list})

@app.post("/show_websocket/")

async def show_project(request: Request,projectname1: str = Form(...), envname1: str = Form(...)):

print(projectname1,envname1,'######################show_websocket')

tk = request.cookies.get('dabaojian')

print(tk,'---------------')

if not tk:

print( 'shwo_logs@@@@@@@@@@@@@@env')

return templates.TemplateResponse('login.html', {'request': request})

else:

logs_an = {projectname1:envname1}

print({"success----------------------------------"})

return templates.TemplateResponse('websocket_show2.html', {'request': request,'logs_an':logs_an,'project_list':project_list,'env_list':env_list})

if __name__ == '__main__':

import uvicorn

uvicorn.run(app, host='192.168.120.26', port=8886)index2.html

Title

hellokugou

websocket

show_websocket2.html

Title

show websocket

項目名:

請選擇項目

{% for row in project_list %}

{{ row.project }}

{% endfor %}

環(huán) 境 :

請選擇環(huán)境

{% for row in env_list %}

{{ row.env }}

{% endfor %}

home

{{logs_an}}

不用亂點,其他功能都沒加------------懶

注意: 如果要使用request.form()支持表單“解析”,則為必需 python-multipart 。

index

上傳文件from starlette.requests import Request

from fastapi import FastAPI, Form, File, UploadFile

from starlette.templating import Jinja2Templates

from typing import List

from starlette.staticfiles import StaticFiles

app = FastAPI()

# 掛載模板文件夾

tmp = Jinja2Templates(directory='C:\\Users\\xxxx\\PycharmProjects\\FastAPI-kelan\\venv1')

app.mount("/static", StaticFiles(directory="C:\\Users\\xxxx\\PycharmProjects\\FastAPI-kelan\\venv1\\static"), name="static")

@app.get('/') # 接受get請求

async def get_file(request: Request):

return tmp.TemplateResponse('file.html', {'request': request})

# 單個文件

@app.post('/one/')

async def get_user(request: Request,

file: bytes = File(...), # # 把文件對象轉(zhuǎn)為bytes類型,這種類型的文件無法保存

file_obj: UploadFile = File(...), # UploadFile轉(zhuǎn)為文件對象,可以保存文件到本地

info: str = Form(...) # 獲取普通鍵值對

):

# 保存上傳的文件

contents = await file_obj.read()

with open("/static/file/" + file_obj.filename, "wb") as f:

f.write(contents)

return tmp.TemplateResponse('upload.html', {

'request': request,

'file_size': len(file),

'file_name': file_obj.filename,

'info':info,

'file_content_type':file_obj.content_type

})

# 多個文件

@app.post('/more/')

async def get_files(request:Request,

files_list:List[bytes] = File(...), # [使用二進制數(shù)據(jù)]

files_obj_list:List[UploadFile]=File(...) # [file_obj1,file_obj2,....] #可以同時上傳多個文件

):

# 保存上傳的多個文件

for file in files_obj_list:

contents = await file.read()

filename = file.filename

with open("static/file/" + filename, "wb") as f:

f.write(contents)

return tmp.TemplateResponse('upload.html',

{'request':request,

'file_sizes':[len(file) for file in files_list],

'file_names':[file_obj.filename for file_obj in files_obj_list]

}

)

if __name__ == '__main__':

import uvicorn

uvicorn.run(app, host='192.168.120.26', port=8886)upload.html

Title

單個文件

{{ file_size }}

{{ file_name }}

{{ info }}

{{ file_content_type }}

多個文件

{{ file_sizes }}

{{ file_names }}

file.html

Title

單個文件

多個文件

{# multiple參數(shù)支持一次性傳多個文件 #}

上傳文件-顯示

注意 file 目錄需要提前創(chuàng)建

靜態(tài)文件配置

1.使用 HTMLResponse 在python代碼中體現(xiàn)html@app.get("/logs/{Jenvironment}/{project}")

def read_project_logs(project: str,Jenvironment: str):

print(project, '#######################project')

print(Jenvironment, '@@@@@@@@@@@@@@env')

#print(ansible_project_websocket_port(project,Jenvironment),"$$$ansible_project_websocket_port-LIst")

html_content = """

config-center

{tansiblestr}

""".format(tansiblestr=ansible_project_logs(project,Jenvironment))

return HTMLResponse(content=html_content, status_code=200)

2.需要安裝aiofiles模塊from starlette.staticfiles import StaticFiles

app = FastAPI()

app.mount("/static", StaticFiles(directory="C:\\Users\\xxxx\\PycharmProjects\\FastAPI-kelan\\venv1\\static"), name="static")StaticFiles

layout.html

{% block css %}{% endblock %}

SEAN-Config_Center

個人資料

注銷

消息

郵箱

列表

添加

生成

工具

  • Home
  • Library
  • Data
  • {% block xx %}{% endblock %}

    {% block js %}{% endblock %}

    當 staic目錄設(shè)置之后,基本就和django 一樣使用 bootstrap等等了。

    總結(jié)

    以上是生活随笔為你收集整理的fastapi 传输文件存文件_python3 FastAPI框架入门 基本使用, 模版渲染, 数据交互,cookie使用, 上传文件, 静态文件配置...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。