将 HTML 表单的输入分配为变量

问题描述 投票:0回答:1

我正在尝试编写一个 URL 缩短网站,但遇到了一个问题,在尝试缩短 URL 时出现“错误”。当我的 URL Shortener.py 上的“long_url”变量中有一个链接时,它可以工作并给出一个测试 URL,但是当我尝试更改它以从 HTML 表单获取输入时,它已停止工作。有谁知道如何将 HTML 表单的输入正确分配给 python 变量。我会附上我的文件。

应用程序.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缩短器.py

import requests

url = 'http://tinurl.com/api-create.php?url=' <-- This is meant to say tinyurl but stack overflow will not allow me to post it with the link as it thinks it is malicious.

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 中的 long_url 变量编辑为示例 long_url,该示例给出了示例 Short_url,但它不会根据输入框中的输入而改变,因为 long_url 已经确定。我还尝试了 def getvalue(): 可以在 app.py 中看到,但这也不起作用。任何建议都会很棒!

python html flask
1个回答
0
投票

您需要从表单中获取长 URL 并将其作为参数传递给脚本。

@app.route('/run-script', methods=['GET', 'POST'])
def run_script():
    script_path = 'URL Shortener.py'

    if request.method == 'POST':
        try:
            long_url = request.form['long_url']
            result = subprocess.check_output(['python', script_path, long_url], stderr=subprocess.PIPE, text=True)
            return result
        except subprocess.CalledProcessError as e:
            return str(e.stderr)
    return "Invalid request method"

那么 URLShortener.py 就是:

import sys
import requests

url = 'http://tinurl.com/api-create.php?url='

if len(sys.argv) < 2:
    print( "Must provide the long URL as a parameter." )
    exit(0)

long_url = sys.argv[1]
response = requests.get(url+long_url)
short_url = response.text

print(short_url)
© www.soinside.com 2019 - 2024. All rights reserved.