/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

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