python - CherryPy 网页表单 : checkboxes produces error when unchecked

标签 python html sqlite null cherrypy

我正在尝试使用 Python 3.5 中的 CherryPy 生成一个简单的 Web 表单(与 sqlite3 数据库进行比较),该表单需要一些不同类型数据的输入。当复选框未选中时,它会产生错误,因为(我假设)没有默认的空值;它要么“开启”,要么不存在。如何更改我的表单,以便它自动将空框设置为“无”? 这是代码(部分):

class startScreen(object):
    @cherrypy.expose
    def index(self):
        return """<form method="post" action="search">
        Job Title:<br>
        <input type="text" name="title"><br>
        Employer name:<br>
        <input type="text" name="employer"><br>
        Minimum Starting Salary:<br>
        <input type="number" name="minsal"><br>
        Contract Hours Per Week:<br>
        <input type="number" name="hpwMin">
        <input type="number" name="hpwMax"><br>
        Start Date:<br>
        <input type="date" name="startDate"><br>
        <!--jobtype drop down menu--!>
        Contract Length (months):<br>
        <input type="number" name="CLMin">
        <input type="number" name="CLMax"><br>
        <!--qualifications list--!>
        <!--key skills list--!>
        Training Offered:<br>
        <input type="checkbox" name="training"><br>
        Expenses covered:<br>
        <input type="checkbox" name="expenses"><br>
        Job benefits:<br>
        <input type="checkbox" name="benefits"><br>
        Number of days annual holiday: <br>
        <input type="number" name="holiday"><br>
        Opportunities abroad:<br>
        <input type="checkbox" name="abroad"><br>
        Date posted: <br>
        <input type="date" name="datePosted"><br>


        <button type="submit">Submit</button>
        </form>

        """
    @cherrypy.expose #needed for every page
    def search(self, title, employer, minsal, hpwMin, hpwMax, startDate, CLMin, CLMax, training, expenses, benefits, holiday, abroad, datePosted):
        search.search.searchDBS(title, employer, minsal, hpwMin, hpwMax, startDate, CLMin, CLMax, training, expenses, benefits, holiday, abroad, datePosted)
        return "done"

这是未选中一个复选框时网页上的输出:

404 Not Found

Missing parameters: training

Traceback (most recent call last):
  File "C:\Users\Anna\AppData\Local\Programs\Python\Python35\lib\site-packages\cherrypy\_cpdispatch.py", line 60, in __call__
    return self.callable(*self.args, **self.kwargs)
TypeError: search() missing 1 required positional argument: 'training'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Anna\AppData\Local\Programs\Python\Python35\lib\site-packages\cherrypy\_cprequest.py", line 670, in respond
    response.body = self.handler()
  File "C:\Users\Anna\AppData\Local\Programs\Python\Python35\lib\site-packages\cherrypy\lib\encoding.py", line 221, in __call__
    self.body = self.oldhandler(*args, **kwargs)
  File "C:\Users\Anna\AppData\Local\Programs\Python\Python35\lib\site-packages\cherrypy\_cpdispatch.py", line 66, in __call__
    raise sys.exc_info()[1]
  File "C:\Users\Anna\AppData\Local\Programs\Python\Python35\lib\site-packages\cherrypy\_cpdispatch.py", line 64, in __call__
    test_callable_spec(self.callable, self.args, self.kwargs)
  File "C:\Users\Anna\AppData\Local\Programs\Python\Python35\lib\site-packages\cherrypy\_cpdispatch.py", line 163, in test_callable_spec
    raise cherrypy.HTTPError(404, message=message)
cherrypy._cperror.HTTPError: (404, 'Missing parameters: training')

最佳答案

这是 html 复选框的常规行为,您可以使用默认参数来处理它:training=None 或使用 kwargs 并查找键。

对于第一个选项,您的公开方法是:

@cherrypy.expose #needed for every page
def search(self, title, employer, minsal, hpwMin, hpwMax,
           startDate,  CLMin, CLMax, expenses,
           benefits, holiday, abroad, datePosted, training=None):
    # "training" will be None, if the checkbox is not set
    # you can verify with something like:
    # if training is None:
    #    ...
    search.search.searchDBS(
       title, employer, minsal, hpwMin, hpwMax,
       startDate, CLMin, CLMax, training, expenses,
       benefits, holiday, abroad, datePosted)
    return "done"

另一个替代方案(从我的角度来看更好,因为这些方法有很多参数,您可以使用 **params 替代方案:

@cherrypy.expose #needed for every page
def search(self, **params):
    fields = ['title', 'employer', 'minsal', 'hpwMin',
              'hpwMax', 'startDate', 'CLMin', 'CLMax',
              'training', 'expenses','benefits', 'holiday',
              'abroad','datePosted']
    # the params.get, will try to get the value if the field
    # and if is not defined, then it will return None
    search.search.searchDBS(*[params.get(f, None) for f in fields])
    # alternative approach without passing specific fields
    #if 'training' not in params: 
    #    params['training'] = None
    #search.search.searchDBS(**params)
    return "done"

关于python - CherryPy 网页表单 : checkboxes produces error when unchecked,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43616845/

相关文章:

python - 如何将字符串解析为 float 或整数?

python - Django 规则重用谓词

python - python中的别名字典,Class vs dict

html - 无法在 css 动画中将文本保留在屏幕上

html - 如何在图像上设置垂直

html - CSS 线性渐变彩虹轮...未显示所有 12 个部分

sqlite - 在 Laravel 迁移中决定唯一、主要或增量

python - 如何在 Python 中从语料库创建词云?

java - Android sqlite jdbc由于只读文件系统而无法连接

ios - Swift - SharkORM 忽略并加密属性