You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PythonAnywhere部署Flask调用TwelveData时出现请求方法不允许错误

问题分析与解决办法

核心问题出在代码层面,主要有两点:

  1. 请求方法不兼容
    你写的Flask路由@app.route('/', methods=['POST'])只接受POST请求,但如果是直接在浏览器里打开链接(浏览器默认用GET方法),或者请求方用了GET方式访问,就会触发Method Not Allowed错误。
    如果需要支持GET(比如测试用),可以把路由的methods改成['GET', 'POST'];如果只需要POST,就确保请求方用POST方法发送数据。

  2. 代码缩进错误
    Python是靠缩进识别代码块的,你代码里if ticker:和else:下面的代码都没有缩进,这会直接导致代码运行报错,哪怕请求方法正确也没法正常工作。修正后的代码块参考如下:

    @app.route('/', methods=['GET', 'POST'])
    def webhook():
        # 兼容GET和POST两种方式获取参数
        if request.method == 'POST':
            body = request.json
            ticker = body.get('queryResult', {}).get('parameters', {}).get('Share')
        else:
            ticker = request.args.get('Share')
            
        if ticker:
            stock_details = get_stock_quote(ticker, api_key)
            stock_price = get_stock_price(ticker, api_key)
            name = stock_details['name']
            response = {'fulfillmentText': f'The price of {name} is {stock_price}'}
        else:
            response = {
                'fulfillmentText': 'No ticker symbol provided.'
            }
        return jsonify(response)
    

关于PythonAnywhere配置的排查

如果代码修正后还是有问题,再检查这两点:

  • 确认WSGI配置文件里的路径正确指向你的Flask应用
  • 确保PythonAnywhere的环境里装了所有依赖包(flask、requests、geopy)

内容的提问来源于stack exchange,提问作者Vyas Lakshminarayanan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 02:33:12