从 CherryPy 中的 HTML 表单读取输入

Reading input from an HTML form in CherryPy

我希望将 HTML 表单中的值读入 CherryPy 端点:

class MyWebService(object):

    def generate_random_string(length = 6):
        letters = string.ascii_lowercase
        print("length: " + str(length))
        result_str = ''.join(random.sample(letters, k = length))
        print("Random String is:", result_str)
        return result_str

    @cherrypy.expose
    def index(self):
        return """<form method="POST" action="randomize">
          <input type="text" name="the_link" size="50"/>
          <button type="submit">Randomize!</button>
        </form>"""

    @cherrypy.expose
    def randomize(self, the_link):
        random_string = self.generate_random_string()
        log_statement = link + " converted to: " + random_string
        return log_statement

if __name__ == '__main__':
    config = {'server.socket_host': '0.0.0.0'}
    cherrypy.config.update(config)
    cherrypy.quickstart(MyWebService())
    cherrypy.quickstart(MyWebService(), '/', config)

当我 运行 代码并转到 localhost:8080 并输入 the_link 的值时,我看到此错误:

File "app.py", line 25, in generate_random_string
    result_str = ''.join(random.sample(letters, k = length))
  File "/opt/anaconda3/lib/python3.8/random.py", line 362, in sample
    if not 0 <= k <= n:
TypeError: '<=' not supported between instances of 'int' and 'MyWebService'File "app.py", line 25, in generate_random_string
    result_str = ''.join(random.sample(letters, k = length))
  File "/opt/anaconda3/lib/python3.8/random.py", line 362, in sample
    if not 0 <= k <= n:
TypeError: '<=' not supported between instances of 'int' and 'MyWebService'

我不明白为什么 nMyWebService 类型。你能指出为什么吗? generate_random_string() 函数在此源文件之外按预期工作。

定义generate_random_string时应提供add参数。当您调用实例方法时。实例本身总是作为第一个参数传递。

class MyWebService(object):

def generate_random_string(self, length = 6):
    letters = string.ascii_lowercase
    print("length: " + str(length))
    result_str = ''.join(random.sample(letters, k = length))
    print("Random String is:", result_str)
    return result_str

您应该使用此代码从表单中获取信息:

cherrypy.request.params.get('the_link')

所以你的随机函数应该是这样的:

@cherrypy.expose
def randomize(self, *args,**kwargs):
    self.string=cherrypy.request.params.get('the_link')
    random_string = self.generate_random_string()
    log_statement = self.string + " converted to: " + random_string
    return log_statement

你的 generate_random_string 函数应该是这样的:

def generate_random_string(self,length=6):
    letters = self.string.lower()
    print("length: " + str(length))
    print(letters)
    result_str = ''.join(random.sample(letters, k=length))
    print("Random String is:", result_str)
    return result_str