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

PythonAnywhere部署Flask API:POST PDF URL下载报400错误求助

问题排查与解决方案

核心原因:参数格式错误

你在Postman中给url参数的VALUE添加了多余的双引号,导致后端拿到的是带引号的无效URL(例如"https://www.irs.gov/pub/irs-pdf/p15.pdf"),直接传给requests.get()会触发异常,进而引发Flask返回400错误。

快速修复步骤

  1. 移除Postman参数值的引号
    将Postman中url参数的VALUE改为不带引号的原始URL:https://www.irs.gov/pub/irs-pdf/p15.pdf。

  2. 确认参数传递格式
    确保你在Postman中使用form-data或x-www-form-urlencoded格式传递参数——你的代码通过request.values.get('url')只能读取这两种格式的参数。如果习惯用JSON传参,需要修改代码中的参数获取逻辑为request.get_json().get('url')。

代码优化(添加校验与异常处理)

原代码缺乏错误处理逻辑,一旦参数缺失、URL无效或网络异常就会崩溃。以下是增强后的代码:

from flask import Flask, request, abort
import requests
import logging
from urllib.parse import urlparse

app = Flask(__name__)

# 配置日志
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler = logging.FileHandler('log.txt')
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

@app.route('/download', methods=['POST'])
def download_file():
    logger.info("download_file function called")

    # 兼容表单、URL参数和JSON三种传参方式
    pdf_url = request.values.get('url') or (request.get_json().get('url') if request.is_json else None)
    
    # 校验参数是否存在
    if not pdf_url:
        logger.error("No URL parameter provided")
        abort(400, description="Missing 'url' parameter")
    
    # 校验URL格式合法性
    parsed_url = urlparse(pdf_url)
    if not all([parsed_url.scheme, parsed_url.netloc]):
        logger.error(f"Invalid URL format: {pdf_url}")
        abort(400, description="Invalid URL format")

    logger.info(f"Retrieved URL: {pdf_url}")

    try:
        # 下载PDF并添加超时限制,触发HTTP错误状态码异常
        response = requests.get(pdf_url, timeout=10)
        response.raise_for_status()
        logger.info("PDF file downloaded")
    except requests.exceptions.RequestException as e:
        logger.error(f"Failed to download PDF: {str(e)}")
        abort(500, description=f"Failed to download PDF: {str(e)}")

    try:
        # 保存文件(建议使用唯一文件名避免覆盖)
        with open('downloaded_file.pdf', 'wb') as f:
            f.write(response.content)
        logger.info("PDF file saved to working directory")
    except IOError as e:
        logger.error(f"Failed to save PDF: {str(e)}")
        abort(500, description=f"Failed to save PDF: {str(e)}")

    return 'File downloaded and saved successfully!'

后续排查建议

如果问题仍存在,登录PythonAnywhere控制面板查看Flask应用的官方错误日志,里面会显示更详细的错误信息,可直接定位是网络权限问题(比如PythonAnywhere是否允许出站请求到目标URL)还是其他参数异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 00:10:20