Permalink
Browse files

working on import / export feature

  • Loading branch information...
1 parent 871d645 commit bd9c86247c7c468480110a365719ccabdecb9428 @andrewschoen andrewschoen committed Jun 10, 2011
@@ -0,0 +1,55 @@
+import os
+import csv
+from optparse import make_option
+
+from django.core.management.base import BaseCommand, CommandError
+from django.contrib.sites.models import Site
+from django.core.exceptions import ObjectDoesNotExist
+
+
+class Command(BaseCommand):
+ can_import_settings = True
+ help='''Import redirects'''
+ args = "<csv_path>"
+
+ option_list = BaseCommand.option_list + (
+ make_option('--site',
+ dest="site",
+ default=Site.objects.get_current(),
+ help="Use to specify the domain of the site you are importing redirects into. Defaults to current site."),
+ )
+
+ def execute(self, *args, **options):
+ if len(args) != 1:
+ raise CommandError("Must pass in the absolute path to the csv import file")
+ csv_path = args[0]
+
+ if not os.path.exists(csv_path):
+ raise CommandError("File not found, invalid path: %s" % csv_path)
+ csv_file = open(csv_path, "rb")
+ reader = csv.reader(csv_file)
+ header_row = reader.next()
+ if header_row != ["Old Url","New Url","Response Code"]:
+ raise CommandError("CSV file is missing the correct header row. Should be Old Url, New Url and Response Code")
+ reader = csv.DictReader(csv_file, header_row)
+
+ current_site = options["site"]
+ if not isinstance(current_site, Site):
+ try:
+ current_site = Site.objects.get(domain=options["site"])
+ except ObjectDoesNotExist:
+ raise CommandError("No site found, invalid domain: %s" % options["site"])
+
+ for row in reader:
+ print row["Old Url"]
+ print row["New Url"]
+ print "*************"
+
+
+
+
+
+
+
+
+
@@ -21,14 +21,10 @@ class Command(BaseCommand):
Usage:
./manage.py redirect_csv > import.csv
- ./manage.py redirect_csv -ga > import_google_analytics.csv
+ ./manage.py redirect_csv --ga > import_google_analytics.csv
'''
option_list = BaseCommand.option_list + (
- make_option('--rows',
- dest="num_rows",
- default=5,
- help="Use to specify the number of extra rows"),
make_option('--ga',
action='store_true',
dest="use_analytics",
@@ -54,7 +50,6 @@ class Command(BaseCommand):
def execute(self, *args, **options):
- num_rows = options["num_rows"]
output = StringIO.StringIO()
writer = csv.writer(output)
writer.writerow(['Old Url','New Url','Response Code'])
@@ -75,8 +70,7 @@ def execute(self, *args, **options):
sorted_data = sorted(data.dict.iteritems(), key=operator.itemgetter(1), reverse=True)
for url, visits in sorted_data:
writer.writerow([csv_safe(url),'',''])
- else:
- [writer.writerow(['','','']) for row in range(0,num_rows)]
+
print output.getvalue()
def csv_safe(s):

0 comments on commit bd9c862

Please sign in to comment.