PageRenderTime 45ms CodeModel.GetById 27ms app.highlight 13ms RepoModel.GetById 1ms app.codeStats 0ms

/bangkokhotel/lib/python2.5/site-packages/haystack/management/commands/build_solr_schema.py

https://bitbucket.org/luisrodriguez/bangkokhotel
Python | 55 lines | 45 code | 8 blank | 2 comment | 2 complexity | 90aa209d9eca36add3edcaa9aa0b6319 MD5 | raw file
 1from optparse import make_option
 2import sys
 3from django.core.management.base import BaseCommand
 4from django.template import loader, Context
 5from haystack.constants import ID, DJANGO_CT, DJANGO_ID, DEFAULT_OPERATOR
 6
 7
 8class Command(BaseCommand):
 9    help = "Generates a Solr schema that reflects the indexes."
10    base_options = (
11        make_option("-f", "--filename", action="store", type="string", dest="filename",
12                    help='If provided, directs output to a file instead of stdout.'),
13    )
14    option_list = BaseCommand.option_list + base_options
15    
16    def handle(self, **options):
17        """Generates a Solr schema that reflects the indexes."""
18        schema_xml = self.build_template()
19        
20        if options.get('filename'):
21            self.write_file(options.get('filename'), schema_xml)
22        else:
23            self.print_stdout(schema_xml)
24    
25    def build_context(self):
26        # Cause the default site to load.
27        from haystack import backend, site
28        content_field_name, fields = backend.SearchBackend().build_schema(site.all_searchfields())
29        return Context({
30            'content_field_name': content_field_name,
31            'fields': fields,
32            'default_operator': DEFAULT_OPERATOR,
33            'ID': ID,
34            'DJANGO_CT': DJANGO_CT,
35            'DJANGO_ID': DJANGO_ID,
36        })
37    
38    def build_template(self):
39        t = loader.get_template('search_configuration/solr.xml')
40        c = self.build_context()
41        return t.render(c)
42    
43    def print_stdout(self, schema_xml):
44        sys.stderr.write("\n")
45        sys.stderr.write("\n")
46        sys.stderr.write("\n")
47        sys.stderr.write("Save the following output to 'schema.xml' and place it in your Solr configuration directory.\n")
48        sys.stderr.write("--------------------------------------------------------------------------------------------\n")
49        sys.stderr.write("\n")
50        print schema_xml
51    
52    def write_file(self, filename, schema_xml):
53        schema_file = open(filename, 'w')
54        schema_file.write(schema_xml)
55        schema_file.close()