我用FastAPI构建了一个应用程序接口,然后我想通过PHP调用它(我通过Docker运行PHP,公开端口80到80),但它总是给出布尔值(False)。但是这个接口在JavaScript,Postman,firefox.(我想把这个接口的结果给外部用户,所以我的理想是用PHP把这个接口的结果带到前端,我不知道如何从FastAPI直接给外部用户这个接口)。所以你可以在下面看到我的FastAPI代码:
from fastapi import FastAPI #import class FastAPI() from library fastapi
from pydantic import BaseModel
import main_user
import user_database
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI() #constructor and app
origins = [
"http://localhost",
"http://localhost:80",
"https://localhost",
"https://localhost:80"
]
app.add_middleware(
CORSMiddleware,
allow_origins=['*'],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class InfosCalculIndice(BaseModel):
nomTuile:str
dateAcquisition:str
heureAcquisition:str
nomIndice:str
lonMin: float
lonMax: float
latMin: float
latMax: float
interp: str
imgFormat: str
class InfosLogin(BaseModel):
username: str
password: str
class InfosTuile(BaseModel):
tuile:str
@app.post("/calcul-indice")
async def calcul_indice(infos: InfosCalculIndice):
img = main_user.calcul_api(infos.nomTuile, infos.dateAcquisition,infos.nomIndice,infos.lonMin,
infos.lonMax,infos.latMin,infos.latMax,infos.interp, infos.imgFormat)
return {"img":img}
@app.post("/login")
async def login(infos: InfosLogin):
status = user_database.login(infos.username, infos.password)
return {"stt":status}
@app.post("/register")
async def register(infos: InfosLogin):
stt = user_database.createUser(infos.username, infos.password)
return {"stt":stt}
@app.get("/get-tuile")
async def getTuile():
tuiles = user_database.getAllTuiles()
return tuiles
下面是PHP代码:
<?php
$url = 'http://localhost/login'; #OR http://127.0.0.1:800/login
$data = array("username" => "myusernam", "password"=>"mypassword");
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_PORT, 8000); #OR without this option
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // For HTTPS
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // For HTTPS
curl_setopt($curl, CURLOPT_HTTPHEADER, [
'Content-Type: application/json', 'server:uvicorn'
]);
$response = curl_exec($curl);
echo $response;
var_dump($response);
curl_close($curl);
?>
我也尝试过file_get_contents
,但没有改变。
提前谢谢你!
发布于 2021-05-03 18:00:47
我刚刚找到了解决方案,docker上的php上的curl不能从ip为127.0.0.1的主机调用api。我使用命令ip addr show docker0
,然后获取内部网地址,而不是本地主机,它起作用了。
https://stackoverflow.com/questions/67362462
复制相似问题