Flask URL短链网站:HTML表单输入赋值Python变量失败求助
Flask URL短链网站表单传值故障排查与修复
我正在开发一个基于Flask的URL短链网站,此前硬编码long_url变量时能正常生成测试短链,但改成从HTML表单获取输入后,点击缩短按钮就返回“Error”。我尝试在app.py中添加getvalue函数获取表单值,但问题依然存在。希望了解如何正确将HTML表单输入赋值给Python变量,以下是我的代码文件:
app.py
from flask import Flask, render_template, request import subprocess app = Flask(__name__) @app.route('/') def index(): return render_template('index.html', long_url='long_url') @app.route('/') def getvalue(): long_url = request.form['long_url'] return long_url @app.route('/run-script', methods=['GET', 'POST']) def run_script(): script_path = 'URL Shortener.py' if request.method == 'POST': try: result = subprocess.check_output(['python', script_path], stderr=subprocess.PIPE, text=True) return result except subprocess.CalledProcessError as e: return str(e.stderr) return "Invalid request method" if __name__ == '__main__': app.run(host="0.0.0.0", port=80)
URL Shortener.py
import requests url = 'http://tinurl.com/api-create.php?url=' # 注:实际应为tinyurl,Stack Overflow判定链接恶意无法正常显示 long_url = 'long_url' response = requests.get(url+long_url) short_url = response.text print(short_url)
index.html
<!DOCTYPE html> <html lang="en"> <head> <title>URL Shortener</title> </head> <body> <h1>URL Shortener - Project</h1> <h2>Hello, welcome to my URL shortener. Check it out and make use of it as and when you need to. Thanks for checking it out!</h2> <label for="long_url">Enter Long URL Here:</label> <form method="post" action="{{ url_for('run_script') }}"> <input type="text" id="long_url" name="long_url"> <!-- Added name attribute to the input field --> <button type="submit">Shorten URL</button> </form> <p></p> </body> </html>
问题分析与修复方案
核心问题点
- 路由冲突:app.py中两个
@app.route('/')路由重复,Flask只会加载第一个index函数,getvalue函数完全不会被触发,表单数据根本没被获取。 - 未传递表单数据:
run_script调用子脚本时,没有把表单里的long_url传递过去,子脚本依然使用硬编码的无效值请求API,必然返回错误。 - API地址拼写错误:子脚本里的API地址写的是
tinurl,实际应为tinyurl,这也是请求失败的直接原因之一。
修复步骤
1. 重构app.py的路由与逻辑
删除重复路由,直接在run_script中获取表单数据并传递给子脚本:
from flask import Flask, render_template, request import subprocess app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/run-script', methods=['GET', 'POST']) def run_script(): script_path = 'URL Shortener.py' if request.method == 'POST': # 安全获取表单输入,避免键不存在抛出异常 long_url = request.form.get('long_url', '').strip() if not long_url: return "请输入有效的长链接" try: # 将长链接作为命令行参数传递给子脚本 result = subprocess.check_output( ['python', script_path, long_url], stderr=subprocess.PIPE, text=True ) return f"生成成功:{result.strip()}" except subprocess.CalledProcessError as e: return f"生成失败:{str(e.stderr.strip())}" return "无效请求方式" if __name__ == '__main__': app.run(host="0.0.0.0", port=80)
2. 修改子脚本接收命令行参数
让URL Shortener.py从命令行获取传递的长链接,替换硬编码值:
import requests import sys # 修正API地址为正确的tinyurl url = 'http://tinyurl.com/api-create.php?url=' # 校验命令行参数是否存在 if len(sys.argv) < 2: print("缺少长链接参数") sys.exit(1) long_url = sys.argv[1] response = requests.get(url + long_url) short_url = response.text print(short_url)
3. 优化前端页面(可选)
将页面改为中文,并添加结果展示区域:
<!DOCTYPE html> <html lang="zh-CN"> <head> <title>URL短链生成器</title> </head> <body> <h1>URL短链生成器</h1> <h2>欢迎使用我的URL短链工具,有需要就用起来吧!感谢你的支持!</h2> <label for="long_url">输入长链接:</label> <form method="post" action="{{ url_for('run_script') }}"> <input type="text" id="long_url" name="long_url" placeholder="例如:https://www.example.com" required> <button type="submit">生成短链接</button> </form> <!-- 展示生成结果 --> <div style="margin-top: 20px;"> {% if request.method == 'POST' %} <p>{{ response }}</p> {% endif %} </div> </body> </html>
内容的提问来源于stack exchange,提问作者Billy Fuller
相关产品推荐
相关产品推荐

