【发布时间】:2021-05-03 01:10:51
【问题描述】:
我用 FastAPI 构建了一个 API,然后我想通过 PHP 调用它(我通过 Docker 运行 PHP,将端口 80 公开到 80),但它总是给出布尔值(False)。 然而,这个 API 与 JavaScript、Postman、Firefox 配合得很好。(我想把这个 API 的结果提供给外部用户,所以我的理想是使用 PHP 把这个 API 的结果提供给前端,我不这样做'不知道如何将这个 API 直接从 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,但没有改变。
提前谢谢你!
【问题讨论】:
-
运行 PHP 时是否收到错误消息?您在 FastAPI 中收到任何错误消息吗?您是否在日志文件中写入任何内容以查看您得到了什么?你甚至可以使用 Flask 来构建前端。或纯 HTML 与 JavaScript(直接或与即反应,Vue)。据我所知,暴露端口用于从外部访问 PHP,而不是从 PHP 外部访问。而且我不确定docker是否使用
localhost作为IP。它可能使用子网172.17.0.0/16 -
谢谢@furas,根据您的建议,我找到了解决方案。 docker 容器上的 PHP 无法访问主机端口。
标签: python php api rest fastapi