清理/验证 Kivy 设置用户输入
Sanitize / Validate Kivy Settings User Input
如果你使用Kivy提供的ConfigParser/Settings并添加你自己在json中定义的设置,那么你只有两种安全的设置:"type":"options" 和 "type":"bool"。原因是,其他类型会给用户一个文本输入小部件,他们可以在其中输入他们喜欢的任何内容。例如。 import os; os.system("rm -r ~")
。但是,给定的设置可能有许多不同的值(实际上我正在处理一个设置,它有许多不同的可能值)。所以我不能使用仅有的两种安全类型,因为它会烧屏。
所以我在 github 上深入研究了 ConfigParser 和设置 classes 并且我找到了 config.add_callback
。您可以在 build
方法中访问您的配置对象,所以我进入该方法并添加了 self.config.add_callback(self.validate_settings_input)
。您添加的回调函数将获得 on_config_change
获得的所有参数,第一个参数 (config
) 除外。所以我将我的验证码添加到 self.validate_settings_input
。如果用户输入无效,我想覆盖它,所以我添加了 self.config.set('MySection', 'MyKey', override_value)
和 config.write()
。但这不起作用,或者至少它不像我期望的那样起作用:
对于以下描述,请注意存在一个 class 属性,它被设置为设置的值(接线在 on_config_change
中)。如果单击该设置,将弹出带有文本输入的弹出窗口。如果您输入有效值并按确定提交,则设置会更改(在配置文件、设置-GUI 和 programm/class 中)。但是,如果您输入了一个无效值,则设置也会更改(在配置文件中,在设置-GUI 中,但不在 programm/class 中)。如果您随后关闭应用程序并再次启动它,则设置将更改为有效值,如 self.validate_settings_input 中所定义。
因此,我的验证正确完成的唯一情况是 on_start()
。虽然使用 add_callback
添加到 ConfigParser
的回调应该在每次 config.set()
被调用时被调用。在不知道的情况下,我假设 config.set()
即使用户通过 GUI 更改设置也会被调用。如果不是,这一切有什么意义?
Googleing "Kivy input validation" 只得到一个 Whosebug 问题,没有答案。这个问题也是关于普通文本输入小部件的。但是,我关心的文本输入小部件是某些设置 class 的内部对象。
您对如何sanitize/validate用户输入设置有什么建议吗?
示例代码
###############################################################################
# Version
###############################################################################
__version__ = '0.1'
###############################################################################
# Imports
###############################################################################
# Python build-in Modules
from functools import partial # schedule callback functions that take arguments different from 'dt'
# Kivy
from kivy.lang.builder import Builder
from kivy.app import App
from kivy.core.window import Window
from kivy.utils import platform
from kivy.uix.screenmanager import Screen
from kivy.properties import ObjectProperty, NumericProperty, StringProperty
from kivy.uix.settings import SettingsWithTabbedPanel
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.clock import Clock
from kivy.uix.label import Label
from kivy.logger import Logger
###############################################################################
# Constants
###############################################################################
BACKGROUND_COLOR = [0,0,0,0]
TEXT_COLOR = [1,1,1,1]
JSON_MATH = '''
[
{
"type": "string",
"title": "Operator (free choice)",
"desc": "Choose the operator. + (addition). - (subtraction). * (multiplication). : (division). % (modulo). You can also choose any combination of those operations to create your own mix.",
"section": "Math",
"key": "operator"
},
{
"type": "options",
"title": "Operator (options)",
"desc": "Choose the operator. + (addition). - (subtraction). * (multiplication). : (division). % (modulo). You can also choose from three mixes.",
"options": ["+", "-", "*", ":", "%", "+-", "*:", "+-*:"],
"section": "Math",
"key": "operator_"
}
]
'''
kv_string = """
<MySettingsRoot>:
orientation: 'vertical'
Label:
text: '[b] My Settings App [/b]'
markup: True
Button:
text: 'Settings'
on_release: app.open_settings()
Button:
text: 'Quit'
on_release: app.stop()
"""
###############################################################################
# Widgets
###############################################################################
###############################################################################
# Root Widget
###############################################################################
class MySettingsRoot(BoxLayout):
""" See kv string
"""
def __init__(self, *args, **kwargs):
super(MySettingsRoot, self).__init__(*args, **kwargs)
def changeScreen(self, next_screen):
pass
def onBackBtnPress(self):
pass
###############################################################################
# App Object
###############################################################################
class MySettingsApp(App):
""" App object
"""
def __init__(self, *args, **kwargs):
super(MySettingsApp, self).__init__(*args, **kwargs)
#self.use_kivy_settings = False
self.settings_cls = SettingsWithTabbedPanel
def build(self):
Builder.load_string(kv_string)
self.config.add_callback(self.config_input_validation)
return MySettingsRoot()
def build_config(self, config):
config.setdefaults('Math', {'operator': '+-:%', 'operator_': '*'})
def build_settings(self, settings):
settings.add_json_panel('Math', self.config, data=JSON_MATH)
def config_input_validation(self, section, key, value, *args):
""" Callback function, which is bound to the same event as on_config_change.
It is supposed to validate the value that a user sets some setting to.
It is being called, but config.set and config.write just don't work.
However, if the app is restartet, all settings that are not valid, are
changed to valid values. This is realy wired!
"""
if section == 'Math':
if key == 'operator':
if set(["+", "-", "*", ":", "%"]).union([str(v) for v in value]) != set(["+", "-", "*", ":", "%"]):
Logger.info('App: This choice is forbidden. Returning to default.')
self.config.set('Math', 'operator', '*')
self.config.write()
# Also tried combinations of the following lines:
#Clock.schedule_once(partial(self.config.set, 'Math', 'diffclty', value)) # -> set-method misses *args, so dt cannot be catched
#self.config.write()
#Clock.schedule_once(self.close_settings)
#Clock.schedule_once(partial(self.on_config_change, self.config, 'Math', 'diffclty', value))
#Clock.schedule_once(self.open_settings, 1)
if key == 'operator_':
pass
def on_config_change(self, config, section, key, value, *args):
if section == 'Math':
if key == 'operator':
Logger.info('App: Your operators via free choice: %s' %value)
#self.root.calculation_screen.operation = ''.join([str(MathBackEnd.operator_strings.index(p)) for p in list(value)])
if key == 'operator_':
Logger.info('App: Your operators via options: %s' %value)
if __name__ in ('__main__', '__android__'):
MySettingsApp().run()
想法是继承 Settings
和 SettingString
,它们都在 kivy API 中找到用于设置。在 SettingString
的子类中,定义一个包含验证的方法 _validate
。用户输入将保存在 self.textinput.text
中,有效值应保存在 self.value
中,而 non-valid 值只是结束进程(或引发异常)。在 Settings
的子类中注册一个新类型并将其设置为 SettingString
的子类。在为设置定义数据时,此类型将在 json 文件中使用。
# Kivy
from kivy.app import App
from kivy.lang.builder import Builder
from kivy.uix.settings import Settings
from kivy.uix.settings import SettingString
from kivy.uix.settings import InterfaceWithNoMenu
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.logger import Logger
JSON_MATH = '''
[
{
"type": "complex_operator_string",
"title": "Operator (free choice)",
"desc": "Choose the operator. + (addition). - (subtraction). * (multiplication). : (division). % (modulo). You can also choose any combination of those operations to create your own mix.",
"section": "Math",
"key": "operator"
},
{
"type": "options",
"title": "Operator (options)",
"desc": "Choose the operator. + (addition). - (subtraction). * (multiplication). : (division). % (modulo). You can also choose from three mixes.",
"options": ["+", "-", "*", ":", "%", "+-", "*:", "+-*:"],
"section": "Math",
"key": "operator_"
}
]
'''
kv_string = """
<MySettingsRoot>:
orientation: 'vertical'
Label:
text: '[b] My Settings App [/b]'
markup: True
Button:
text: 'Settings'
on_release: app.open_settings()
Button:
text: 'Quit'
on_release: app.stop()
<ValidatedSettings>:
interface_cls: 'ValidatedSettingsInterface'
"""
###############################################################################
# Widgets
###############################################################################
class ValidatedSettingsInterface(InterfaceWithNoMenu):
pass
class ValidatedSettings(Settings):
def __init__(self, **kwargs):
super(ValidatedSettings, self).__init__(**kwargs)
self.register_type('complex_operator_string', OperatorSetting)
def add_kivy_panel(self):
pass
class OperatorSetting(SettingString):
def __init__(self, **kwargs):
super(OperatorSetting, self).__init__(**kwargs)
def _validate(self, instance):
self._dismiss() # closes the popup
try:
assert set(["+", "-", "*", ":", "%"]).union([str(v) for v in self.textinput.text]) == set(["+", "-", "*", ":", "%"])
self.value = self.textinput.text
Logger.info('App: Assertion is true, setting value to textinput')
except AssertionError:
Logger.info('App: This choice is forbidden.')
return
###############################################################################
# Root Widget
###############################################################################
class MySettingsRoot(BoxLayout):
""" See kv string
"""
def __init__(self, *args, **kwargs):
super(MySettingsRoot, self).__init__(*args, **kwargs)
###############################################################################
# App Object
###############################################################################
class MySettingsApp(App):
""" App object
"""
def __init__(self, *args, **kwargs):
super(MySettingsApp, self).__init__(*args, **kwargs)
self.settings_cls = ValidatedSettings
def build(self):
Builder.load_string(kv_string)
return MySettingsRoot()
def build_config(self, config):
config.setdefaults('Math', {'operator': '+-:%', 'operator_': '*'})
def build_settings(self, settings):
settings.add_json_panel('Math', self.config, data=JSON_MATH)
def on_config_change(self, config, section, key, value, *args):
if section == 'Math':
if key == 'operator':
Logger.info('App: Your operators via free choice: %s' %value)
if key == 'operator_':
Logger.info('App: Your operators via options: %s' %value)
if __name__ in ('__main__', '__android__'):
MySettingsApp().run()
如果你使用Kivy提供的ConfigParser/Settings并添加你自己在json中定义的设置,那么你只有两种安全的设置:"type":"options" 和 "type":"bool"。原因是,其他类型会给用户一个文本输入小部件,他们可以在其中输入他们喜欢的任何内容。例如。 import os; os.system("rm -r ~")
。但是,给定的设置可能有许多不同的值(实际上我正在处理一个设置,它有许多不同的可能值)。所以我不能使用仅有的两种安全类型,因为它会烧屏。
所以我在 github 上深入研究了 ConfigParser 和设置 classes 并且我找到了 config.add_callback
。您可以在 build
方法中访问您的配置对象,所以我进入该方法并添加了 self.config.add_callback(self.validate_settings_input)
。您添加的回调函数将获得 on_config_change
获得的所有参数,第一个参数 (config
) 除外。所以我将我的验证码添加到 self.validate_settings_input
。如果用户输入无效,我想覆盖它,所以我添加了 self.config.set('MySection', 'MyKey', override_value)
和 config.write()
。但这不起作用,或者至少它不像我期望的那样起作用:
对于以下描述,请注意存在一个 class 属性,它被设置为设置的值(接线在 on_config_change
中)。如果单击该设置,将弹出带有文本输入的弹出窗口。如果您输入有效值并按确定提交,则设置会更改(在配置文件、设置-GUI 和 programm/class 中)。但是,如果您输入了一个无效值,则设置也会更改(在配置文件中,在设置-GUI 中,但不在 programm/class 中)。如果您随后关闭应用程序并再次启动它,则设置将更改为有效值,如 self.validate_settings_input 中所定义。
因此,我的验证正确完成的唯一情况是 on_start()
。虽然使用 add_callback
添加到 ConfigParser
的回调应该在每次 config.set()
被调用时被调用。在不知道的情况下,我假设 config.set()
即使用户通过 GUI 更改设置也会被调用。如果不是,这一切有什么意义?
Googleing "Kivy input validation" 只得到一个 Whosebug 问题,没有答案。这个问题也是关于普通文本输入小部件的。但是,我关心的文本输入小部件是某些设置 class 的内部对象。
您对如何sanitize/validate用户输入设置有什么建议吗?
示例代码
###############################################################################
# Version
###############################################################################
__version__ = '0.1'
###############################################################################
# Imports
###############################################################################
# Python build-in Modules
from functools import partial # schedule callback functions that take arguments different from 'dt'
# Kivy
from kivy.lang.builder import Builder
from kivy.app import App
from kivy.core.window import Window
from kivy.utils import platform
from kivy.uix.screenmanager import Screen
from kivy.properties import ObjectProperty, NumericProperty, StringProperty
from kivy.uix.settings import SettingsWithTabbedPanel
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.clock import Clock
from kivy.uix.label import Label
from kivy.logger import Logger
###############################################################################
# Constants
###############################################################################
BACKGROUND_COLOR = [0,0,0,0]
TEXT_COLOR = [1,1,1,1]
JSON_MATH = '''
[
{
"type": "string",
"title": "Operator (free choice)",
"desc": "Choose the operator. + (addition). - (subtraction). * (multiplication). : (division). % (modulo). You can also choose any combination of those operations to create your own mix.",
"section": "Math",
"key": "operator"
},
{
"type": "options",
"title": "Operator (options)",
"desc": "Choose the operator. + (addition). - (subtraction). * (multiplication). : (division). % (modulo). You can also choose from three mixes.",
"options": ["+", "-", "*", ":", "%", "+-", "*:", "+-*:"],
"section": "Math",
"key": "operator_"
}
]
'''
kv_string = """
<MySettingsRoot>:
orientation: 'vertical'
Label:
text: '[b] My Settings App [/b]'
markup: True
Button:
text: 'Settings'
on_release: app.open_settings()
Button:
text: 'Quit'
on_release: app.stop()
"""
###############################################################################
# Widgets
###############################################################################
###############################################################################
# Root Widget
###############################################################################
class MySettingsRoot(BoxLayout):
""" See kv string
"""
def __init__(self, *args, **kwargs):
super(MySettingsRoot, self).__init__(*args, **kwargs)
def changeScreen(self, next_screen):
pass
def onBackBtnPress(self):
pass
###############################################################################
# App Object
###############################################################################
class MySettingsApp(App):
""" App object
"""
def __init__(self, *args, **kwargs):
super(MySettingsApp, self).__init__(*args, **kwargs)
#self.use_kivy_settings = False
self.settings_cls = SettingsWithTabbedPanel
def build(self):
Builder.load_string(kv_string)
self.config.add_callback(self.config_input_validation)
return MySettingsRoot()
def build_config(self, config):
config.setdefaults('Math', {'operator': '+-:%', 'operator_': '*'})
def build_settings(self, settings):
settings.add_json_panel('Math', self.config, data=JSON_MATH)
def config_input_validation(self, section, key, value, *args):
""" Callback function, which is bound to the same event as on_config_change.
It is supposed to validate the value that a user sets some setting to.
It is being called, but config.set and config.write just don't work.
However, if the app is restartet, all settings that are not valid, are
changed to valid values. This is realy wired!
"""
if section == 'Math':
if key == 'operator':
if set(["+", "-", "*", ":", "%"]).union([str(v) for v in value]) != set(["+", "-", "*", ":", "%"]):
Logger.info('App: This choice is forbidden. Returning to default.')
self.config.set('Math', 'operator', '*')
self.config.write()
# Also tried combinations of the following lines:
#Clock.schedule_once(partial(self.config.set, 'Math', 'diffclty', value)) # -> set-method misses *args, so dt cannot be catched
#self.config.write()
#Clock.schedule_once(self.close_settings)
#Clock.schedule_once(partial(self.on_config_change, self.config, 'Math', 'diffclty', value))
#Clock.schedule_once(self.open_settings, 1)
if key == 'operator_':
pass
def on_config_change(self, config, section, key, value, *args):
if section == 'Math':
if key == 'operator':
Logger.info('App: Your operators via free choice: %s' %value)
#self.root.calculation_screen.operation = ''.join([str(MathBackEnd.operator_strings.index(p)) for p in list(value)])
if key == 'operator_':
Logger.info('App: Your operators via options: %s' %value)
if __name__ in ('__main__', '__android__'):
MySettingsApp().run()
想法是继承 Settings
和 SettingString
,它们都在 kivy API 中找到用于设置。在 SettingString
的子类中,定义一个包含验证的方法 _validate
。用户输入将保存在 self.textinput.text
中,有效值应保存在 self.value
中,而 non-valid 值只是结束进程(或引发异常)。在 Settings
的子类中注册一个新类型并将其设置为 SettingString
的子类。在为设置定义数据时,此类型将在 json 文件中使用。
# Kivy
from kivy.app import App
from kivy.lang.builder import Builder
from kivy.uix.settings import Settings
from kivy.uix.settings import SettingString
from kivy.uix.settings import InterfaceWithNoMenu
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.logger import Logger
JSON_MATH = '''
[
{
"type": "complex_operator_string",
"title": "Operator (free choice)",
"desc": "Choose the operator. + (addition). - (subtraction). * (multiplication). : (division). % (modulo). You can also choose any combination of those operations to create your own mix.",
"section": "Math",
"key": "operator"
},
{
"type": "options",
"title": "Operator (options)",
"desc": "Choose the operator. + (addition). - (subtraction). * (multiplication). : (division). % (modulo). You can also choose from three mixes.",
"options": ["+", "-", "*", ":", "%", "+-", "*:", "+-*:"],
"section": "Math",
"key": "operator_"
}
]
'''
kv_string = """
<MySettingsRoot>:
orientation: 'vertical'
Label:
text: '[b] My Settings App [/b]'
markup: True
Button:
text: 'Settings'
on_release: app.open_settings()
Button:
text: 'Quit'
on_release: app.stop()
<ValidatedSettings>:
interface_cls: 'ValidatedSettingsInterface'
"""
###############################################################################
# Widgets
###############################################################################
class ValidatedSettingsInterface(InterfaceWithNoMenu):
pass
class ValidatedSettings(Settings):
def __init__(self, **kwargs):
super(ValidatedSettings, self).__init__(**kwargs)
self.register_type('complex_operator_string', OperatorSetting)
def add_kivy_panel(self):
pass
class OperatorSetting(SettingString):
def __init__(self, **kwargs):
super(OperatorSetting, self).__init__(**kwargs)
def _validate(self, instance):
self._dismiss() # closes the popup
try:
assert set(["+", "-", "*", ":", "%"]).union([str(v) for v in self.textinput.text]) == set(["+", "-", "*", ":", "%"])
self.value = self.textinput.text
Logger.info('App: Assertion is true, setting value to textinput')
except AssertionError:
Logger.info('App: This choice is forbidden.')
return
###############################################################################
# Root Widget
###############################################################################
class MySettingsRoot(BoxLayout):
""" See kv string
"""
def __init__(self, *args, **kwargs):
super(MySettingsRoot, self).__init__(*args, **kwargs)
###############################################################################
# App Object
###############################################################################
class MySettingsApp(App):
""" App object
"""
def __init__(self, *args, **kwargs):
super(MySettingsApp, self).__init__(*args, **kwargs)
self.settings_cls = ValidatedSettings
def build(self):
Builder.load_string(kv_string)
return MySettingsRoot()
def build_config(self, config):
config.setdefaults('Math', {'operator': '+-:%', 'operator_': '*'})
def build_settings(self, settings):
settings.add_json_panel('Math', self.config, data=JSON_MATH)
def on_config_change(self, config, section, key, value, *args):
if section == 'Math':
if key == 'operator':
Logger.info('App: Your operators via free choice: %s' %value)
if key == 'operator_':
Logger.info('App: Your operators via options: %s' %value)
if __name__ in ('__main__', '__android__'):
MySettingsApp().run()