Python模块导入机制与FastAPI
声明:本文章使用AI辅助完成
两个程序
branch.py
def function():
return "来自函数function"
def main():
function()
print("这是一个测试!")
return
if __name__ == '__main__':
main()
main.py
from branch import function
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
@app.get("/")
async def call_function():
show = function()
# 在 FastAPI 中,路由函数(如 call_function)的返回值会被自动转换为 JSON 格式并返回给客户端
return {'message':show}
|问| 这是什么写法?我在main.py里调用了function函数,branch.py里main函数里的打印会在main.py运行的时候一起被调用吗?|
|答| 不会,branch.py 里的 main() 函数不会被自动调用,因此 print("这是一个测试!") 也不会执行。
① 为什么 print 不会执行?
这都归功于 Python 中 if name == 'main': 这行神奇的代码。
当你直接运行 branch.py 时
Python 解释器会把 branch.py 当作主程序来执行。此时,name 变量的值就是 'main'。因此,if 条件成立,main() 函数会被执行,你就能在控制台看到打印信息。
当你在 main.py 中 from branch import function 时
Python 解释器会把 branch.py 当作一个模块来导入。此时,name 变量的值是模块的名字,也就是 'branch'。if 条件 if 'branch' == 'main': 不成立,所以 main() 函数里的代码就被跳过了。
这种写法是一种非常优秀的编程习惯,它的作用是防止模块在被导入时执行测试代码或启动脚本。它确保了 branch.py 既可以作为一个独立脚本运行,也可以作为一个模块被其他程序安全地调用。
② 这种写法有一个好处:当运行本程序时通过在main函数里写测试可以判断此程序是否有bug,测试完成其他程序里直接调用主要函数function即可。比如我在毕设中有一个main.py文件,其调用了一个数据预处理的程序
from fastapi import FastAPI, File, UploadFile
from data_preprocessor import preprocess
app = FastAPI()
@app.post("/preprocess/")
async def preprocess_endpoint(file: UploadFile = File(...)):
try:
print(f"[DEBUG] Received file: {file.filename}")
contents = await file.read()
df = reprocess(contents)
print(f"[DEBUG] DataFrame shape before preprocessing: {df.shape}")
# preprocess 是同步函数,不需要 await
processed_df = preprocess(df)
print(f"[DEBUG] DataFrame shape after preprocessing: {processed_df.shape}")
output = io.BytesIO()
processed_df.to_csv(output, index=False, encoding='utf-8-sig')
output.seek(0)
return StreamingResponse(
output,
media_type="text/csv",
headers={
"Content-Disposition": f"attachment; filename={file.filename.replace('.csv', '_preprocessed.csv')}"}
)
except Exception as e:
error_msg = traceback.format_exc()
logging.error(error_msg)
print(error_msg)
return JSONResponse(
status_code=500,
content={"message": f"Preprocessing failed: {str(e)}", "details": error_msg}
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)
当main文件代码多起来后,debug也更困难。在data_preprocessor.py里写好preprocess和main函数,测试完成后再运行主文件,可以有效提高开发效率
浙公网安备 33010602011771号