def import_art(self, fname, year): reader = csv.reader(open(fname, "r")) y = Year.objects.get(year=year) artct = 0 for row in reader: if row: name = smart_unicode(row[1], errors="ignore") name = name.replace('"', "") slug = slugify(name) a = ArtInstallation(name=name, year=y, slug=slug, bm_fm_id=int(row[0])) a.save() artct += 1 print ("done, loaded %i art installations" % artct)
def _create_or_update(self, request, year_year=None, art_id=None): user = request.user if not user.get_profile().api_allowed: return rc_response(request, rc.BAD_REQUEST, 'User not permitted to use the API') method = request.method if method == "PUT": data = request.PUT.copy() elif method == "POST": data = request.POST.copy() else: return rc_response(request, rc.BAD_REQUEST, 'Bad request method: %s' % method) if year_year and 'year' not in data: data['year'] = year_year if not (data and user): log.debug('Bad request: data=%s, user=%s', data, user) return rc_response(request, rc.BAD_REQUEST, 'Missing critical information') log.debug('data for create_or_update: %s', data) obj = None if art_id: try: obj = ArtInstallation.objects.get(pk=art_id) log.debug('got art #%i for update', obj.id) except ArtInstallation.DoesNotExist: return rc_response(request, rc.NOT_HERE, 'ArtInstallation not found #%s' % art_id) # no updating the year! if 'year' in data: del data['year'] elif 'bm_fm_id' in data: log.debug('trying to get art installation from DB: bm_fm_id = %s', data['bm_fm_id']) try: obj = ArtInstallation.objects.get(bm_fm_id=int(data['bm_fm_id'])) except ArtInstallation.DoesNotExist: pass if obj is None: log.debug('creating new ArtInstallation') obj = ArtInstallation() # get rid of illegal-to-update attributes for key in ('id','pk'): if key in data: del data[key] # now loop through the data, updating as needed if 'year' in data: try: year = Year.objects.get(year=data['year']) except Year.DoesNotExist: return rc_response(request, rc.NOT_HERE, 'No such year: %s' % data['year']) obj.year = year # text fields for key in ('description', 'name', 'artist', 'contact_email', 'url', 'slug', 'time_address', 'distance'): if key in data: val = data[key] log.debug('setting %s=%s', key, val) setattr(obj, key, val) #bm_fm_id if 'bm_fm_id' in data: obj.bm_fm_id = int(data['bm_fm_id']) obj.save() if method == 'PUT': response = rc.ALL_OK else: response = rc.CREATED response.content = json.dumps({'pk' : obj.id}) return response