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 FastAPIapp = 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 CORSMiddlewareapp = 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是空但是還是被使用了