从另一个文件输入

时间:2017-06-16 18:03:21

标签: python

我有2个python文件。这是第一个:

class Downloader():

    def __init__(self):

        baseURL = 'https://example.com'

    def getDownloadLink(self):            

        #linkBase = input("Text: ")

        responseBase = requests.get(linkBase).content
        soupBase = BeautifulSoup(responseBase, 'lxml')

第二个python文件:

from flask import Flask
from flask import request
from flask import render_template
from firstFile import Downloader

app = Flask(__name__)

@app.route('/')
def my_form():
    return render_template("form.html")

@app.route('/', methods=['POST'])
def my_form_post():

    linkBase = request.form['text']
    #processed_text = text.upper()

    return Downloader().getDownloadLink()

if __name__ == '__main__':
    app.run()

它给了我错误:

NameError: name 'linkBase' is not defined

是否可以将第一个文件中的linkBase与第二个文件中的linkBase相关联?

2 个答案:

答案 0 :(得分:1)

这里的问题是您正在尝试访问getDownloadLink函数范围内不存在的变量。

一种解决方案是添加linkBase作为参数:

def getDownloadLink(self, linkBase):
    responseBase = requests.get(linkBase).content
    soupBase = BeautifulSoup(responseBase, 'lxml')

然后修改路由以将值发送到函数:

@app.route('/', methods=['POST'])
def my_form_post():
    linkBase = request.form['text']
    return Downloader().getDownloadLink(linkBase)

答案 1 :(得分:0)

修改代码以将值作为参数传递:

class Downloader():

    def __init__(self):

        baseURL = 'https://example.com'

    def getDownloadLink(self, linkBase):            

        #linkBase = input("Text: ")

        responseBase = requests.get(linkBase).content
        soupBase = BeautifulSoup(responseBase, 'lxml')

第二档:

from flask import Flask
from flask import request
from flask import render_template
from firstFile import Downloader

app = Flask(__name__)

@app.route('/')
def my_form():
    return render_template("form.html")

@app.route('/', methods=['POST'])
def my_form_post():

    linkBase = request.form['text']
    #processed_text = text.upper()

    return Downloader().getDownloadLink(linkBase)

if __name__ == '__main__':
    app.run()