Python+FastAPI的一些语法与问题解决

发布于:2025-07-02 ⋅ 阅读:(25) ⋅ 点赞:(0)

Q1:result= await dbsession.execute(text(sql_context),params)

如何把result转成key,value的字典列表

A1:

使用SQLAlchemy的mappings()方法获取字典形式的结果集:

result = await db_session.execute(text(sql_context), params)

dict_list = [dict(row) for row in result.mappings()]

Q2:为什么aysnc方法中调用其他async方法时,跳过了调试?

A1:必须加await在被调用的async方法 

@router.post("/hand")

async def start():

    await migration.do_migration()

Q3:fastAPI中如何读取json文件?

A3:

import json

import os

def read_json_file(urlpath:str,key:str):

    filepath=os.path.join(os.environ["project_root"],urlpath)

    with open(filepath) as f:

        data=json.load(f)

        return data.get(key)

Q4:python中如何获取服务端IP和hotsname?

import socket
from fastapi import FastAPI

app = FastAPI()

@app.get("/server-ip")
async def get_server_ip():
    hostname = socket.gethostname()
    server_ip = socket.gethostbyname(hostname)
    return {"server_ip": server_ip}

 

 Q5 vue+fastapi获取客户端ip?

使用nginx反向代理

location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

fastapi获取

fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/api/client-ip")
async def get_client_ip(request: Request):
    real_ip = request.headers.get("X-Real-IP") 
    forwarded_for = request.headers.get("X-Forwarded-For")
    return {
        "ip": real_ip or forwarded_for or request.client.host,
        "headers": dict(request.headers)
    }
 

 或者从vue获取

<template>
  <div>您的IP是: {{ clientIP }}</div>
</template>

<script>
import axios from 'axios'
export default {
  data() {
    return { clientIP: '' }
  },
  async mounted() {
    const res = await axios.get('/api/client-ip')
    this.clientIP = res.data.ip
  }
}
</script>

Q6 data.sort("seq",1) 报错TypeError: sort() takes no positional arguments
A6:

这个错误是因为Python列表的sort()方法在Python 3.x版本中不再接受位置参数,必须使用关键字参数形式调用

data.sort(key=lambda x: x["seq"], reverse=True)  # 降序排序

Q7 TypeError: 'NoneType' object is not iterable

 A7:获取的data是空但是还是被使用了


网站公告

今日签到

点亮在社区的每一天
去签到