1. get访问,有参方式和无参方式
from fastapi import FastAPI
from fastapi import Query
import uvicorn as uvicorn
import json
app = FastAPI()
# 前端无参数访问 http://127.0.0.1/no
@app.get('/no')
async def no():
return "res"
#方式一
# 前端带参访问实列 http://127.0.0.1/now?info={"ip":"127.0.0.1"}
@app.get('/now')
async def now(info:str):
info = json.loads(info)
print(info["ip"])
return "res"
# 方式二
# 前端带参访问实列 http://127.0.0.1/now?info={"ip":"127.0.0.1"}
@app.get('/now')
async def now(info=Query(None)): # 如果不带参 则为None
info = json.loads(info)
print(info["ip"])
return "res"
if __name__ == '__main__':
uvicorn.run(app =app, host = '0.0.0.0', port=80)
2. post访问,上传为json数据
前端js
//第一种
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://127.0.0.1/imgpath');
xhr.setRequestHeader("Content-type", "application/json");
xhr.send(JSON.stringify({"item":{"key" : "关键字"}}));
xhr.onreadystatechange = function() {
console.log(xhr.readyState);
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
// 行 头 空行 体
console.log(xhr.status); //状态码
console.log(xhr.statusText); //状态字符串
console.log(xhr.getAllResponseHeaders()); //所有响应头
console.log(xhr.response); //响应体
}
}
}
// 第二种
function login() {
var username = document.querySelector('.username').value
var password = document.querySelector('.password').value
console.log(username, password)
// post
var xhr = new XMLHttpRequest()
xhr.open('POST', '/login')
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
console.log(xhr.responseText)
var data = JSON.parse(xhr.responseText)
if (data.code === 0) {
alert('登录成功')
window.location.href = 'static/project.html?username=' + username
} else {
alert('用户名或密码错误')
}
}
}
xhr.send(JSON.stringify({
username: username,
password: password
}))
}
python代码
from fastapi import FastAPI,Body
import uvicorn as uvicorn
from pydantic import BaseModel
app = FastAPI()
# 第一种
class Item(BaseModel):
key: str
@app.post('/imgpath')
async def index(item: Item = Body(..., embed=True)):
print(item.key)
return item.key
# 第二种
@app.post('/login')
async def login(username=Body(None), password=Body(None)):
# 查询数据库
c.execute("SELECT * FROM USER WHERE NAME=? AND PASSWORD=?", (username, password))
# 获取查询结果
result = c.fetchone()
# 判断是否存在
if result:
return {"code": 0, "msg": "登录成功"}
else:
return {"code": 1, "msg": "用户名或密码错误"}
if __name__ == '__main__':
uvicorn.run(app =app, host = '0.0.0.0', port=80)
3. 访问静态资源(可使用nginx)
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
import uvicorn as uvicorn
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
# 按钮按下接口
@app.get('/', response_class=HTMLResponse)
async def index():
with open("index.html", "rb") as f: # 打开文件
data = f.read() # 读取文件
return data
if __name__ == '__main__':
uvicorn.run(app =app, host = '0.0.0.0', port=80)
4. 异步数据库
pip install databases[aiosqlite]
数据库连接的建立与断开
#!/usr/bin/ python
# -*- encoding: utf-8 -*-
'''
@文件 :main.py
@说明 :
@时间 :2022/07/03 13:08:07
@作者 :刘子沫
@邮箱 :spiritai@qq.com
@版本 :1.0
'''
from fastapi import FastAPI,Body
import uvicorn as uvicorn
from databases import Database
app = FastAPI()
database = Database('sqlite+aiosqlite:///gp.db?min_size=5&max_size=20')
@app.on_event("startup")
async def startup():
await database.connect()
@app.on_event("shutdown")
async def shutdown():
await database.disconnect()
# 账号
@app.post('/api/login')
async def login(username=Body(None), password=Body(None)):
query = "SELECT * FROM user WHERE username = %s AND password = %s"%(username, password)
result = await database.fetch_one(query=query)
if result:
return {"code": 0, "msg": "success"}
else:
return {"code": 1, "msg": "用户名或密码错误"}
if __name__ == '__main__':
uvicorn.run(app =app, host = '0.0.0.0', port=8000)
5.异步aiohttp
import json
import aiohttp
# 异步http请求
session = aiohttp.ClientSession()
async def getdata(url):
# async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
return json.loads(await resp.text(), encoding="utf-8")