idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
20,900
def __response_message_descriptor ( self , message_type , method_id ) : descriptor = { '200' : { 'description' : 'A successful response' } } if message_type != message_types . VoidMessage ( ) : self . __parser . add_message ( message_type . __class__ ) self . __response_schema [ method_id ] = self . __parser . ref_for_...
Describes the response .
20,901
def __x_google_quota_descriptor ( self , metric_costs ) : return { 'metricCosts' : { metric : cost for ( metric , cost ) in metric_costs . items ( ) } } if metric_costs else None
Describes the metric costs for a call .
20,902
def __x_google_quota_definitions_descriptor ( self , limit_definitions ) : if not limit_definitions : return None definitions_list = [ { 'name' : ld . metric_name , 'metric' : ld . metric_name , 'unit' : '1/min/{project}' , 'values' : { 'STANDARD' : ld . default_limit } , 'displayName' : ld . display_name , } for ld in...
Describes the quota limit definitions for an API .
20,903
def __security_definitions_descriptor ( self , issuers ) : if not issuers : result = { _DEFAULT_SECURITY_DEFINITION : { 'authorizationUrl' : '' , 'flow' : 'implicit' , 'type' : 'oauth2' , 'x-google-issuer' : 'https://accounts.google.com' , 'x-google-jwks_uri' : 'https://www.googleapis.com/oauth2/v3/certs' , } } return ...
Create a descriptor for the security definitions .
20,904
def __api_openapi_descriptor ( self , services , hostname = None , x_google_api_name = False ) : merged_api_info = self . __get_merged_api_info ( services ) descriptor = self . get_descriptor_defaults ( merged_api_info , hostname = hostname , x_google_api_name = x_google_api_name ) description = merged_api_info . descr...
Builds an OpenAPI description of an API .
20,905
def get_openapi_dict ( self , services , hostname = None , x_google_api_name = False ) : if not isinstance ( services , ( tuple , list ) ) : services = [ services ] util . check_list_type ( services , remote . _ServiceClass , 'services' , allow_none = False ) return self . __api_openapi_descriptor ( services , hostname...
JSON dict description of a protorpc . remote . Service in OpenAPI format .
20,906
def pretty_print_config_to_json ( self , services , hostname = None , x_google_api_name = False ) : descriptor = self . get_openapi_dict ( services , hostname , x_google_api_name = x_google_api_name ) return json . dumps ( descriptor , sort_keys = True , indent = 2 , separators = ( ',' , ': ' ) )
JSON string description of a protorpc . remote . Service in OpenAPI format .
20,907
def __pad_value ( value , pad_len_multiple , pad_char ) : assert pad_len_multiple > 0 assert len ( pad_char ) == 1 padding_length = ( pad_len_multiple - ( len ( value ) % pad_len_multiple ) ) % pad_len_multiple return value + pad_char * padding_length
Add padding characters to the value if needed .
20,908
def add_message ( self , message_type ) : name = self . __normalized_name ( message_type ) if name not in self . __schemas : self . __schemas [ name ] = None schema = self . __message_to_schema ( message_type ) self . __schemas [ name ] = schema return name
Add a new message .
20,909
def ref_for_message_type ( self , message_type ) : name = self . __normalized_name ( message_type ) if name not in self . __schemas : raise KeyError ( 'Message has not been parsed: %s' , name ) return name
Returns the JSON Schema id for the given message .
20,910
def __normalized_name ( self , message_type ) : name = message_type . definition_name ( ) split_name = re . split ( r'[^0-9a-zA-Z]' , name ) normalized = '' . join ( part [ 0 ] . upper ( ) + part [ 1 : ] for part in split_name if part ) previous = self . __normalized_names . get ( normalized ) if previous : if previous...
Normalized schema name .
20,911
def __message_to_schema ( self , message_type ) : name = self . __normalized_name ( message_type ) schema = { 'id' : name , 'type' : 'object' , } if message_type . __doc__ : schema [ 'description' ] = message_type . __doc__ properties = { } for field in message_type . all_fields ( ) : descriptor = { } type_info = { } i...
Parse a single message into JSON Schema .
20,912
def _check_enum ( parameter_name , value , parameter_config ) : enum_values = [ enum [ 'backendValue' ] for enum in parameter_config [ 'enum' ] . values ( ) if 'backendValue' in enum ] if value not in enum_values : raise errors . EnumRejectionError ( parameter_name , value , enum_values )
Checks if an enum value is valid .
20,913
def _check_boolean ( parameter_name , value , parameter_config ) : if parameter_config . get ( 'type' ) != 'boolean' : return if value . lower ( ) not in ( '1' , 'true' , '0' , 'false' ) : raise errors . BasicTypeParameterError ( parameter_name , value , 'boolean' )
Checks if a boolean value is valid .
20,914
def _get_parameter_conversion_entry ( parameter_config ) : entry = _PARAM_CONVERSION_MAP . get ( parameter_config . get ( 'type' ) ) if entry is None and 'enum' in parameter_config : entry = _PARAM_CONVERSION_MAP [ 'enum' ] return entry
Get information needed to convert the given parameter to its API type .
20,915
def transform_parameter_value ( parameter_name , value , parameter_config ) : if isinstance ( value , list ) : return [ transform_parameter_value ( '%s[%d]' % ( parameter_name , index ) , element , parameter_config ) for index , element in enumerate ( value ) ] entry = _get_parameter_conversion_entry ( parameter_config...
Validates and transforms parameters to the type expected by the API .
20,916
def filter_items ( self , items ) : items = self . _filter_active ( items ) items = self . _filter_in_nav ( items ) return items
perform filtering items by specific criteria
20,917
def is_leonardo_module ( mod ) : if hasattr ( mod , 'default' ) or hasattr ( mod , 'leonardo_module_conf' ) : return True for key in dir ( mod ) : if 'LEONARDO' in key : return True return False
returns True if is leonardo module
20,918
def _translate_page_into ( page , language , default = None ) : if page . language == language : return page translations = dict ( ( t . language , t ) for t in page . available_translations ( ) ) translations [ page . language ] = page if language in translations : return translations [ language ] else : if hasattr ( ...
Return the translation for a given page
20,919
def feincms_breadcrumbs ( page , include_self = True ) : if not page or not isinstance ( page , Page ) : raise ValueError ( "feincms_breadcrumbs must be called with a valid Page object" ) ancs = page . get_ancestors ( ) bc = [ ( anc . get_absolute_url ( ) , anc . short_title ( ) ) for anc in ancs ] if include_self : bc...
Generate a list of the page s ancestors suitable for use as breadcrumb navigation .
20,920
def is_parent_of ( page1 , page2 ) : try : return page1 . tree_id == page2 . tree_id and page1 . lft < page2 . lft and page1 . rght > page2 . rght except AttributeError : return False
Determines whether a given page is the parent of another page
20,921
def parent ( self ) : if not hasattr ( self , '_parent' ) : if 'parent' in self . kwargs : try : self . _parent = Page . objects . get ( id = self . kwargs [ "parent" ] ) except Exception as e : raise e else : if hasattr ( self . request , 'leonardo_page' ) : self . _parent = self . request . leonardo_page else : retur...
We use parent for some initial data
20,922
def tree_label ( self ) : titles = [ ] page = self while page : titles . append ( page . title ) page = page . parent return smart_text ( ' > ' . join ( reversed ( titles ) ) )
render tree label like as root > child > child
20,923
def flush_ct_inventory ( self ) : if hasattr ( self , '_ct_inventory' ) : self . _ct_inventory = None self . update_view = False self . save ( )
internal method used only if ct_inventory is enabled
20,924
def register_default_processors ( cls , frontend_editing = None ) : super ( Page , cls ) . register_default_processors ( ) if frontend_editing : cls . register_request_processor ( edit_processors . frontendediting_request_processor , key = 'frontend_editing' ) cls . register_response_processor ( edit_processors . front...
Register our default request processors for the out - of - the - box Page experience .
20,925
def run_request_processors ( self , request ) : if not getattr ( self , 'request_processors' , None ) : return for fn in reversed ( list ( self . request_processors . values ( ) ) ) : r = fn ( self , request ) if r : return r
Before rendering a page run all registered request processors . A request processor may peruse and modify the page or the request . It can also return a HttpResponse for shortcutting the rendering and returning that response immediately to the client .
20,926
def as_text ( self ) : from leonardo . templatetags . leonardo_tags import _render_content request = get_anonymous_request ( self ) content = '' try : for region in [ region . key for region in self . _feincms_all_regions ] : content += '' . join ( _render_content ( content , request = request , context = { } ) for con...
Fetch and render all regions
20,927
def technical_404_response ( request , exception ) : "Create a technical 404 error response. The exception should be the Http404." try : error_url = exception . args [ 0 ] [ 'path' ] except ( IndexError , TypeError , KeyError ) : error_url = request . path_info [ 1 : ] try : tried = exception . args [ 0 ] [ 'tried' ] e...
Create a technical 404 error response . The exception should be the Http404 .
20,928
def items ( self ) : if hasattr ( self , '_items' ) : return self . filter_items ( self . _items ) self . _items = self . get_items ( ) return self . filter_items ( self . _items )
access for filtered items
20,929
def populate_items ( self , request ) : self . _items = self . get_items ( request ) return self . items
populate and returns filtered items
20,930
def columns_classes ( self ) : md = 12 / self . objects_per_row sm = None if self . objects_per_row > 2 : sm = 12 / ( self . objects_per_row / 2 ) return md , ( sm or md ) , 12
returns columns count
20,931
def get_pages ( self ) : pages = [ ] page = [ ] for i , item in enumerate ( self . get_rows ) : if i > 0 and i % self . objects_per_page == 0 : pages . append ( page ) page = [ ] page . append ( item ) pages . append ( page ) return pages
returns pages with rows
20,932
def needs_pagination ( self ) : if self . objects_per_page == 0 : return False if len ( self . items ) > self . objects_per_page or len ( self . get_pages [ 0 ] ) > self . objects_per_page : return True return False
Calculate needs pagination
20,933
def get_item_template ( self ) : content_template = self . content_theme . name if content_template == "default" : return "widget/%s/_item.html" % self . widget_name return "widget/%s/_%s.html" % ( self . widget_name , content_template )
returns template for signle object from queryset If you have a template name my_list_template . html then template for a single object will be _my_list_template . html
20,934
def is_obsolete ( self ) : if self . cache_updated : now = timezone . now ( ) delta = now - self . cache_updated if delta . seconds < self . cache_validity : return False return True
returns True is data is obsolete and needs revalidation
20,935
def update_cache ( self , data = None ) : if data : self . cache_data = data self . cache_updated = timezone . now ( ) self . save ( )
call with new data or set data to self . cache_data and call this
20,936
def data ( self ) : if self . is_obsolete ( ) : self . update_cache ( self . get_data ( ) ) return self . cache_data
this property just calls get_data but here you can serilalize your data or render as html these data will be saved to self . cached_content also will be accessable from template
20,937
def data ( self ) : if self . is_obsolete ( ) : data = self . get_data ( ) for datum in data : if 'published_parsed' in datum : datum [ 'published_parsed' ] = self . parse_time ( datum [ 'published_parsed' ] ) try : dumped_data = json . dumps ( data ) except : self . update_cache ( data ) else : self . update_cache ( d...
load and cache data in json format
20,938
def get_loaded_modules ( modules ) : _modules = [ ] for mod in modules : mod_cfg = get_conf_from_module ( mod ) _modules . append ( ( mod , mod_cfg , ) ) _modules = sorted ( _modules , key = lambda m : m [ 1 ] . get ( 'ordering' ) ) return _modules
load modules and order it by ordering key
20,939
def _is_leonardo_module ( whatever ) : if hasattr ( whatever , 'default' ) or hasattr ( whatever , 'leonardo_module_conf' ) : return True for key in dir ( whatever ) : if 'LEONARDO' in key : return True
check if is leonardo module
20,940
def extract_conf_from ( mod , conf = ModuleConfig ( CONF_SPEC ) , depth = 0 , max_depth = 2 ) : for key , default_value in six . iteritems ( conf ) : conf [ key ] = _get_key_from_module ( mod , key , default_value ) try : filtered_apps = [ app for app in conf [ 'apps' ] if app not in BLACKLIST ] except TypeError : pass...
recursively extract keys from module or object by passed config scheme
20,941
def _get_correct_module ( mod ) : module_location = getattr ( mod , 'leonardo_module_conf' , getattr ( mod , "LEONARDO_MODULE_CONF" , None ) ) if module_location : mod = import_module ( module_location ) elif hasattr ( mod , 'default_app_config' ) : mod_path , _ , cls_name = mod . default_app_config . rpartition ( '.' ...
returns imported module check if is leonardo_module_conf specified and then import them
20,942
def get_conf_from_module ( mod ) : conf = ModuleConfig ( CONF_SPEC ) mod = _get_correct_module ( mod ) conf . set_module ( mod ) if hasattr ( mod , 'default' ) : default = mod . default conf = extract_conf_from ( default , conf ) else : conf = extract_conf_from ( mod , conf ) return conf
return configuration from module with defaults no worry about None type
20,943
def get_anonymous_request ( leonardo_page ) : request_factory = RequestFactory ( ) request = request_factory . get ( leonardo_page . get_absolute_url ( ) , data = { } ) request . feincms_page = request . leonardo_page = leonardo_page request . frontend_editing = False request . user = AnonymousUser ( ) if not hasattr (...
returns inicialized request
20,944
def webfont_cookie ( request ) : if hasattr ( request , 'COOKIES' ) and request . COOKIES . get ( WEBFONT_COOKIE_NAME , None ) : return { WEBFONT_COOKIE_NAME . upper ( ) : True } return { WEBFONT_COOKIE_NAME . upper ( ) : False }
Adds WEBFONT Flag to the context
20,945
def get_all_widget_classes ( ) : from leonardo . module . web . models import Widget _widgets = getattr ( settings , 'WIDGETS' , Widget . __subclasses__ ( ) ) widgets = [ ] if isinstance ( _widgets , dict ) : for group , widget_cls in six . iteritems ( _widgets ) : widgets . extend ( widget_cls ) elif isinstance ( _wid...
returns collected Leonardo Widgets
20,946
def render_region ( widget = None , request = None , view = None , page = None , region = None ) : if not isinstance ( request , dict ) : request . query_string = None request . method = "GET" if not hasattr ( request , '_feincms_extra_context' ) : request . _feincms_extra_context = { } leonardo_page = widget . parent ...
returns rendered content this is not too clear and little tricky because external apps needs calling process method
20,947
def get_feincms_inlines ( self , model , request ) : model . _needs_content_types ( ) inlines = [ ] for content_type in model . _feincms_content_types : if not self . can_add_content ( request , content_type ) : continue attrs = { '__module__' : model . __module__ , 'model' : content_type , } if hasattr ( content_type ...
Generate genuine django inlines for registered content types .
20,948
def get_changeform_initial_data ( self , request ) : initial = super ( PageAdmin , self ) . get_changeform_initial_data ( request ) if ( 'translation_of' in request . GET ) : original = self . model . _tree_manager . get ( pk = request . GET . get ( 'translation_of' ) ) initial [ 'layout' ] = original . layout initial ...
Copy initial data from parent
20,949
def install_package ( package , upgrade = True , target = None ) : with INSTALL_LOCK : if check_package_exists ( package , target ) : return True _LOGGER . info ( 'Attempting install of %s' , package ) args = [ sys . executable , '-m' , 'pip' , 'install' , '--quiet' , package ] if upgrade : args . append ( '--upgrade' ...
Install a package on PyPi . Accepts pip compatible package strings .
20,950
def check_package_exists ( package , lib_dir ) : try : req = pkg_resources . Requirement . parse ( package ) except ValueError : req = pkg_resources . Requirement . parse ( urlparse ( package ) . fragment ) if lib_dir is not None : if any ( dist in req for dist in pkg_resources . find_distributions ( lib_dir ) ) : retu...
Check if a package is installed globally or in lib_dir .
20,951
def render_widget ( self , request , widget_id ) : widget = get_widget_from_id ( widget_id ) response = widget . render ( ** { 'request' : request } ) return JsonResponse ( { 'result' : response , 'id' : widget_id } )
Returns rendered widget in JSON response
20,952
def render_region ( self , request ) : page = self . get_object ( ) try : region = request . POST [ 'region' ] except KeyError : region = request . GET [ 'region' ] request . query_string = None from leonardo . utils . widgets import render_region result = render_region ( page = page , request = request , region = regi...
Returns rendered region in JSON response
20,953
def handle_ajax_method ( self , request , method ) : response = { } def get_param ( request , name ) : try : return request . POST [ name ] except KeyError : return request . GET . get ( name , None ) widget_id = get_param ( request , "widget_id" ) class_name = get_param ( request , "class_name" ) if method in 'widget_...
handle ajax methods and return serialized reponse in the default state allows only authentificated users
20,954
def add_bootstrap_class ( field ) : if not isinstance ( field . field . widget , ( django . forms . widgets . CheckboxInput , django . forms . widgets . CheckboxSelectMultiple , django . forms . widgets . RadioSelect , django . forms . widgets . FileInput , str ) ) : field_classes = set ( field . field . widget . attrs...
Add a form - control CSS class to the field s widget .
20,955
def ajax_upload ( self , request , folder_id = None ) : mimetype = "application/json" if request . is_ajax ( ) else "text/html" content_type_key = 'content_type' response_params = { content_type_key : mimetype } folder = None if folder_id : try : folder = Folder . objects . get ( pk = folder_id ) except Folder . DoesNo...
receives an upload from the uploader . Receives only one file at the time .
20,956
def set_options ( self , ** options ) : self . interactive = False self . verbosity = options [ 'verbosity' ] self . symlink = "" self . clear = False ignore_patterns = [ ] self . ignore_patterns = list ( set ( ignore_patterns ) ) self . page_themes_updated = 0 self . skins_updated = 0
Set instance variables based on an options dict
20,957
def collect ( self ) : self . ignore_patterns = [ '*.png' , '*.jpg' , '*.js' , '*.gif' , '*.ttf' , '*.md' , '*.rst' , '*.svg' ] page_themes = PageTheme . objects . all ( ) for finder in get_finders ( ) : for path , storage in finder . list ( self . ignore_patterns ) : for t in page_themes : static_path = 'themes/{0}' ....
Load and save PageColorScheme for every PageTheme
20,958
def has_generic_permission ( self , request , permission_type ) : user = request . user if not user . is_authenticated ( ) : return False elif user . is_superuser : return True elif user == self . owner : return True elif self . folder : return self . folder . has_generic_permission ( request , permission_type ) else :...
Return true if the current user has permission on this image . Return the string ALL if the user has all rights .
20,959
def get_template_data ( self , request , * args , ** kwargs ) : dimension = int ( self . get_size ( ) . split ( 'x' ) [ 0 ] ) data = { } if dimension <= 356 : data [ 'image_dimension' ] = "row-md-13" if self . get_template_name ( ) . name . split ( "/" ) [ - 1 ] == "directories.html" : data [ 'directories' ] = self . g...
Add image dimensions
20,960
def _decorate_urlconf ( urlpatterns , decorator = require_auth , * args , ** kwargs ) : if isinstance ( urlpatterns , ( list , tuple ) ) : for pattern in urlpatterns : if getattr ( pattern , 'callback' , None ) : pattern . _callback = decorator ( pattern . callback , * args , ** kwargs ) if getattr ( pattern , 'url_pat...
Decorate all urlpatterns by specified decorator
20,961
def catch_result ( task_func ) : @ functools . wraps ( task_func , assigned = available_attrs ( task_func ) ) def dec ( * args , ** kwargs ) : orig_stdout = sys . stdout sys . stdout = content = StringIO ( ) task_response = task_func ( * args , ** kwargs ) sys . stdout = orig_stdout content . seek ( 0 ) task_response [...
Catch printed result from Celery Task and return it in task response
20,962
def compress_monkey_patch ( ) : from compressor . templatetags import compress as compress_tags from compressor import base as compress_base compress_base . Compressor . filter_input = filter_input compress_base . Compressor . output = output compress_base . Compressor . hunks = hunks compress_base . Compressor . preco...
patch all compress
20,963
def output ( self , mode = 'file' , forced = False , context = None ) : output = '\n' . join ( self . filter_input ( forced , context = context ) ) if not output : return '' if settings . COMPRESS_ENABLED or forced : filtered_output = self . filter_output ( output ) return self . handle_output ( mode , filtered_output ...
The general output method override in subclass if you need to do any custom modification . Calls other mode specific methods or simply returns the content directly .
20,964
def precompile ( self , content , kind = None , elem = None , filename = None , charset = None , ** kwargs ) : if not kind : return False , content attrs = self . parser . elem_attribs ( elem ) mimetype = attrs . get ( "type" , None ) if mimetype is None : return False , content filter_or_command = self . precompiler_m...
Processes file using a pre compiler . This is the place where files like coffee script are processed .
20,965
def decode ( self , data ) : self . val = ':' . join ( "%02x" % x for x in reversed ( data [ : 6 ] ) ) return data [ 6 : ]
Decode the MAC address from a byte array .
20,966
def thumbnail ( parser , token ) : thumb = None if SORL : try : thumb = sorl_thumb ( parser , token ) except Exception : thumb = False if EASY and not thumb : thumb = easy_thumb ( parser , token ) return thumb
This template tag supports both syntax for declare thumbanil in template
20,967
def handle_uploaded_file ( file , folder = None , is_public = True ) : _folder = None if folder and isinstance ( folder , Folder ) : _folder = folder elif folder : _folder , folder_created = Folder . objects . get_or_create ( name = folder ) for cls in MEDIA_MODELS : if cls . matches_file_type ( file . name ) : obj , c...
handle uploaded file to folder match first media type and create media object and returns it
20,968
def handle_uploaded_files ( files , folder = None , is_public = True ) : results = [ ] for f in files : result = handle_uploaded_file ( f , folder , is_public ) results . append ( result ) return results
handle uploaded files to folder
20,969
def serve_protected_file ( request , path ) : path = path . rstrip ( '/' ) try : file_obj = File . objects . get ( file = path ) except File . DoesNotExist : raise Http404 ( 'File not found %s' % path ) if not file_obj . has_read_permission ( request ) : if settings . DEBUG : raise PermissionDenied else : raise Http404...
Serve protected files to authenticated users with read permissions .
20,970
def serve_protected_thumbnail ( request , path ) : source_path = thumbnail_to_original_filename ( path ) if not source_path : raise Http404 ( 'File not found' ) try : file_obj = File . objects . get ( file = source_path ) except File . DoesNotExist : raise Http404 ( 'File not found %s' % path ) if not file_obj . has_re...
Serve protected thumbnails to authenticated users . If the user doesn t have read permissions redirect to a static image .
20,971
def get_app_modules ( self , apps ) : modules = getattr ( self , "_modules" , [ ] ) if not modules : from django . utils . module_loading import module_has_submodule package_string = '.' . join ( [ 'leonardo' , 'module' ] ) for app in apps : exc = '...' try : _app = import_module ( app ) except Exception as e : _app = ...
return array of imported leonardo modules for apps
20,972
def urlpatterns ( self ) : if not hasattr ( self , '_urlspatterns' ) : urlpatterns = [ ] for mod in leonardo . modules : if is_leonardo_module ( mod ) : conf = get_conf_from_module ( mod ) if module_has_submodule ( mod , 'urls' ) : urls_mod = import_module ( '.urls' , mod . __name__ ) if hasattr ( urls_mod , 'urlpatter...
load and decorate urls from all modules then store it as cached property for less loading
20,973
def cycle_app_reverse_cache ( * args , ** kwargs ) : value = '%07x' % ( SystemRandom ( ) . randint ( 0 , 0x10000000 ) ) cache . set ( APP_REVERSE_CACHE_GENERATION_KEY , value ) return value
Does not really empty the cache ; instead it adds a random element to the cache key generation which guarantees that the cache does not yet contain values for all newly generated keys
20,974
def reverse ( viewname , urlconf = None , args = None , kwargs = None , current_app = None ) : if not urlconf : urlconf = get_urlconf ( ) resolver = get_resolver ( urlconf ) args = args or [ ] kwargs = kwargs or { } prefix = get_script_prefix ( ) if not isinstance ( viewname , six . string_types ) : view = viewname els...
monkey patched reverse
20,975
def add_page_if_missing ( request ) : try : page = Page . objects . for_request ( request , best_match = True ) return { 'leonardo_page' : page , 'feincms_page' : page , } except Page . DoesNotExist : return { }
Returns feincms_page for request .
20,976
def render_in_page ( request , template ) : from leonardo . module . web . models import Page page = request . leonardo_page if hasattr ( request , 'leonardo_page' ) else Page . objects . filter ( parent = None ) . first ( ) if page : try : slug = request . path_info . split ( "/" ) [ - 2 : - 1 ] [ 0 ] except KeyError ...
return rendered template in standalone mode or False
20,977
def page_not_found ( request , template_name = '404.html' ) : response = render_in_page ( request , template_name ) if response : return response template = Template ( '<h1>Not Found</h1>' '<p>The requested URL {{ request_path }} was not found on this server.</p>' ) body = template . render ( RequestContext ( request ,...
Default 404 handler .
20,978
def bad_request ( request , template_name = '400.html' ) : response = render_in_page ( request , template_name ) if response : return response try : template = loader . get_template ( template_name ) except TemplateDoesNotExist : return http . HttpResponseBadRequest ( '<h1>Bad Request (400)</h1>' , content_type = 'text...
400 error handler .
20,979
def process_response ( self , request , response ) : if request . is_ajax ( ) and hasattr ( request , 'horizon' ) : queued_msgs = request . horizon [ 'async_messages' ] if type ( response ) == http . HttpResponseRedirect : for tag , message , extra_tags in queued_msgs : getattr ( django_messages , tag ) ( request , mes...
Convert HttpResponseRedirect to HttpResponse if request is via ajax to allow ajax request to redirect url
20,980
def process_exception ( self , request , exception ) : if isinstance ( exception , ( exceptions . NotAuthorized , exceptions . NotAuthenticated ) ) : auth_url = settings . LOGIN_URL next_url = None if request . method in ( "POST" , "PUT" ) : referrer = request . META . get ( 'HTTP_REFERER' ) if referrer and is_safe_url...
Catches internal Horizon exception classes such as NotAuthorized NotFound and Http302 and handles them gracefully .
20,981
def canonical ( request , uploaded_at , file_id ) : filer_file = get_object_or_404 ( File , pk = file_id , is_public = True ) if ( uploaded_at != filer_file . uploaded_at . strftime ( '%s' ) or not filer_file . file ) : raise Http404 ( 'No %s matches the given query.' % File . _meta . object_name ) return redirect ( fi...
Redirect to the current url of a public file
20,982
def check_message ( keywords , message ) : exc_type , exc_value , exc_traceback = sys . exc_info ( ) if set ( str ( exc_value ) . split ( " " ) ) . issuperset ( set ( keywords ) ) : exc_value . message = message raise
Checks an exception for given keywords and raises a new ActionError with the desired message if the keywords are found . This allows selective control over API error messages .
20,983
def get_switched_form_field_attrs ( self , prefix , input_type , name ) : attributes = { 'class' : 'switched' , 'data-switch-on' : prefix + 'field' } attributes [ 'data-' + prefix + 'field-' + input_type ] = name return attributes
Creates attribute dicts for the switchable theme form
20,984
def clean_slug ( self ) : slug = self . cleaned_data . get ( 'slug' , None ) if slug is None or len ( slug ) == 0 and 'title' in self . cleaned_data : slug = slugify ( self . cleaned_data [ 'title' ] ) return slug
slug title if is not provided
20,985
def get_widget_from_id ( id ) : res = id . split ( '-' ) try : model_cls = apps . get_model ( res [ 0 ] , res [ 1 ] ) obj = model_cls . objects . get ( parent = res [ 2 ] , id = res [ 3 ] ) except : obj = None return obj
returns widget object by id
20,986
def get_widget_class_from_id ( id ) : res = id . split ( '-' ) try : model_cls = apps . get_model ( res [ 1 ] , res [ 2 ] ) except : model_cls = None return model_cls
returns widget class by id
20,987
def frontendediting_request_processor ( page , request ) : if 'frontend_editing' not in request . GET : return response = HttpResponseRedirect ( request . path ) if request . user . has_module_perms ( 'page' ) : if 'frontend_editing' in request . GET : try : enable_fe = int ( request . GET [ 'frontend_editing' ] ) > 0 ...
Sets the frontend editing state in the cookie depending on the frontend_editing GET parameter and the user s permissions .
20,988
def extra_context ( self ) : from django . conf import settings return { "site_name" : ( lambda r : settings . LEONARDO_SITE_NAME if getattr ( settings , 'LEONARDO_SITE_NAME' , '' ) != '' else settings . SITE_NAME ) , "debug" : lambda r : settings . TEMPLATE_DEBUG }
Add site_name to context
20,989
def get_property ( self , key ) : _key = DJANGO_CONF [ key ] return getattr ( self , _key , CONF_SPEC [ _key ] )
Expect Django Conf property
20,990
def needs_sync ( self ) : affected_attributes = [ 'css_files' , 'js_files' , 'scss_files' , 'widgets' ] for attr in affected_attributes : if len ( getattr ( self , attr ) ) > 0 : return True return False
Indicates whater module needs templates static etc .
20,991
def get_attr ( self , name , default = None , fail_silently = True ) : try : return getattr ( self , name ) except KeyError : extra_context = getattr ( self , "extra_context" ) if name in extra_context : value = extra_context [ name ] if callable ( value ) : return value ( request = None ) return default
try extra context
20,992
def find_all_templates ( pattern = '*.html' , ignore_private = True ) : templates = [ ] template_loaders = flatten_template_loaders ( settings . TEMPLATE_LOADERS ) for loader_name in template_loaders : module , klass = loader_name . rsplit ( '.' , 1 ) if loader_name in ( 'django.template.loaders.app_directories.Loader'...
Finds all Django templates matching given glob in all TEMPLATE_LOADERS
20,993
def flatten_template_loaders ( templates ) : for loader in templates : if not isinstance ( loader , string_types ) : for subloader in flatten_template_loaders ( loader ) : yield subloader else : yield loader
Given a collection of template loaders unwrap them into one flat iterable .
20,994
def seek ( self , offset , whence = os . SEEK_SET ) : self . wrapped . seek ( offset , whence )
Sets the file s current position .
20,995
def put_file ( self , file , object_type , object_id , width , height , mimetype , reproducible ) : raise NotImplementedError ( 'put_file() has to be implemented' )
Puts the file of the image .
20,996
def delete ( self , image ) : from . entity import Image if not isinstance ( image , Image ) : raise TypeError ( 'image must be a sqlalchemy_imageattach.entity.' 'Image instance, not ' + repr ( image ) ) self . delete_file ( image . object_type , image . object_id , image . width , image . height , image . mimetype )
Delete the file of the given image .
20,997
def locate ( self , image ) : from . entity import Image if not isinstance ( image , Image ) : raise TypeError ( 'image must be a sqlalchemy_imageattach.entity.' 'Image instance, not ' + repr ( image ) ) url = self . get_url ( image . object_type , image . object_id , image . width , image . height , image . mimetype )...
Gets the URL of the given image .
20,998
def identity_attributes ( cls ) : columns = inspect ( cls ) . primary_key names = [ c . name for c in columns if c . name not in ( 'width' , 'height' ) ] return names
A list of the names of primary key fields .
20,999
def make_blob ( self , store = current_store ) : with self . open_file ( store ) as f : return f . read ( )
Gets the byte string of the image from the store .