<s> from __future__ import unicode_literals <EOL> from django import template <EOL> from django . conf import settings <EOL> from django . core . cache import cache <EOL> from django . utils . encoding import force_str , force_text <EOL> from django . utils . functional import cached_property <EOL> import csv <EOL> import logging <EOL> import requests <EOL> logger = logging . getLogger ( __name__ ) <EOL> register = template . Library ( ) <EOL> gdocs_format = '<STR_LIT>' <EOL> CACHE_TIMEOUT = getattr ( settings , '<STR_LIT>' , <NUM_LIT> ) <EOL> CACHE_KEY = '<STR_LIT>' <EOL> class Sheet ( object ) : <EOL> def __init__ ( self , key , gid ) : <EOL> if not key : <EOL> raise RuntimeError ( '<STR_LIT>' ) <EOL> self . key = key <EOL> self . gid = gid <EOL> def __len__ ( self ) : <EOL> return len ( self . data ) <EOL> def __iter__ ( self ) : <EOL> return iter ( self . data ) <EOL> def headers ( self ) : <EOL> return self . data [ <NUM_LIT:0> ] if self . data else [ ] <EOL> def rows ( self ) : <EOL> return self . data [ <NUM_LIT:1> : ] if len ( self ) > <NUM_LIT:1> else [ ] <EOL> def _fetch_sheet ( self ) : <EOL> try : <EOL> gdocs_url = gdocs_format . format ( key = self . key ) <EOL> if self . gid : <EOL> gdocs_url += '<STR_LIT>' . format ( self . gid ) <EOL> response = requests . get ( gdocs_url ) <EOL> response . raise_for_status ( ) <EOL> return force_str ( response . content ) <EOL> except requests . HTTPError as exp : <EOL> logger . error ( '<STR_LIT>' % exp ) <EOL> return force_str ( '<STR_LIT>' ) <EOL> def fetch_sheet ( self ) : <EOL> cache_enabled = not getattr ( settings , '<STR_LIT>' , False ) <EOL> if cache_enabled : <EOL> cache_key = CACHE_KEY . format ( <EOL> key = self . key , gid = self . gid ) <EOL> cached_output = cache . get ( cache_key ) <EOL> if cached_output is not None : <EOL> return cached_output <EOL> sheet = self . _fetch_sheet ( ) <EOL> if cache_enabled : <EOL> cache . set ( cache_key , sheet , CACHE_TIMEOUT ) <EOL> return sheet <EOL> @ cached_property <EOL> def data ( self ) : <EOL> sheet = self . fetch_sheet ( ) <EOL> reader = csv . reader ( <EOL> sheet . splitlines ( ) , <EOL> delimiter = str ( '<STR_LIT:U+002C>' ) , <EOL> quotechar = str ( '<STR_LIT:">' ) , <EOL> quoting = csv . QUOTE_MINIMAL , <EOL> ) <EOL> return [ [ force_text ( cell ) for cell in row ] for row in reader ] <EOL> @ register . assignment_tag ( name = '<STR_LIT>' ) <EOL> def csv_tag ( key , gid = None ) : <EOL> return Sheet ( key , gid ) </s>
