我正在学习 Python,我正在尝试托管一个简单的 Flask 应用程序,该应用程序在 Vercel 中显示当前温度(从开源 API 获取)。
我能够在 Visual Studio 代码中在 127.0.0.1:5000 运行该应用程序,但是当我将其部署到 Vercel 时,我收到一条错误消息。
我的应用程序具有以下结构:
app.py
weather_controller.py
requirements.txt
vercel.json
templates/home.html
这是app.py文件中的代码
import requests
import weather_controller
from flask import Flask, render_template
app = Flask(__name__, template_folder='templates')
@app.route('/', methods=['GET'])
def home():
temperature = weather_controller.print_current_temperature()
return render_template('home.html', temperature=temperature)
@app.route('/contact', methods=['GET'])
def contact():
return "Contact page"
if __name__ == "__main__":
app.run()
这是vercel.json中的代码
{
"builds": [
{
"src":"app.py",
"use":"@vercel/python"
}
],
"routes": [
{
"src":"/(.*)",
"dest":"app.py"
}
]
}
这是weather_controller.py
import requests
url = r"https://api.open-meteo.com/v1/forecast"
params = {
"latitude": 42.69,
"longitude": 23.32,
"current": "temperature_2m,wind_speed_10m",
}
response = requests.get(url, params=params)
responseJSON = response.json()
def print_current_temperature():
return f'The current temperature is {str(responseJSON['current']['temperature_2m'])}'
我注意到,如果我在开始时删除weather_controller位(例如导入weather_controller),部署就会起作用。即使只是导入weather_controller也会破坏vercel部署。
预先感谢您的帮助!
您正在weather_controller.py中的模块级别进行API调用。这意味着模块一导入就会发出 HTTP 请求,这对于可能冷启动的无服务器功能来说并不理想。相反,您应该在
print_current_temperature
函数中进行 API 调用,因此它是在访问路由时执行的,而不是在初始化无服务器函数时执行的。
尝试一下这个更新版本:
import requests
def print_current_temperature():
url = "https://api.open-meteo.com/v1/forecast"
params = {
"latitude": 42.69,
"longitude": 23.32,
"current_weather": True
}
try:
response = requests.get(url, params=params)
response.raise_for_status() # This will raise an exception for HTTP errors
responseJSON = response.json()
temperature = responseJSON['current_weather']['temperature']
return f'The current temperature is {temperature}'
except requests.RequestException as e:
return str(e)
我不确定这是否是确切的问题,但如果它仍然没有运行,您应该考虑检查扩展的 vercel 日志,看看是否有有关该错误的更多详细信息。
考虑按如下方式更新您的文件,以便更好地处理错误。
app.py:
from flask import Flask, render_template
import weather_controller
app = Flask(__name__, template_folder='templates')
@app.route('/', methods=['GET'])
def home():
try:
temperature = weather_controller.get_current_temperature()
return render_template('home.html', temperature=temperature)
except Exception as e:
# You should probably log this error
# For example: app.logger.error(f"Failed to get temperature: {e}")
return f"An error occurred: {e}", 500
@app.route('/contact', methods=['GET'])
def contact():
return "Contact page"
if __name__ == "__main__":
app.run()