python fastapi get,post,静态资源访问 使用方式

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")
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Python FastAPI 是一个快速(高性能)且易于学习的 Web 框架,它可以与多种消息队列(MQ)进行集成,其中包括 RabbitMQ。 在使用 FastAPI 和 RabbitMQ 进行集成时,你可以使用 Pika 库来连接 RabbitMQ,然后在 FastAPI使用 FastAPI-BackgroundTasks 库来异步处理消息队列中的消息。以下是一个简单的示例: 1. 安装 FastAPI 和 Pika 库: ```python pip install fastapi pip install pika pip install fastapi-background-tasks ``` 2. 在 FastAPI 应用程序中导入相关库: ```python from fastapi import FastAPI, BackgroundTasks import pika ``` 3. 连接 RabbitMQ: ```python connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='my_queue') ``` 4. 编写处理函数,并在函数中使用 `channel.basic_publish()` 方法将消息发布到消息队列中: ```python def process_message(message): # 处理消息的代码 print("Received message:", message) def send_message_to_queue(message): channel.basic_publish(exchange='', routing_key='my_queue', body=message) ``` 5. 在 FastAPI 中定义异步任务: ```python app = FastAPI() @app.post("/send_message") async def send_message(message: str, background_tasks: BackgroundTasks): background_tasks.add_task(send_message_to_queue, message) return {"message": "Message sent successfully!"} @app.on_event("startup") async def startup_event(): connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='my_queue') channel.basic_consume(queue='my_queue', on_message_callback=process_message, auto_ack=True) channel.start_consuming() ``` 6. 启动应用程序: ```python uvicorn main:app --reload ``` 这是一个简单的示例,你可以根据你的需求进行调整和扩展。下面是一些相关问题:

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

图像处理大大大大大牛啊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值