idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
20,800 | 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 . | 58 | 9 |
20,801 | 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 limit_definitions ] metrics = [ { 'name' : ld . metric_name , 'valueType' : 'INT64' , 'metricKind' : 'GAUGE' , } for ld in limit_definitions ] return { 'quota' : { 'limits' : definitions_list } , 'metrics' : metrics , } | Describes the quota limit definitions for an API . | 188 | 10 |
20,802 | 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 result result = { } for issuer_key , issuer_value in issuers . items ( ) : result [ issuer_key ] = { 'authorizationUrl' : '' , 'flow' : 'implicit' , 'type' : 'oauth2' , 'x-google-issuer' : issuer_value . issuer , } # If jwks_uri is omitted, the auth library will use OpenID discovery # to find it. Otherwise, include it in the descriptor explicitly. if issuer_value . jwks_uri : result [ issuer_key ] [ 'x-google-jwks_uri' ] = issuer_value . jwks_uri return result | Create a descriptor for the security definitions . | 268 | 8 |
20,803 | def get_openapi_dict ( self , services , hostname = None , x_google_api_name = False ) : if not isinstance ( services , ( tuple , list ) ) : services = [ services ] # The type of a class that inherits from remote.Service is actually # remote._ServiceClass, thanks to metaclass strangeness. # pylint: disable=protected-access util . check_list_type ( services , remote . _ServiceClass , 'services' , allow_none = False ) return self . __api_openapi_descriptor ( services , hostname = hostname , x_google_api_name = x_google_api_name ) | JSON dict description of a protorpc . remote . Service in OpenAPI format . | 149 | 17 |
20,804 | 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 . | 92 | 17 |
20,805 | 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 . | 76 | 9 |
20,806 | def add_message ( self , message_type ) : name = self . __normalized_name ( message_type ) if name not in self . __schemas : # Set a placeholder to prevent infinite recursion. self . __schemas [ name ] = None schema = self . __message_to_schema ( message_type ) self . __schemas [ name ] = schema return name | Add a new message . | 87 | 5 |
20,807 | 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 . | 60 | 11 |
20,808 | def __normalized_name ( self , message_type ) : # Normalization is applied to match the constraints that Discovery applies # to Schema names. 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 != name : raise KeyError ( 'Both %s and %s normalize to the same schema name: %s' % ( name , previous , normalized ) ) else : self . __normalized_names [ normalized ] = name return normalized | Normalized schema name . | 166 | 5 |
20,809 | 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 = { } # Info about the type of this field. This is either merged with # the descriptor or it's placed within the descriptor's 'items' # property, depending on whether this is a repeated field or not. type_info = { } if type ( field ) == messages . MessageField : field_type = field . type ( ) . __class__ type_info [ '$ref' ] = self . add_message ( field_type ) if field_type . __doc__ : descriptor [ 'description' ] = field_type . __doc__ else : schema_type = self . __FIELD_TO_SCHEMA_TYPE_MAP . get ( type ( field ) , self . __DEFAULT_SCHEMA_TYPE ) # If the map pointed to a dictionary, check if the field's variant # is in that dictionary and use the type specified there. if isinstance ( schema_type , dict ) : variant_map = schema_type variant = getattr ( field , 'variant' , None ) if variant in variant_map : schema_type = variant_map [ variant ] else : # The variant map needs to specify a default value, mapped by None. schema_type = variant_map [ None ] type_info [ 'type' ] = schema_type [ 0 ] if schema_type [ 1 ] : type_info [ 'format' ] = schema_type [ 1 ] if type ( field ) == messages . EnumField : sorted_enums = sorted ( [ enum_info for enum_info in field . type ] , key = lambda enum_info : enum_info . number ) type_info [ 'enum' ] = [ enum_info . name for enum_info in sorted_enums ] if field . required : descriptor [ 'required' ] = True if field . default : if type ( field ) == messages . EnumField : descriptor [ 'default' ] = str ( field . default ) else : descriptor [ 'default' ] = field . default if field . repeated : descriptor [ 'items' ] = type_info descriptor [ 'type' ] = 'array' else : descriptor . update ( type_info ) properties [ field . name ] = descriptor schema [ 'properties' ] = properties return schema | Parse a single message into JSON Schema . | 567 | 10 |
20,810 | 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 . | 81 | 9 |
20,811 | 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 . | 81 | 9 |
20,812 | def _get_parameter_conversion_entry ( parameter_config ) : entry = _PARAM_CONVERSION_MAP . get ( parameter_config . get ( 'type' ) ) # Special handling for enum parameters. An enum's type is 'string', so we # need to detect them by the presence of an 'enum' property in their # configuration. 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 . | 107 | 13 |
20,813 | def transform_parameter_value ( parameter_name , value , parameter_config ) : if isinstance ( value , list ) : # We're only expecting to handle path and query string parameters here. # The way path and query string parameters are passed in, they'll likely # only be single values or singly-nested lists (no lists nested within # lists). But even if there are nested lists, we'd want to preserve that # structure. These recursive calls should preserve it and convert all # parameter values. See the docstring for information about the parameter # renaming done here. return [ transform_parameter_value ( '%s[%d]' % ( parameter_name , index ) , element , parameter_config ) for index , element in enumerate ( value ) ] # Validate and convert the parameter value. entry = _get_parameter_conversion_entry ( parameter_config ) if entry : validation_func , conversion_func , type_name = entry if validation_func : validation_func ( parameter_name , value , parameter_config ) if conversion_func : try : return conversion_func ( value ) except ValueError : raise errors . BasicTypeParameterError ( parameter_name , value , type_name ) return value | Validates and transforms parameters to the type expected by the API . | 263 | 13 |
20,814 | def filter_items ( self , items ) : items = self . _filter_active ( items ) items = self . _filter_in_nav ( items ) return items | perform filtering items by specific criteria | 36 | 7 |
20,815 | 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 | 61 | 9 |
20,816 | def _translate_page_into ( page , language , default = None ) : # Optimisation shortcut: No need to dive into translations if page already what we want 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 ( default , '__call__' ) : return default ( page = page ) return default | Return the translation for a given page | 109 | 7 |
20,817 | 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 . append ( ( None , page . short_title ( ) ) ) return { "trail" : bc } | Generate a list of the page s ancestors suitable for use as breadcrumb navigation . | 126 | 18 |
20,818 | 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 | 63 | 13 |
20,819 | 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 : return None return self . _parent | We use parent for some initial data | 104 | 7 |
20,820 | 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 | 48 | 10 |
20,821 | def flush_ct_inventory ( self ) : if hasattr ( self , '_ct_inventory' ) : # skip self from update self . _ct_inventory = None self . update_view = False self . save ( ) | internal method used only if ct_inventory is enabled | 49 | 11 |
20,822 | 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 . frontendediting_response_processor , key = 'frontend_editing' ) | Register our default request processors for the out - of - the - box Page experience . | 107 | 17 |
20,823 | 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 . | 64 | 46 |
20,824 | 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 content in getattr ( self . content , region ) ) except PermissionDenied : pass except Exception as e : LOG . exception ( e ) return content | Fetch and render all regions | 123 | 6 |
20,825 | def technical_404_response ( request , exception ) : try : error_url = exception . args [ 0 ] [ 'path' ] except ( IndexError , TypeError , KeyError ) : error_url = request . path_info [ 1 : ] # Trim leading slash try : tried = exception . args [ 0 ] [ 'tried' ] except ( IndexError , TypeError , KeyError ) : tried = [ ] else : if ( not tried # empty URLconf or ( request . path == '/' and len ( tried ) == 1 # default URLconf and len ( tried [ 0 ] ) == 1 and getattr ( tried [ 0 ] [ 0 ] , 'app_name' , '' ) == getattr ( tried [ 0 ] [ 0 ] , 'namespace' , '' ) == 'admin' ) ) : return default_urlconf ( request ) urlconf = getattr ( request , 'urlconf' , settings . ROOT_URLCONF ) if isinstance ( urlconf , types . ModuleType ) : urlconf = urlconf . __name__ caller = '' try : resolver_match = resolve ( request . path ) except Resolver404 : pass else : obj = resolver_match . func if hasattr ( obj , '__name__' ) : caller = obj . __name__ elif hasattr ( obj , '__class__' ) and hasattr ( obj . __class__ , '__name__' ) : caller = obj . __class__ . __name__ if hasattr ( obj , '__module__' ) : module = obj . __module__ caller = '%s.%s' % ( module , caller ) feincms_page = slug = template = None try : from leonardo . module . web . models import Page feincms_page = Page . objects . for_request ( request , best_match = True ) template = feincms_page . theme . template except : if Page . objects . exists ( ) : feincms_page = Page . objects . filter ( parent = None ) . first ( ) template = feincms_page . theme . template else : # nested path is not allowed for this time try : slug = request . path_info . split ( "/" ) [ - 2 : - 1 ] [ 0 ] except KeyError : raise Exception ( "Nested path is not allowed !" ) c = RequestContext ( request , { 'urlconf' : urlconf , 'root_urlconf' : settings . ROOT_URLCONF , 'request_path' : error_url , 'urlpatterns' : tried , 'reason' : force_bytes ( exception , errors = 'replace' ) , 'request' : request , 'settings' : get_safe_settings ( ) , 'raising_view_name' : caller , 'feincms_page' : feincms_page , 'template' : template or 'base.html' , 'standalone' : True , 'slug' : slug , } ) try : t = render_to_string ( '404_technical.html' , c ) except : from django . views . debug import TECHNICAL_404_TEMPLATE t = Template ( TECHNICAL_404_TEMPLATE ) . render ( c ) return HttpResponseNotFound ( t , content_type = 'text/html' ) | Create a technical 404 error response . The exception should be the Http404 . | 727 | 16 |
20,826 | 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 | 54 | 4 |
20,827 | def populate_items ( self , request ) : self . _items = self . get_items ( request ) return self . items | populate and returns filtered items | 27 | 6 |
20,828 | 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 | 58 | 4 |
20,829 | 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 | 72 | 5 |
20,830 | 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 | 63 | 6 |
20,831 | def get_item_template ( self ) : content_template = self . content_theme . name # _item.html is obsolete use _default.html # TODO: remove this condition after all _item.html will be converted if content_template == "default" : return "widget/%s/_item.html" % self . widget_name # TODO: support more template suffixes 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 | 108 | 40 |
20,832 | 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 | 49 | 12 |
20,833 | 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 | 39 | 16 |
20,834 | 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 | 36 | 39 |
20,835 | 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 ( dumped_data ) return data try : return json . loads ( self . cache_data ) except : return self . cache_data return self . get_data ( ) | load and cache data in json format | 138 | 7 |
20,836 | 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 | 76 | 8 |
20,837 | def _is_leonardo_module ( whatever ) : # check if is python module if hasattr ( whatever , 'default' ) or hasattr ( whatever , 'leonardo_module_conf' ) : return True # check if is python object for key in dir ( whatever ) : if 'LEONARDO' in key : return True | check if is leonardo module | 72 | 7 |
20,838 | def extract_conf_from ( mod , conf = ModuleConfig ( CONF_SPEC ) , depth = 0 , max_depth = 2 ) : # extract config keys from module or object for key , default_value in six . iteritems ( conf ) : conf [ key ] = _get_key_from_module ( mod , key , default_value ) # support for recursive dependecies try : filtered_apps = [ app for app in conf [ 'apps' ] if app not in BLACKLIST ] except TypeError : pass except Exception as e : warnings . warn ( 'Error %s during loading %s' % ( e , conf [ 'apps' ] ) ) for app in filtered_apps : try : app_module = import_module ( app ) if app_module != mod : app_module = _get_correct_module ( app_module ) if depth < max_depth : mod_conf = extract_conf_from ( app_module , depth = depth + 1 ) for k , v in six . iteritems ( mod_conf ) : # prevent config duplicity # skip config merge if k == 'config' : continue if isinstance ( v , dict ) : conf [ k ] . update ( v ) elif isinstance ( v , ( list , tuple ) ) : conf [ k ] = merge ( conf [ k ] , v ) except Exception as e : pass # swallow, but maybe log for info what happens return conf | recursively extract keys from module or object by passed config scheme | 306 | 13 |
20,839 | 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' ) : # use django behavior mod_path , _ , cls_name = mod . default_app_config . rpartition ( '.' ) _mod = import_module ( mod_path ) config_class = getattr ( _mod , cls_name ) # check if is leonardo config compliant if _is_leonardo_module ( config_class ) : mod = config_class return mod | returns imported module check if is leonardo_module_conf specified and then import them | 168 | 19 |
20,840 | def get_conf_from_module ( mod ) : conf = ModuleConfig ( CONF_SPEC ) # get imported module mod = _get_correct_module ( mod ) conf . set_module ( mod ) # extarct from default object or from module 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 | 99 | 11 |
20,841 | 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 ( request , '_feincms_extra_context' ) : request . _feincms_extra_context = { } request . path = leonardo_page . get_absolute_url ( ) request . frontend_editing = False leonardo_page . run_request_processors ( request ) request . LEONARDO_CONFIG = ContextConfig ( request ) handler = BaseHandler ( ) handler . load_middleware ( ) # Apply request middleware for middleware_method in handler . _request_middleware : try : middleware_method ( request ) except : pass # call processors for fn in reversed ( list ( leonardo_page . request_processors . values ( ) ) ) : fn ( leonardo_page , request ) return request | returns inicialized request | 262 | 6 |
20,842 | 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 | 79 | 8 |
20,843 | 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 ( _widgets , list ) : widgets = _widgets return load_widget_classes ( widgets ) | returns collected Leonardo Widgets | 118 | 6 |
20,844 | def render_region ( widget = None , request = None , view = None , page = None , region = None ) : # change the request 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 if widget else page render_region = widget . region if widget else region # call processors for fn in reversed ( list ( leonardo_page . request_processors . values ( ) ) ) : try : r = fn ( leonardo_page , request ) except : pass contents = { } for content in leonardo_page . content . all_of_type ( tuple ( leonardo_page . _feincms_content_types_with_process ) ) : try : r = content . process ( request , view = view ) except : pass else : # this is HttpResponse object or string if not isinstance ( r , six . string_types ) : r . render ( ) contents [ content . fe_identifier ] = getattr ( r , 'content' , r ) else : contents [ content . fe_identifier ] = r from leonardo . templatetags . leonardo_tags import _render_content region_content = '' . join ( contents [ content . fe_identifier ] if content . fe_identifier in contents else _render_content ( content , request = request , context = { } ) for content in getattr ( leonardo_page . content , render_region ) ) return region_content | returns rendered content this is not too clear and little tricky because external apps needs calling process method | 366 | 19 |
20,845 | 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 , 'feincms_item_editor_inline' ) : inline = content_type . feincms_item_editor_inline attrs [ 'form' ] = inline . form #if hasattr(content_type, 'feincms_item_editor_form'): # warnings.warn( # 'feincms_item_editor_form on %s is ignored because ' # 'feincms_item_editor_inline is set too' % content_type, # RuntimeWarning) else : inline = FeinCMSInline attrs [ 'form' ] = getattr ( content_type , 'feincms_item_editor_form' , inline . form ) name = '%sFeinCMSInline' % content_type . __name__ # TODO: We generate a new class every time. Is that really wanted? inline_class = type ( str ( name ) , ( inline , ) , attrs ) inlines . append ( inline_class ) return inlines | Generate genuine django inlines for registered content types . | 314 | 12 |
20,846 | 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 [ 'theme' ] = original . theme initial [ 'color_scheme' ] = original . color_scheme # optionaly translate title and make slug old_lang = translation . get_language ( ) translation . activate ( request . GET . get ( 'language' ) ) title = _ ( original . title ) if title != original . title : initial [ 'title' ] = title initial [ 'slug' ] = slugify ( title ) translation . activate ( old_lang ) return initial | Copy initial data from parent | 194 | 5 |
20,847 | def install_package ( package , upgrade = True , target = None ) : # Not using 'import pip; pip.main([])' because it breaks the logger 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' ) if target : args += [ '--target' , os . path . abspath ( target ) ] try : return subprocess . call ( args ) == 0 except subprocess . SubprocessError : _LOGGER . exception ( 'Unable to install pacakge %s' , package ) return False | Install a package on PyPi . Accepts pip compatible package strings . | 176 | 14 |
20,848 | def check_package_exists ( package , lib_dir ) : try : req = pkg_resources . Requirement . parse ( package ) except ValueError : # This is a zip file req = pkg_resources . Requirement . parse ( urlparse ( package ) . fragment ) # Check packages from lib dir if lib_dir is not None : if any ( dist in req for dist in pkg_resources . find_distributions ( lib_dir ) ) : return True # Check packages from global + virtual environment # pylint: disable=not-an-iterable return any ( dist in req for dist in pkg_resources . working_set ) | Check if a package is installed globally or in lib_dir . | 142 | 13 |
20,849 | 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 | 65 | 6 |
20,850 | 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 = region ) return JsonResponse ( { 'result' : result , 'region' : region } ) | Returns rendered region in JSON response | 102 | 6 |
20,851 | 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_content' : return self . render_widget ( request , widget_id ) if method == 'region' : return self . render_region ( request ) # handle methods called directly on widget if widget_id : widget = get_widget_from_id ( widget_id ) try : func = getattr ( widget , method ) except AttributeError : response [ "exception" ] = "%s method is not implmented on %s" % ( method , widget ) else : response [ "result" ] = func ( request ) elif class_name : # handle calling classmethod without instance try : cls = get_model ( * class_name . split ( '.' ) ) except Exception as e : response [ "exception" ] = str ( e ) return JsonResponse ( data = response ) if method == "render_preview" : # TODO: i think that we need only simple form # for loading relations but maybe this would be need it # custom_form_cls = getattr( # cls, 'feincms_item_editor_form', None) # if custom_form_cls: # FormCls = modelform_factory(cls, form=custom_form_cls, # exclude=('pk', 'id')) FormCls = modelform_factory ( cls , exclude = ( 'pk' , 'id' ) ) form = FormCls ( request . POST ) if form . is_valid ( ) : widget = cls ( * * form . cleaned_data ) request . frontend_editing = False try : content = widget . render ( * * { 'request' : request } ) except Exception as e : response [ 'result' ] = widget . handle_exception ( request , e ) else : response [ 'result' ] = content response [ 'id' ] = widget_id else : response [ 'result' ] = form . errors response [ 'id' ] = widget_id else : # standard method try : func = getattr ( cls , method ) except Exception as e : response [ "exception" ] = str ( e ) else : response [ "result" ] = func ( request ) return JsonResponse ( data = response ) | handle ajax methods and return serialized reponse in the default state allows only authentificated users | 572 | 21 |
20,852 | 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 . get ( 'class' , '' ) . split ( ) ) field_classes . add ( 'form-control' ) field . field . widget . attrs [ 'class' ] = ' ' . join ( field_classes ) return field | Add a form - control CSS class to the field s widget . | 135 | 13 |
20,853 | 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 : # Get folder folder = Folder . objects . get ( pk = folder_id ) except Folder . DoesNotExist : return HttpResponse ( json . dumps ( { 'error' : NO_FOLDER_ERROR } ) , * * response_params ) # check permissions if folder and not folder . has_add_children_permission ( request ) : return HttpResponse ( json . dumps ( { 'error' : NO_PERMISSIONS_FOR_FOLDER } ) , * * response_params ) try : if len ( request . FILES ) == 1 : # dont check if request is ajax or not, just grab the file upload , filename , is_raw = handle_request_files_upload ( request ) else : # else process the request as usual upload , filename , is_raw = handle_upload ( request ) # Get clipboad # TODO: Deprecated/refactor # clipboard = Clipboard.objects.get_or_create(user=request.user)[0] # find the file type for filer_class in media_settings . MEDIA_FILE_MODELS : FileSubClass = load_object ( filer_class ) # TODO: What if there are more than one that qualify? if FileSubClass . matches_file_type ( filename , upload , request ) : FileForm = modelform_factory ( model = FileSubClass , fields = ( 'original_filename' , 'owner' , 'file' ) ) break uploadform = FileForm ( { 'original_filename' : filename , 'owner' : request . user . pk } , { 'file' : upload } ) if uploadform . is_valid ( ) : file_obj = uploadform . save ( commit = False ) # Enforce the FILER_IS_PUBLIC_DEFAULT file_obj . is_public = settings . MEDIA_IS_PUBLIC_DEFAULT file_obj . folder = folder file_obj . save ( ) # TODO: Deprecated/refactor # clipboard_item = ClipboardItem( # clipboard=clipboard, file=file_obj) # clipboard_item.save() json_response = { 'thumbnail' : file_obj . icons [ '32' ] , 'alt_text' : '' , 'label' : str ( file_obj ) , 'file_id' : file_obj . pk , } return HttpResponse ( json . dumps ( json_response ) , * * response_params ) else : form_errors = '; ' . join ( [ '%s: %s' % ( field , ', ' . join ( errors ) ) for field , errors in list ( uploadform . errors . items ( ) ) ] ) raise UploadException ( "AJAX request not valid: form invalid '%s'" % ( form_errors , ) ) except UploadException as e : return HttpResponse ( json . dumps ( { 'error' : str ( e ) } ) , * * response_params ) | receives an upload from the uploader . Receives only one file at the time . | 724 | 19 |
20,854 | 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 | 82 | 8 |
20,855 | 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}' . format ( t . name . split ( '/' ) [ - 1 ] ) if static_path in path : try : page_theme = PageTheme . objects . get ( id = t . id ) except PageTheme . DoesNotExist : raise Exception ( "Run sync_themes before this command" ) except Exception as e : self . stdout . write ( "Cannot load {} into database original error: {}" . format ( t , e ) ) # find and load skins skins_path = os . path . join ( storage . path ( '/' . join ( path . split ( '/' ) [ 0 : - 1 ] ) ) ) for dirpath , skins , filenames in os . walk ( skins_path ) : for skin in [ s for s in skins if s not in [ 'fonts' ] ] : for skin_dirpath , skins , filenames in os . walk ( os . path . join ( dirpath , skin ) ) : skin , created = PageColorScheme . objects . get_or_create ( theme = page_theme , label = skin , name = skin . title ( ) ) for f in filenames : if 'styles' in f : with codecs . open ( os . path . join ( skin_dirpath , f ) ) as style_file : skin . styles = style_file . read ( ) elif 'variables' in f : with codecs . open ( os . path . join ( skin_dirpath , f ) ) as variables_file : skin . variables = variables_file . read ( ) skin . save ( ) self . skins_updated += 1 self . page_themes_updated += len ( page_themes ) | Load and save PageColorScheme for every PageTheme | 484 | 11 |
20,856 | 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 False | Return true if the current user has permission on this image . Return the string ALL if the user has all rights . | 84 | 23 |
20,857 | def get_template_data ( self , request , * args , * * kwargs ) : # little tricky with vertical centering 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 . get_directories ( request ) return data | Add image dimensions | 124 | 3 |
20,858 | 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_patterns' , [ ] ) : _decorate_urlconf ( pattern . url_patterns , decorator , * args , * * kwargs ) else : if getattr ( urlpatterns , 'callback' , None ) : urlpatterns . _callback = decorator ( urlpatterns . callback , * args , * * kwargs ) | Decorate all urlpatterns by specified decorator | 170 | 10 |
20,859 | def catch_result ( task_func ) : @ functools . wraps ( task_func , assigned = available_attrs ( task_func ) ) def dec ( * args , * * kwargs ) : # inicialize orig_stdout = sys . stdout sys . stdout = content = StringIO ( ) task_response = task_func ( * args , * * kwargs ) # catch sys . stdout = orig_stdout content . seek ( 0 ) # propagate to the response task_response [ 'stdout' ] = content . read ( ) return task_response return dec | Catch printed result from Celery Task and return it in task response | 130 | 14 |
20,860 | 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 . precompile = precompile compress_tags . CompressorMixin . render_compressed = render_compressed from django_pyscss import compressor as pyscss_compressor pyscss_compressor . DjangoScssFilter . input = input | patch all compress | 130 | 3 |
20,861 | 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 , forced ) return 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 . | 89 | 28 |
20,862 | 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_mimetypes . get ( mimetype ) if filter_or_command is None : if mimetype in ( "text/css" , "text/javascript" ) : return False , content raise CompressorError ( "Couldn't find any precompiler in " "COMPRESS_PRECOMPILERS setting for " "mimetype '%s'." % mimetype ) mod_name , cls_name = get_mod_func ( filter_or_command ) try : mod = import_module ( mod_name ) except ( ImportError , TypeError ) : filter = CachedCompilerFilter ( content = content , filter_type = self . type , filename = filename , charset = charset , command = filter_or_command , mimetype = mimetype ) return True , filter . input ( * * kwargs ) try : precompiler_class = getattr ( mod , cls_name ) except AttributeError : raise FilterDoesNotExist ( 'Could not find "%s".' % filter_or_command ) filter = precompiler_class ( content , attrs = attrs , filter_type = self . type , charset = charset , filename = filename , * * kwargs ) return True , filter . input ( * * kwargs ) | Processes file using a pre compiler . This is the place where files like coffee script are processed . | 381 | 20 |
20,863 | 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 . | 41 | 10 |
20,864 | 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 | 56 | 13 |
20,865 | 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 , created = cls . objects . get_or_create ( original_filename = file . name , file = file , folder = _folder , is_public = is_public ) if created : return obj return None | handle uploaded file to folder match first media type and create media object and returns it | 137 | 16 |
20,866 | 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 | 55 | 5 |
20,867 | 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 ( 'File not found %s' % path ) return server . serve ( request , file_obj = file_obj . file , save_as = False ) | Serve protected files to authenticated users with read permissions . | 127 | 11 |
20,868 | 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_read_permission ( request ) : if settings . DEBUG : raise PermissionDenied else : raise Http404 ( 'File not found %s' % path ) try : thumbnail = ThumbnailFile ( name = path , storage = file_obj . file . thumbnail_storage ) return thumbnail_server . serve ( request , thumbnail , save_as = False ) except Exception : raise Http404 ( 'File not found %s' % path ) | Serve protected thumbnails to authenticated users . If the user doesn t have read permissions redirect to a static image . | 187 | 23 |
20,869 | def get_app_modules ( self , apps ) : modules = getattr ( self , "_modules" , [ ] ) if not modules : from django . utils . module_loading import module_has_submodule # Try importing a modules from the module package package_string = '.' . join ( [ 'leonardo' , 'module' ] ) for app in apps : exc = '...' try : # check if is not full app _app = import_module ( app ) except Exception as e : _app = False exc = e if module_has_submodule ( import_module ( package_string ) , app ) or _app : if _app : mod = _app else : mod = import_module ( '.{0}' . format ( app ) , package_string ) if mod : modules . append ( mod ) continue warnings . warn ( '%s was skipped because %s ' % ( app , exc ) ) self . _modules = modules return self . _modules | return array of imported leonardo modules for apps | 211 | 10 |
20,870 | def urlpatterns ( self ) : if not hasattr ( self , '_urlspatterns' ) : urlpatterns = [ ] # load all urls # support .urls file and urls_conf = 'elephantblog.urls' on default module # decorate all url patterns if is not explicitly excluded for mod in leonardo . modules : # TODO this not work 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 , 'urlpatterns' ) : # if not public decorate all if conf [ 'public' ] : urlpatterns += urls_mod . urlpatterns else : _decorate_urlconf ( urls_mod . urlpatterns , require_auth ) urlpatterns += urls_mod . urlpatterns # avoid circural dependency # TODO use our loaded modules instead this property from django . conf import settings for urls_conf , conf in six . iteritems ( getattr ( settings , 'MODULE_URLS' , { } ) ) : # is public ? try : if conf [ 'is_public' ] : urlpatterns += patterns ( '' , url ( r'' , include ( urls_conf ) ) , ) else : _decorate_urlconf ( url ( r'' , include ( urls_conf ) ) , require_auth ) urlpatterns += patterns ( '' , url ( r'' , include ( urls_conf ) ) ) except Exception as e : raise Exception ( 'raised %s during loading %s' % ( str ( e ) , urls_conf ) ) self . _urlpatterns = urlpatterns return self . _urlpatterns | load and decorate urls from all modules then store it as cached property for less loading | 409 | 18 |
20,871 | 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 | 68 | 33 |
20,872 | 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 else : parts = viewname . split ( ':' ) parts . reverse ( ) view = parts [ 0 ] path = parts [ 1 : ] resolved_path = [ ] ns_pattern = '' while path : ns = path . pop ( ) # Lookup the name to see if it could be an app identifier try : app_list = resolver . app_dict [ ns ] # Yes! Path part matches an app in the current Resolver if current_app and current_app in app_list : # If we are reversing for a particular app, # use that namespace ns = current_app elif ns not in app_list : # The name isn't shared by one of the instances # (i.e., the default) so just pick the first instance # as the default. ns = app_list [ 0 ] except KeyError : pass try : extra , resolver = resolver . namespace_dict [ ns ] resolved_path . append ( ns ) ns_pattern = ns_pattern + extra except KeyError as key : for urlconf , config in six . iteritems ( ApplicationWidget . _feincms_content_models [ 0 ] . ALL_APPS_CONFIG ) : partials = viewname . split ( ':' ) app = partials [ 0 ] partials = partials [ 1 : ] # check if namespace is same as app name and try resolve if urlconf . split ( "." ) [ - 1 ] == app : try : return app_reverse ( ':' . join ( partials ) , urlconf , args = args , kwargs = kwargs , current_app = current_app ) except NoReverseMatch : pass if resolved_path : raise NoReverseMatch ( "%s is not a registered namespace inside '%s'" % ( key , ':' . join ( resolved_path ) ) ) else : raise NoReverseMatch ( "%s is not a registered namespace" % key ) if ns_pattern : resolver = get_ns_resolver ( ns_pattern , resolver ) return iri_to_uri ( resolver . _reverse_with_prefix ( view , prefix , * args , * * kwargs ) ) | monkey patched reverse | 564 | 3 |
20,873 | def add_page_if_missing ( request ) : try : page = Page . objects . for_request ( request , best_match = True ) return { 'leonardo_page' : page , # DEPRECATED 'feincms_page' : page , } except Page . DoesNotExist : return { } | Returns feincms_page for request . | 70 | 9 |
20,874 | 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 : slug = None try : body = render_to_string ( template , RequestContext ( request , { 'request_path' : request . path , 'feincms_page' : page , 'slug' : slug , 'standalone' : True } ) ) response = http . HttpResponseNotFound ( body , content_type = CONTENT_TYPE ) except TemplateDoesNotExist : response = False return response return False | return rendered template in standalone mode or False | 185 | 8 |
20,875 | 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 , { 'request_path' : request . path } ) ) return http . HttpResponseNotFound ( body , content_type = CONTENT_TYPE ) | Default 404 handler . | 122 | 4 |
20,876 | 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/html' ) return http . HttpResponseBadRequest ( template . render ( Context ( { } ) ) ) | 400 error handler . | 112 | 4 |
20,877 | 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 : # Drop our messages back into the session as per usual so they # don't disappear during the redirect. Not that we explicitly # use django's messages methods here. for tag , message , extra_tags in queued_msgs : getattr ( django_messages , tag ) ( request , message , extra_tags ) # if response['location'].startswith(settings.LOGOUT_URL): # redirect_response = http.HttpResponse(status=401) # # This header is used for handling the logout in JS # redirect_response['logout'] = True # if self.logout_reason is not None: # utils.add_logout_reason( # request, redirect_response, self.logout_reason) # else: redirect_response = http . HttpResponse ( ) # Use a set while checking if we want a cookie's attributes # copied cookie_keys = set ( ( 'max_age' , 'expires' , 'path' , 'domain' , 'secure' , 'httponly' , 'logout_reason' ) ) # Copy cookies from HttpResponseRedirect towards HttpResponse for cookie_name , cookie in six . iteritems ( response . cookies ) : cookie_kwargs = dict ( ( ( key , value ) for key , value in six . iteritems ( cookie ) if key in cookie_keys and value ) ) redirect_response . set_cookie ( cookie_name , cookie . value , * * cookie_kwargs ) redirect_response [ 'X-Horizon-Location' ] = response [ 'location' ] upload_url_key = 'X-File-Upload-URL' if upload_url_key in response : self . copy_headers ( response , redirect_response , ( upload_url_key , 'X-Auth-Token' ) ) return redirect_response if queued_msgs : # TODO(gabriel): When we have an async connection to the # client (e.g. websockets) this should be pushed to the # socket queue rather than being sent via a header. # The header method has notable drawbacks (length limits, # etc.) and is not meant as a long-term solution. response [ 'X-Horizon-Messages' ] = json . dumps ( queued_msgs ) return response | Convert HttpResponseRedirect to HttpResponse if request is via ajax to allow ajax request to redirect url | 562 | 27 |
20,878 | def process_exception ( self , request , exception ) : if isinstance ( exception , ( exceptions . NotAuthorized , exceptions . NotAuthenticated ) ) : auth_url = settings . LOGIN_URL next_url = None # prevent submiting forms after login and # use http referer if request . method in ( "POST" , "PUT" ) : referrer = request . META . get ( 'HTTP_REFERER' ) if referrer and is_safe_url ( referrer , request . get_host ( ) ) : next_url = referrer if not next_url : next_url = iri_to_uri ( request . get_full_path ( ) ) if next_url != auth_url : field_name = REDIRECT_FIELD_NAME else : field_name = None login_url = request . build_absolute_uri ( auth_url ) response = redirect_to_login ( next_url , login_url = login_url , redirect_field_name = field_name ) if isinstance ( exception , exceptions . NotAuthorized ) : logout_reason = _ ( "Unauthorized. Please try logging in again." ) utils . add_logout_reason ( request , response , logout_reason ) # delete messages, created in get_data() method # since we are going to redirect user to the login page response . delete_cookie ( 'messages' ) if request . is_ajax ( ) : response_401 = http . HttpResponse ( status = 401 ) response_401 [ 'X-Horizon-Location' ] = response [ 'location' ] return response_401 return response # If an internal "NotFound" error gets this far, return a real 404. if isinstance ( exception , exceptions . NotFound ) : raise http . Http404 ( exception ) if isinstance ( exception , exceptions . Http302 ) : # TODO(gabriel): Find a way to display an appropriate message to # the user *on* the login form... return shortcuts . redirect ( exception . location ) | Catches internal Horizon exception classes such as NotAuthorized NotFound and Http302 and handles them gracefully . | 448 | 23 |
20,879 | 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 ( filer_file . url ) | Redirect to the current url of a public file | 109 | 10 |
20,880 | 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 . | 66 | 32 |
20,881 | 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 | 70 | 11 |
20,882 | 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 | 66 | 7 |
20,883 | 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 | 76 | 6 |
20,884 | 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 | 59 | 6 |
20,885 | 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 except ValueError : enable_fe = False if enable_fe : response . set_cookie ( str ( 'frontend_editing' ) , enable_fe ) clear_cache ( ) else : response . delete_cookie ( str ( 'frontend_editing' ) ) clear_cache ( ) else : response . delete_cookie ( str ( 'frontend_editing' ) ) # Redirect to cleanup URLs return response | Sets the frontend editing state in the cookie depending on the frontend_editing GET parameter and the user s permissions . | 185 | 26 |
20,886 | 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 | 85 | 6 |
20,887 | def get_property ( self , key ) : _key = DJANGO_CONF [ key ] return getattr ( self , _key , CONF_SPEC [ _key ] ) | Expect Django Conf property | 40 | 5 |
20,888 | 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 . | 66 | 10 |
20,889 | 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 | 81 | 3 |
20,890 | 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' , 'django.template.loaders.filesystem.Loader' , ) : loader_class = getattr ( import_module ( module ) , klass ) if getattr ( loader_class , '_accepts_engine_in_init' , False ) : loader = loader_class ( Engine . get_default ( ) ) else : loader = loader_class ( ) for dir in loader . get_template_sources ( '' ) : for root , dirnames , filenames in os . walk ( dir ) : for basename in filenames : if ignore_private and basename . startswith ( "_" ) : continue filename = os . path . join ( root , basename ) rel_filename = filename [ len ( dir ) + 1 : ] if fnmatch . fnmatch ( filename , pattern ) or fnmatch . fnmatch ( basename , pattern ) or fnmatch . fnmatch ( rel_filename , pattern ) : templates . append ( rel_filename ) else : LOGGER . debug ( '%s is not supported' % loader_name ) return sorted ( set ( templates ) ) | Finds all Django templates matching given glob in all TEMPLATE_LOADERS | 335 | 17 |
20,891 | 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 . | 51 | 16 |
20,892 | def seek ( self , offset , whence = os . SEEK_SET ) : self . wrapped . seek ( offset , whence ) | Sets the file s current position . | 27 | 8 |
20,893 | 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 . | 47 | 8 |
20,894 | 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 . | 85 | 8 |
20,895 | 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 ) if '?' in url : fmt = '{0}&_ts={1}' else : fmt = '{0}?_ts={1}' return fmt . format ( url , image . created_at . strftime ( '%Y%m%d%H%M%S%f' ) ) | Gets the URL of the given image . | 155 | 9 |
20,896 | 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 . | 49 | 10 |
20,897 | 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 . | 33 | 12 |
20,898 | def locate ( self , store = current_store ) : if not isinstance ( store , Store ) : raise TypeError ( 'store must be an instance of ' 'sqlalchemy_imageattach.store.Store, not ' + repr ( store ) ) return store . locate ( self ) | Gets the URL of the image from the store . | 61 | 11 |
20,899 | def _original_images ( self , * * kwargs ) : def test ( image ) : if not image . original : return False for filter , value in kwargs . items ( ) : if getattr ( image , filter ) != value : return False return True if Session . object_session ( self . instance ) is None : images = [ ] for image , store in self . _stored_images : if test ( image ) : images . append ( image ) state = instance_state ( self . instance ) try : added = state . committed_state [ self . attr . key ] . added_items except KeyError : pass else : for image in added : if test ( image ) : images . append ( image ) if self . session : for image in self . session . new : if test ( image ) : images . append ( image ) else : query = self . filter_by ( original = True , * * kwargs ) images = query . all ( ) return images | A list of the original images . | 210 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.