【发布时间】:2021-03-05 15:52:57
【问题描述】:
我希望将 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'
我不明白为什么n 的类型是MyWebService。你能指出为什么吗? generate_random_string() 函数在此源文件之外按预期工作。
【问题讨论】:
-
首先给
generate_random_string一个“自我”论点。