Can Python's string .format() be made safe for untrusted format strings?

后端 未结 2 760
猫巷女王i
猫巷女王i 2021-01-01 13:04

I\'m working on a web app where users will be able to supply strings that the server will then substitute variables into.

Preferably I\'d like to use PEP 3101 format

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-01 13:18

    This simple Formatter override blocks users from accessing attributes. It still allows formatting and conversion of types.

    from string import Formatter
    class SafeFormatter(Formatter):
            def get_field(self, field_name, args, kwargs):
                if '.' in field_name or '[' in field_name:
                    raise Exception('Invalid format string.')
                return super().get_field(field_name,args,kwargs)
    
    form = SafeFormatter()
    fname = form.format(format,num=1,id='hello')
    

提交回复
热议问题