代码之家  ›  专栏  ›  技术社区  ›  Emeasoba Tochi

python、django、solr、haystack:编辑solr\u build\u schema BaseCommand时出现arg\u parse错误。add\u参数()

  •  0
  • Emeasoba Tochi  · 技术社区  · 6 年前

    请帮助。。。。我正在django网站搜索中尝试使用solr、pysolr和haystack。我已经编辑了haystack build\u solr\u模式脚本以使用BaseCommand。add\u argument(),删除默认选项列表。以下是我使用的版本; Python 3.5.2 Django 1.11.11 solr-7.3.0 django haystack 2.4.0 pysolr 3.7.0

    # encoding: utf-8
    
    from __future__ import absolute_import, division, print_function, unicode_literals
    
    import sys
    from optparse import make_option
    from django.core.exceptions import ImproperlyConfigured
    from django.core.management.base import BaseCommand
    from django.template import Context, loader
    from haystack import constants
    from haystack.backends.solr_backend import SolrSearchBackend
    
    class Command(BaseCommand):
        help = "Generates a Solr schema that reflects the indexes."
    
        def add_arguments(self, parser):
            # positional arguments
            parser.add_argument("-f", "--filename", action="store", type="string", dest="filename",
                    help='If provided, directs output to a file instead of stdout.',),
           # optional positional arguments
           parser.add_argument("-u", "--using", action="store", type="string", dest="using", default=constants.DEFAULT_ALIAS,
                    help='If provided, chooses a connection to work with.')
    
          """
           base_options = (
           make_option("-f", "--filename", action="store", type="string", dest="filename",
                    help='If provided, directs output to a file instead of stdout.'),
           make_option("-u", "--using", action="store", type="string", dest="using", default=constants.DEFAULT_ALIAS,
                    help='If provided, chooses a connection to work with.'),
           )
          option_list = BaseCommand.option_list + base_options
          """
         def  handle(self, **options):
             """Generates a Solr schema that reflects the indexes."""
             using = options.get('using')
             schema_xml = self.build_template(using=using)
    
             if options.get('filename'):
                self.write_file(options.get('filename'), schema_xml)
             else:
                 self.print_stdout(schema_xml)
    
        def build_context(self, using):
            from haystack import connections, connection_router
            backend = connections[using].get_backend()
    
            if not isinstance(backend, SolrSearchBackend):
                raise ImproperlyConfigured("'%s' isn't configured as a SolrEngine)." % backend.connection_alias)
    
            content_field_name, fields = backend.build_schema(connections[using].get_unified_index().all_searchfields())
            return Context({
                'content_field_name': content_field_name,
                'fields': fields,
                'default_operator': constants.DEFAULT_OPERATOR,
                'ID': constants.ID,
                'DJANGO_CT': constants.DJANGO_CT,
                'DJANGO_ID': constants.DJANGO_ID,
            })
    
        def build_template(self, using):
            t = loader.get_template('search_configuration/solr.xml')
            c = self.build_context(using=using)
            return t.render(c)
    
        def print_stdout(self, schema_xml):
            sys.stderr.write("\n")
            sys.stderr.write("\n")
            sys.stderr.write("\n")
            sys.stderr.write("Save the following output to 'schema.xml' and place it in your Solr configuration directory.\n")
            sys.stderr.write("--------------------------------------------------------------------------------------------\n")
            sys.stderr.write("\n")
            print(schema_xml)
    
        def write_file(self, filename, schema_xml):
            schema_file = open(filename, 'w')
            schema_file.write(schema_xml)
            schema_file.close()
    

    误差如下所示:

    Traceback (most recent call last):
    File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
    File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
    utility.execute()
    File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 356, in execute
        self.fetch_command(subcommand).run_from_argv(self.argv)
    File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 275, in run_from_argv
        parser = self.create_parser(argv[0], argv[1])
    File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 249, in create_parser
        self.add_arguments(parser)
    File "/home/tochie/virtual_django/myblog_env/mysite/venv/lib/python3.5/site-packages/haystack/management/commands/build_solr_schema.py", line 22, in add_arguments
        help='If provided, directs output to a file instead of stdout.',),
    File "/usr/lib/python3.5/argparse.py", line 1344, in add_argument
        raise ValueError('%r is not callable' % (type_func,))
    ValueError: 'string' is not callable
    

    如果有任何其他方法可以解决此问题,请提供帮助,而无需编辑haystack的build\u solr\u模式或任何其他解决方案。。谢谢

    1 回复  |  直到 6 年前
        1
  •  1
  •   rtindru    6 年前

    问题在于 type 论点顾名思义,它必须是python类型 str 而不是python字符串 'string' 意思是这就是你需要的

    def add_arguments(self, parser):
        # positional arguments
        parser.add_argument("-f", "--filename", action="store", type=str, dest="filename",
                            help='If provided, directs output to a file instead of stdout.', )
        # optional positional arguments
    
        parser.add_argument("-u", "--using", action="store", type=str, dest="using",
                            default=constants.DEFAULT_ALIAS, help='If provided, chooses a connection to work with.')
    

    当你通过时 类型 作为字符串,而不是类型 str公司 ,则, argparse 假设您正在提供一个可调用的执行。看见 https://docs.python.org/3/library/argparse.html#type

    type=可以接受任何接受单个字符串参数和 返回转换后的值:

    def perfect_square(string):
        value = int(string)
        sqrt = math.sqrt(value)
        if sqrt != int(sqrt):
            msg = "%r is not a perfect square" % string
            raise argparse.ArgumentTypeError(msg)
        return value
    
    parser = argparse.ArgumentParser(prog='PROG')
    parser.add_argument('foo', type=perfect_square)
    parser.parse_args(['9'])
    
    parser.parse_args(['7'])