idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
52,200 | def send ( self , request , queryset ) : send_outward_mails . delay ( queryset ) messages . info ( request , _ ( 'Message sent successfully' ) , fail_silently = True ) | Send action available in change outward list |
52,201 | def post ( self , request , * args , ** kwargs ) : try : self . get_object ( ** kwargs ) except Http404 : return Response ( { 'detail' : _ ( 'Not Found' ) } , status = 404 ) if not self . is_contactable ( ) : return Response ( { 'detail' : _ ( 'This resource cannot be contacted' ) } , status = 400 ) content_type = ContentType . objects . only ( 'id' , 'model' ) . get ( model = self . content_type ) data = request . data message = Inward ( ) message . content_type = content_type message . object_id = self . recipient . id message . message = data . get ( 'message' ) if request . user . is_authenticated ( ) : message . user = request . user else : message . from_name = data . get ( 'from_name' ) message . from_email = data . get ( 'from_email' ) message . ip = request . META . get ( 'REMOTE_ADDR' , '' ) message . user_agent = request . META . get ( 'HTTP_USER_AGENT' , '' ) message . accept_language = request . META . get ( 'HTTP_ACCEPT_LANGUAGE' , '' ) try : message . full_clean ( ) except ValidationError , e : return Response ( e . message_dict , status = 400 ) message . save ( ) if message . status >= 1 : return Response ( { 'details' : _ ( 'Message sent successfully' ) } , status = 201 ) else : return Response ( { 'details' : _ ( 'Something went wrong. The email was not sent.' ) } , status = 500 ) | Contact node owner . |
52,202 | def get ( self , request , * args , ** kwargs ) : serializer = self . serializer_reader_class if request . user . is_authenticated ( ) : return Response ( serializer ( request . user , context = self . get_serializer_context ( ) ) . data ) else : return Response ( { 'detail' : _ ( 'Authentication credentials were not provided' ) } , status = 401 ) | return profile of current user if authenticated otherwise 401 |
52,203 | def post ( self , request , format = None ) : serializer_class = self . get_serializer_class ( ) serializer = serializer_class ( data = request . data , instance = request . user ) if serializer . is_valid ( ) : serializer . save ( ) return Response ( { 'detail' : _ ( u'Password successfully changed' ) } ) return Response ( serializer . errors , status = 400 ) | validate password change operation and return result |
52,204 | def retrieve_data ( self ) : url = self . config . get ( 'url' ) timeout = float ( self . config . get ( 'timeout' , 10 ) ) self . data = requests . get ( url , verify = self . verify_ssl , timeout = timeout ) . content | retrieve data from an HTTP URL |
52,205 | def get_text ( item , tag , default = False ) : try : xmlnode = item . getElementsByTagName ( tag ) [ 0 ] . firstChild except IndexError as e : if default is not False : return default else : raise IndexError ( e ) if xmlnode is not None : return unicode ( xmlnode . nodeValue ) else : return '' | returns text content of an xml tag |
52,206 | def _convert_item ( self , item ) : item = self . parse_item ( item ) if not item [ 'name' ] : raise Exception ( 'Expected property %s not found in item %s.' % ( self . keys [ 'name' ] , item ) ) elif len ( item [ 'name' ] ) > 75 : item [ 'name' ] = item [ 'name' ] [ : 75 ] if not item [ 'status' ] : item [ 'status' ] = self . default_status try : item [ 'status' ] = Status . objects . get ( slug__iexact = item [ 'status' ] ) except Status . DoesNotExist : try : item [ 'status' ] = Status . objects . create ( name = item [ 'status' ] , slug = slugify ( item [ 'status' ] ) , description = item [ 'status' ] , is_default = False ) except Exception as e : logger . exception ( e ) item [ 'status' ] = None item [ 'slug' ] = slugify ( item [ 'name' ] ) if not item [ 'address' ] : item [ 'address' ] = '' if not item [ 'is_published' ] : item [ 'is_published' ] = '' User = get_user_model ( ) try : item [ 'user' ] = User . objects . get ( username = item [ 'user' ] ) except User . DoesNotExist : item [ 'user' ] = None if not item [ 'elev' ] : item [ 'elev' ] = None if not item [ 'description' ] : item [ 'description' ] = '' if not item [ 'notes' ] : item [ 'notes' ] = '' if item [ 'added' ] : try : item [ 'added' ] = parser . parse ( item [ 'added' ] ) except Exception as e : print "Exception while parsing 'added' date: %s" % e if item [ 'updated' ] : try : item [ 'updated' ] = parser . parse ( item [ 'updated' ] ) except Exception as e : print "Exception while parsing 'updated' date: %s" % e result = { "name" : item [ 'name' ] , "slug" : item [ 'slug' ] , "status" : item [ 'status' ] , "address" : item [ 'address' ] , "is_published" : item [ 'is_published' ] , "user" : item [ 'user' ] , "geometry" : item [ 'geometry' ] , "elev" : item [ 'elev' ] , "description" : item [ 'description' ] , "notes" : item [ 'notes' ] , "added" : item [ 'added' ] , "updated" : item [ 'updated' ] , "data" : { } } for key , value in item [ 'data' ] . items ( ) : result [ "data" ] [ key ] = value return result | take a parsed item as input and returns a python dictionary the keys will be saved into the Node model either in their respective fields or in the hstore data field |
52,207 | def get_queryset ( self ) : return self . queryset . all ( ) . accessible_to ( user = self . request . user ) | Returns only objects which are accessible to the current user . If user is not authenticated all public objects will be returned . |
52,208 | def patch ( self , request , * args , ** kwargs ) : with reversion . create_revision ( ) : reversion . set_user ( request . user ) reversion . set_comment ( 'changed through the RESTful API from ip %s' % request . META [ 'REMOTE_ADDR' ] ) kwargs [ 'partial' ] = True return self . update ( request , * args , ** kwargs ) | custom patch method to support django - reversion |
52,209 | def save ( self , * args , ** kwargs ) : adding_new = False if not self . pk or ( not self . cpu and not self . ram ) : if self . model . cpu : self . cpu = self . model . cpu if self . model . ram : self . ram = self . model . ram adding_new = True super ( DeviceToModelRel , self ) . save ( * args , ** kwargs ) try : antenna_model = self . model . antennamodel except AntennaModel . DoesNotExist : antenna_model = False if adding_new and antenna_model : antenna = Antenna ( device = self . device , model = self . model . antennamodel ) wireless_interfaces = self . device . interface_set . filter ( type = 2 ) if len ( wireless_interfaces ) > 0 : antenna . radio = wireless_interfaces [ 0 ] antenna . save ( ) | when creating a new record fill CPU and RAM info if available |
52,210 | def clean ( self , * args , ** kwargs ) : if self . from_user and self . from_user_id == self . to_user_id : raise ValidationError ( _ ( 'A user cannot send a notification to herself/himself' ) ) | from_user and to_user must differ |
52,211 | def save ( self , * args , ** kwargs ) : created = self . pk is None if self . check_user_settings ( medium = 'web' ) : super ( Notification , self ) . save ( * args , ** kwargs ) if created : self . send_notifications ( ) | custom save method to send email and push notification |
52,212 | def send_email ( self ) : if self . check_user_settings ( ) : send_mail ( _ ( self . type ) , self . email_message , settings . DEFAULT_FROM_EMAIL , [ self . to_user . email ] ) return True else : return False | send email notification according to user settings |
52,213 | def check_user_settings ( self , medium = 'email' ) : if self . type == 'custom' : return True try : user_settings = getattr ( self . to_user , '%s_notification_settings' % medium ) except ObjectDoesNotExist : return False user_setting_type = getattr ( user_settings . __class__ , self . type ) . user_setting_type if user_setting_type == 'boolean' : return getattr ( user_settings , self . type , True ) elif user_setting_type == 'distance' : value = getattr ( user_settings , self . type , 0 ) if value is 0 : return True elif value < 0 : return False else : Model = self . related_object . __class__ geo_field = getattr ( user_settings . __class__ , self . type ) . geo_field geo_value = getattr ( self . related_object , geo_field ) km = value * 1000 queryset = Model . objects . filter ( ** { "user_id" : self . to_user_id , geo_field + "__distance_lte" : ( geo_value , km ) } ) return queryset . count ( ) >= 1 | Ensure user is ok with receiving this notification through the specified medium . Available mediums are web and email while mobile notifications will hopefully be implemented in the future . |
52,214 | def email_message ( self ) : url = settings . SITE_URL hello_text = __ ( "Hi %s," % self . to_user . get_full_name ( ) ) action_text = __ ( "\n\nMore details here: %s" ) % url explain_text = __ ( "This is an automatic notification sent from from %s.\n" "If you want to stop receiving this notification edit your" "email notification settings here: %s" ) % ( settings . SITE_NAME , 'TODO' ) return "%s\n\n%s%s\n\n%s" % ( hello_text , self . text , action_text , explain_text ) | compose complete email message text |
52,215 | def generate_key ( self , email ) : salt = sha1 ( str ( random ( ) ) ) . hexdigest ( ) [ : 5 ] return sha1 ( salt + email ) . hexdigest ( ) | Generate a new email confirmation key and return it . |
52,216 | def create_emailconfirmation ( self , email_address ) : "Create an email confirmation obj from the given email address obj" confirmation_key = self . generate_key ( email_address . email ) confirmation = self . create ( email_address = email_address , created_at = now ( ) , key = confirmation_key , ) return confirmation | Create an email confirmation obj from the given email address obj |
52,217 | def user_loggedin ( sender , ** kwargs ) : values = { 'value' : 1 , 'path' : kwargs [ 'request' ] . path , 'user_id' : str ( kwargs [ 'user' ] . pk ) , 'username' : kwargs [ 'user' ] . username , } write ( 'user_logins' , values = values ) | collect metrics about user logins |
52,218 | def user_deleted ( sender , ** kwargs ) : if kwargs . get ( 'created' ) : write ( 'user_variations' , { 'variation' : 1 } , tags = { 'action' : 'created' } ) write ( 'user_count' , { 'total' : User . objects . count ( ) } ) | collect metrics about new users signing up |
52,219 | def _node_rating_count ( self ) : try : return self . noderatingcount except ObjectDoesNotExist : node_rating_count = NodeRatingCount ( node = self ) node_rating_count . save ( ) return node_rating_count | Return node_rating_count record or create it if it does not exist |
52,220 | def _node_participation_settings ( self ) : try : return self . node_participation_settings except ObjectDoesNotExist : node_participation_settings = NodeParticipationSettings ( node = self ) node_participation_settings . save ( ) return node_participation_settings | Return node_participation_settings record or create it if it does not exist |
52,221 | def _action_allowed ( self , action ) : if getattr ( self . layer . participation_settings , '{0}_allowed' . format ( action ) ) is False : return False else : return getattr ( self . participation_settings , '{0}_allowed' . format ( action ) ) | participation actions can be disabled on layer level or disabled on a per node basis |
52,222 | def create_node_rating_counts_settings ( sender , ** kwargs ) : created = kwargs [ 'created' ] node = kwargs [ 'instance' ] if created : create_related_object . delay ( NodeRatingCount , { 'node' : node } ) create_related_object . delay ( NodeParticipationSettings , { 'node' : node } ) | create node rating count and settings |
52,223 | def create_layer_rating_settings ( sender , ** kwargs ) : created = kwargs [ 'created' ] layer = kwargs [ 'instance' ] if created : create_related_object . delay ( LayerParticipationSettings , { 'layer' : layer } ) | create layer rating settings |
52,224 | def needs_confirmation ( self ) : if EMAIL_CONFIRMATION : self . is_active = False self . save ( ) return True else : return False | set is_active to False if needs email confirmation |
52,225 | def change_password ( self , new_password ) : self . set_password ( new_password ) self . save ( ) password_changed . send ( sender = self . __class__ , user = self ) | Changes password and sends a signal |
52,226 | def add_notifications ( myclass ) : for key , value in TEXTS . items ( ) : if 'custom' in [ key , value ] : continue field_type = USER_SETTING [ key ] [ 'type' ] if field_type == 'boolean' : field = models . BooleanField ( _ ( key ) , default = DEFAULT_BOOLEAN ) elif field_type == 'distance' : field = models . IntegerField ( _ ( key ) , default = DEFAULT_DISTANCE , help_text = _ ( '-1 (less than 0): disabled; 0: enabled for all;\ 1 (less than 0): enabled for those in the specified distance range (km)' ) ) field . geo_field = USER_SETTING [ key ] [ 'geo_field' ] field . name = field . column = field . attname = key field . user_setting_type = field_type setattr ( myclass , key , field ) myclass . add_to_class ( key , field ) return myclass | Decorator which adds fields dynamically to User Notification Settings models . |
52,227 | def validate ( self , attrs ) : user = authenticate ( ** self . user_credentials ( attrs ) ) if user : if user . is_active : self . instance = user else : raise serializers . ValidationError ( _ ( "This account is currently inactive." ) ) else : error = _ ( "Invalid login credentials." ) raise serializers . ValidationError ( error ) return attrs | checks if login credentials are correct |
52,228 | def get_details ( self , obj ) : return reverse ( 'api_user_social_links_detail' , args = [ obj . user . username , obj . pk ] , request = self . context . get ( 'request' ) , format = self . context . get ( 'format' ) ) | return detail url |
52,229 | def get_location ( self , obj ) : if not obj . city and not obj . country : return None elif obj . city and obj . country : return '%s, %s' % ( obj . city , obj . country ) elif obj . city or obj . country : return obj . city or obj . country | return user s location |
52,230 | def validate_current_password ( self , value ) : if self . instance and self . instance . has_usable_password ( ) and not self . instance . check_password ( value ) : raise serializers . ValidationError ( _ ( 'Current password is not correct' ) ) return value | current password check |
52,231 | def create_for_user ( self , user ) : if type ( user ) is unicode : from . profile import Profile as User user = User . objects . get ( email = user ) temp_key = token_generator . make_token ( user ) password_reset = PasswordReset ( user = user , temp_key = temp_key ) password_reset . save ( ) subject = _ ( "Password reset email sent" ) message = render_to_string ( "profiles/email_messages/password_reset_key_message.txt" , { "user" : user , "uid" : int_to_base36 ( user . id ) , "temp_key" : temp_key , "site_url" : settings . SITE_URL , "site_name" : settings . SITE_NAME } ) send_mail ( subject , message , settings . DEFAULT_FROM_EMAIL , [ user . email ] ) return password_reset | create password reset for specified user |
52,232 | def handle ( self , * args , ** options ) : self . options = options delete = False try : self . stdout . write ( '\r\n' ) self . verbosity = int ( self . options . get ( 'verbosity' ) ) self . verbose ( 'disabling signals (notififcations, websocket alerts)' ) pause_disconnectable_signals ( ) self . check_status_mapping ( ) self . retrieve_nodes ( ) self . extract_users ( ) self . import_admins ( ) self . import_users ( ) self . import_nodes ( ) self . check_deleted_nodes ( ) self . import_devices ( ) self . import_interfaces ( ) self . import_links ( ) self . check_deleted_links ( ) self . import_contacts ( ) self . confirm_operation_completed ( ) resume_disconnectable_signals ( ) self . verbose ( 're-enabling signals (notififcations, websocket alerts)' ) except KeyboardInterrupt : self . message ( '\n\nOperation cancelled...' ) delete = True except Exception as e : tb = traceback . format_exc ( ) delete = True transaction . rollback ( ) self . message ( 'Got exception:\n\n%s' % tb ) error ( 'import_old_nodeshot: %s' % e ) if delete : self . delete_imported_data ( ) | execute synchronize command |
52,233 | def check_status_mapping ( self ) : self . verbose ( 'checking status mapping...' ) if not self . status_mapping : self . message ( 'no status mapping found' ) return for old_val , new_val in self . status_mapping . iteritems ( ) : try : if isinstance ( new_val , basestring ) : lookup = { 'slug' : new_val } else : lookup = { 'pk' : new_val } status = Status . objects . get ( ** lookup ) self . status_mapping [ old_val ] = status . id except Status . DoesNotExist : raise ImproperlyConfigured ( 'Error! Status with slug %s not found in the database' % new_val ) self . verbose ( 'status map correct' ) | ensure status map does not contain status values which are not present in DB |
52,234 | def retrieve_nodes ( self ) : self . verbose ( 'retrieving nodes from old mysql DB...' ) self . old_nodes = list ( OldNode . objects . all ( ) ) self . message ( 'retrieved %d nodes' % len ( self . old_nodes ) ) | retrieve nodes from old mysql DB |
52,235 | def extract_users ( self ) : email_set = set ( ) users_dict = { } self . verbose ( 'going to extract user information from retrieved nodes...' ) for node in self . old_nodes : email_set . add ( node . email ) if node . email not in users_dict : users_dict [ node . email ] = { 'owner' : node . owner } self . email_set = email_set self . users_dict = users_dict self . verbose ( '%d users extracted' % len ( email_set ) ) | extract user info |
52,236 | def import_admins ( self ) : self . message ( 'saving admins into local DB' ) saved_admins = [ ] for olduser in OldUser . objects . all ( ) : try : user = User . objects . get ( Q ( username = olduser . username ) | Q ( email = olduser . email ) ) except User . DoesNotExist : user = User ( ) except User . MultipleObjectsReturned : continue user . username = olduser . username user . password = olduser . password user . first_name = olduser . first_name user . last_name = olduser . last_name user . email = olduser . email user . is_active = olduser . is_active user . is_staff = olduser . is_staff user . is_superuser = olduser . is_superuser user . date_joined = olduser . date_joined user . full_clean ( ) user . save ( sync_emailaddress = False ) saved_admins . append ( user ) if EMAIL_CONFIRMATION and EmailAddress . objects . filter ( email = user . email ) . count ( ) is 0 : try : email_address = EmailAddress ( user = user , email = user . email , verified = True , primary = True ) email_address . full_clean ( ) email_address . save ( ) except Exception : tb = traceback . format_exc ( ) self . message ( 'Could not save email address for user %s, got exception:\n\n%s' % ( user . username , tb ) ) self . message ( 'saved %d admins into local DB' % len ( saved_admins ) ) self . saved_admins = saved_admins | save admins to local DB |
52,237 | def import_users ( self ) : self . message ( 'saving users into local DB' ) saved_users = self . saved_admins for email in self . email_set : owner = self . users_dict [ email ] . get ( 'owner' ) if owner . strip ( ) == '' : owner , domain = email . split ( '@' ) owner = owner . replace ( '.' , ' ' ) if ' ' in owner : owner_parts = owner . split ( ' ' ) first_name = owner_parts [ 0 ] last_name = owner_parts [ 1 ] else : first_name = owner last_name = '' username = slugify ( owner ) try : user = User . objects . get ( email = email ) except User . DoesNotExist : user = User ( ) user . username = username user . password = self . generate_random_password ( ) user . is_active = True user . first_name = first_name . capitalize ( ) user . last_name = last_name . capitalize ( ) user . email = email oldest_node = OldNode . objects . filter ( email = email ) . order_by ( 'added' ) [ 0 ] user . date_joined = oldest_node . added counter = 1 original_username = username while True : if not user . pk and User . objects . filter ( username = user . username ) . count ( ) > 0 : counter += 1 user . username = '%s%d' % ( original_username , counter ) else : break try : user . full_clean ( ) user . save ( sync_emailaddress = False ) except Exception : if ( User . objects . filter ( email = email ) . count ( ) == 1 ) : user = User . objects . get ( email = email ) else : tb = traceback . format_exc ( ) self . message ( 'Could not save user %s, got exception:\n\n%s' % ( user . username , tb ) ) continue if user : self . users_dict [ email ] [ 'id' ] = user . id saved_users . append ( user ) self . verbose ( 'Saved user %s (%s) with email <%s>' % ( user . username , user . get_full_name ( ) , user . email ) ) if EMAIL_CONFIRMATION and EmailAddress . objects . filter ( email = user . email ) . count ( ) is 0 : try : email_address = EmailAddress ( user = user , email = user . email , verified = True , primary = True ) email_address . full_clean ( ) email_address . save ( ) except Exception : tb = traceback . format_exc ( ) self . message ( 'Could not save email address for user %s, got exception:\n\n%s' % ( user . username , tb ) ) self . message ( 'saved %d users into local DB' % len ( saved_users ) ) self . saved_users = saved_users | save users to local DB |
52,238 | def check_deleted_nodes ( self ) : imported_nodes = Node . objects . filter ( data__contains = [ 'imported' ] ) deleted_nodes = [ ] for node in imported_nodes : if OldNode . objects . filter ( pk = node . pk ) . count ( ) == 0 : user = node . user deleted_nodes . append ( node ) node . delete ( ) if user . node_set . count ( ) == 0 : user . delete ( ) if len ( deleted_nodes ) > 0 : self . message ( 'deleted %d imported nodes from local DB' % len ( deleted_nodes ) ) self . deleted_nodes = deleted_nodes | delete imported nodes that are not present in the old database |
52,239 | def create_settings ( sender , ** kwargs ) : created = kwargs [ 'created' ] user = kwargs [ 'instance' ] if created : UserWebNotificationSettings . objects . create ( user = user ) UserEmailNotificationSettings . objects . create ( user = user ) | create user notification settings on user creation |
52,240 | def parse ( self ) : try : self . parsed_data = json . loads ( self . data ) except UnicodeError as e : self . parsed_data = json . loads ( self . data . decode ( 'latin1' ) ) except Exception as e : raise Exception ( 'Error while converting response from JSON to python. %s' % e ) if self . parsed_data . get ( 'type' , '' ) != 'FeatureCollection' : raise Exception ( 'GeoJson synchronizer expects a FeatureCollection object at root level' ) self . parsed_data = self . parsed_data [ 'features' ] | parse geojson and ensure is collection |
52,241 | def retrieve_old_notifications ( self ) : date = ago ( days = DELETE_OLD ) return Notification . objects . filter ( added__lte = date ) | Retrieve notifications older than X days where X is specified in settings |
52,242 | def push_changes_to_external_layers ( node , external_layer , operation ) : from nodeshot . core . nodes . models import Node if not isinstance ( node , basestring ) : node = Node . objects . get ( pk = node . pk ) synchronizer = import_by_path ( external_layer . synchronizer_path ) instance = synchronizer ( external_layer . layer ) if hasattr ( instance , operation ) : getattr ( instance , operation ) ( node ) | Sync other applications through their APIs by performing updates adds or deletes . This method is designed to be performed asynchronously avoiding blocking the user when he changes data on the local DB . |
52,243 | def send_message ( message , pipe = 'public' ) : if pipe not in [ 'public' , 'private' ] : raise ValueError ( 'pipe argument can be only "public" or "private"' ) else : pipe = pipe . upper ( ) pipe_path = PUBLIC_PIPE if pipe == 'PUBLIC' else PRIVATE_PIPE pipeout = open ( pipe_path , 'a' ) pipeout . write ( '%s\n' % message ) pipeout . close ( ) | writes message to pipe |
52,244 | def create_user ( backend , details , response , uid , username , user = None , * args , ** kwargs ) : if user : return { 'user' : user } if not username : return None email = details . get ( 'email' ) original_email = None if not email : message = _ ( ) raise AuthFailed ( backend , message ) if email and len ( email ) > 75 : original_email = email email = '' return { 'user' : UserSocialAuth . create_user ( username = username , email = email , sync_emailaddress = False ) , 'original_email' : original_email , 'is_new' : True } | Creates user . Depends on get_username pipeline . |
52,245 | def load_extra_data ( backend , details , response , uid , user , social_user = None , * args , ** kwargs ) : social_user = social_user or UserSocialAuth . get_social_auth ( backend . name , uid ) if kwargs [ 'is_new' ] and EMAIL_CONFIRMATION : from . . models import EmailAddress if EmailAddress . objects . filter ( email = user . email ) . count ( ) < 1 : EmailAddress . objects . create ( user = user , email = user . email , verified = True , primary = True ) if social_user : extra_data = backend . extra_data ( user , uid , response , details ) if kwargs . get ( 'original_email' ) and 'email' not in extra_data : extra_data [ 'email' ] = kwargs . get ( 'original_email' ) if extra_data and social_user . extra_data != extra_data : if social_user . extra_data : social_user . extra_data . update ( extra_data ) else : social_user . extra_data = extra_data social_user . save ( ) if backend . name == 'facebook' and kwargs [ 'is_new' ] : response = json . loads ( requests . get ( 'https://graph.facebook.com/%s?access_token=%s' % ( extra_data [ 'id' ] , extra_data [ 'access_token' ] ) ) . content ) try : user . city , user . country = response . get ( 'hometown' ) . get ( 'name' ) . split ( ', ' ) except ( AttributeError , TypeError ) : pass try : user . birth_date = datetime . strptime ( response . get ( 'birthday' ) , '%m/%d/%Y' ) . date ( ) except ( AttributeError , TypeError ) : pass user . save ( ) return { 'social_user' : social_user } | Load extra data from provider and store it on current UserSocialAuth extra_data field . |
52,246 | def send ( self ) : if self . content_type . name == 'node' : to = [ self . to . user . email ] elif self . content_type . name == 'layer' : to = [ self . to . email ] for mantainer in self . to . mantainers . all ( ) . only ( 'email' ) : to += [ mantainer . email ] else : to = [ self . to . email ] context = { 'sender_name' : self . from_name , 'sender_email' : self . from_email , 'message' : self . message , 'site' : settings . SITE_NAME , 'object_type' : self . content_type . name , 'object_name' : str ( self . to ) } message = render_to_string ( 'mailing/inward_message.txt' , context ) email = EmailMessage ( _ ( 'Contact request from %(sender_name)s - %(site)s' ) % context , message , settings . DEFAULT_FROM_EMAIL , to , headers = { 'Reply-To' : self . from_email } ) import socket try : email . send ( ) self . status = 1 except socket . error as e : import logging log = logging . getLogger ( __name__ ) error_msg = 'nodeshot.community.mailing.models.inward.send(): %s' % e log . error ( error_msg ) self . status = - 1 | Sends the email to the recipient If the sending fails will set the status of the instance to error and will log the error according to your project s django - logging configuration |
52,247 | def slice ( self , order_by = 'pk' , n = None ) : if n is not None and n < 0 : raise ValueError ( 'slice parameter cannot be negative' ) queryset = self . order_by ( order_by ) if n is None : return queryset [ 0 ] else : return queryset [ 0 : n ] | return n objects according to specified ordering |
52,248 | def access_level_up_to ( self , access_level ) : if isinstance ( access_level , int ) : value = access_level else : value = ACCESS_LEVELS . get ( access_level ) return self . filter ( access_level__lte = value ) | returns all items that have an access level equal or lower than the one specified |
52,249 | def save ( self , * args , ** kwargs ) : ignore_default_check = kwargs . pop ( 'ignore_default_check' , False ) if self . is_default != self . _current_is_default and self . is_default is True : for status in self . __class__ . objects . filter ( is_default = True ) : status . is_default = False status . save ( ignore_default_check = True ) super ( Status , self ) . save ( * args , ** kwargs ) if self . __class__ . objects . filter ( is_default = True ) . count ( ) == 0 and not ignore_default_check : self . is_default = True self . save ( ) self . _current_is_default = self . is_default | intercepts changes to is_default |
52,250 | def ready ( self ) : from . models import LayerExternal from nodeshot . core . layers . views import LayerNodeListMixin def get_nodes ( self , request , * args , ** kwargs ) : try : external = self . layer . external except LayerExternal . DoesNotExist : external = False if external and self . layer . is_external and hasattr ( external , 'get_nodes' ) : return external . get_nodes ( self . __class__ . __name__ , request . query_params ) else : return ( self . list ( request , * args , ** kwargs ) ) . data LayerNodeListMixin . get_nodes = get_nodes | patch LayerNodesList view to support external layers |
52,251 | def init_celery ( project_name ) : os . environ . setdefault ( 'DJANGO_SETTINGS_MODULE' , '%s.settings' % project_name ) app = Celery ( project_name ) app . config_from_object ( 'django.conf:settings' ) app . autodiscover_tasks ( settings . INSTALLED_APPS , related_name = 'tasks' ) return app | init celery app without the need of redundant code |
52,252 | def send ( self ) : if self . status is OUTWARD_STATUS . get ( 'sent' ) : return False recipients = self . get_recipients ( ) emails = [ ] if OUTWARD_HTML : html_content = self . message EmailClass = EmailMultiAlternatives else : EmailClass = EmailMessage message = strip_tags ( self . message ) for recipient in recipients : msg = EmailClass ( self . subject , message , settings . DEFAULT_FROM_EMAIL , [ recipient ] , ) if OUTWARD_HTML : msg . attach_alternative ( html_content , "text/html" ) emails . append ( msg ) try : counter = 0 for email in emails : if counter == OUTWARD_STEP : counter = 0 time . sleep ( OUTWARD_DELAY ) email . send ( ) counter += 1 except socket . error as e : from logging import error error ( 'nodeshot.core.mailing.models.outward.send(): %s' % e ) self . status = OUTWARD_STATUS . get ( 'error' ) self . status = OUTWARD_STATUS . get ( 'sent' ) self . save ( ) | Sends the email to the recipients |
52,253 | def add_validation_method ( cls , method ) : method_name = method . func_name cls . _additional_validation . append ( method_name ) setattr ( cls , method_name , method ) | Extend validation of Node by adding a function to the _additional_validation list . The additional validation function will be called by the clean method |
52,254 | def point ( self ) : if not self . geometry : raise ValueError ( 'geometry attribute must be set before trying to get point property' ) if self . geometry . geom_type == 'Point' : return self . geometry else : try : return self . geometry . point_on_surface except GEOSException : return self . geometry . centroid | returns location of node . If node geometry is not a point a center point will be returned |
52,255 | def perform_create ( self , serializer ) : if serializer . instance is None : serializer . save ( user = self . request . user ) | determine user when node is added |
52,256 | def get_queryset ( self ) : queryset = super ( NodeList , self ) . get_queryset ( ) . select_related ( 'status' , 'user' , 'layer' ) search = self . request . query_params . get ( 'search' , None ) layers = self . request . query_params . get ( 'layers' , None ) if search is not None : search_query = ( Q ( name__icontains = search ) | Q ( slug__icontains = search ) | Q ( description__icontains = search ) | Q ( address__icontains = search ) ) queryset = queryset . filter ( search_query ) if layers is not None : queryset = queryset . filter ( Q ( layer__slug__in = layers . split ( ',' ) ) ) return queryset | Optionally restricts the returned nodes by filtering against a search query parameter in the URL . |
52,257 | def create_notifications ( users , notification_model , notification_type , related_object ) : Notification = notification_model additional = related_object . __dict__ if related_object else '' notification_text = TEXTS [ notification_type ] % additional for user in users : n = Notification ( to_user = user , type = notification_type , text = notification_text ) if related_object : n . related_object = related_object n . save ( ) | create notifications in a background job to avoid slowing down users |
52,258 | def save ( self , * args , ** kwargs ) : self . type = INTERFACE_TYPES . get ( 'ethernet' ) super ( Ethernet , self ) . save ( * args , ** kwargs ) | automatically set Interface . type to ethernet |
52,259 | def root_endpoint ( request , format = None ) : endpoints = [ ] for urlmodule in urlpatterns : if hasattr ( urlmodule , 'urlconf_module' ) : is_urlconf_module = True else : is_urlconf_module = False if is_urlconf_module : for url in urlmodule . urlconf_module . urlpatterns : if url . name in [ 'django.swagger.resources.view' ] : continue try : endpoints . append ( { 'name' : url . name . replace ( 'api_' , '' ) , 'url' : reverse ( url . name , request = request , format = format ) } ) except NoReverseMatch : pass return Response ( endpoints ) | List of all the available resources of this RESTful API . |
52,260 | def update_count ( self ) : node_rating_count = self . node . rating_count node_rating_count . comment_count = self . node . comment_set . count ( ) node_rating_count . save ( ) | updates comment count |
52,261 | def clean ( self , * args , ** kwargs ) : if not self . pk : node = self . node if node . participation_settings . comments_allowed is False : raise ValidationError ( "Comments not allowed for this node" ) if 'nodeshot.core.layers' in settings . INSTALLED_APPS : layer = node . layer if layer . participation_settings . comments_allowed is False : raise ValidationError ( "Comments not allowed for this layer" ) | Check if comments can be inserted for parent node or parent layer |
52,262 | def retrieve_layers ( self , * args , ** options ) : queryset = Q ( ) if len ( args ) < 1 : all_layers = Layer . objects . published ( ) . external ( ) if options [ 'exclude' ] : exclude_list = options [ 'exclude' ] . replace ( ' ' , '' ) . split ( ',' ) return all_layers . exclude ( slug__in = exclude_list ) else : self . verbose ( 'no layer specified, will retrieve all layers!' ) return all_layers for layer_slug in args : queryset = queryset | Q ( slug = layer_slug ) try : layer = Layer . objects . get ( slug = layer_slug ) if not layer . is_external : raise CommandError ( 'Layer "%s" is not an external layer\n\r' % layer_slug ) if not layer . is_published : raise CommandError ( 'Layer "%s" is not published. Why are you trying to work on an unpublished layer?\n\r' % layer_slug ) except Layer . DoesNotExist : raise CommandError ( 'Layer "%s" does not exist\n\r' % layer_slug ) return Layer . objects . published ( ) . external ( ) . select_related ( ) . filter ( queryset ) | Retrieve specified layers or all external layers if no layer specified . |
52,263 | def handle ( self , * args , ** options ) : self . verbosity = int ( options . get ( 'verbosity' ) ) self . stdout . write ( '\r\n' ) layers = self . retrieve_layers ( * args , ** options ) if len ( layers ) < 1 : self . stdout . write ( 'no layers to process\n\r' ) return else : self . verbose ( 'going to process %d layers...' % len ( layers ) ) for layer in layers : try : synchronizer_path = layer . external . synchronizer_path except ( ObjectDoesNotExist , AttributeError ) : self . stdout . write ( 'External Layer %s does not have a synchronizer class specified\n\r' % layer . name ) continue if synchronizer_path == 'None' : self . stdout . write ( 'External Layer %s does not have a synchronizer class specified\n\r' % layer . name ) continue if layer . external . config is None : self . stdout . write ( 'Layer %s does not have a config yet\n\r' % layer . name ) continue synchronizer = import_by_path ( synchronizer_path ) self . stdout . write ( 'imported module %s\r\n' % synchronizer . __name__ ) try : instance = synchronizer ( layer , verbosity = self . verbosity ) self . stdout . write ( 'Processing layer "%s"\r\n' % layer . slug ) messages = instance . sync ( ) except ImproperlyConfigured as e : self . stdout . write ( 'Validation error: %s\r\n' % e ) continue except Exception as e : self . stdout . write ( 'Got Exception: %s\r\n' % e ) exception ( e ) continue for message in messages : self . stdout . write ( '%s\n\r' % message ) self . stdout . write ( '\r\n' ) | execute sync command |
52,264 | def save_external_nodes ( sender , ** kwargs ) : node = kwargs [ 'instance' ] operation = 'add' if kwargs [ 'created' ] is True else 'change' if node . layer . is_external is False or not hasattr ( node . layer , 'external' ) or node . layer . external . synchronizer_path is None : return False push_changes_to_external_layers . delay ( node = node , external_layer = node . layer . external , operation = operation ) | sync by creating nodes in external layers when needed |
52,265 | def delete_external_nodes ( sender , ** kwargs ) : node = kwargs [ 'instance' ] if node . layer . is_external is False or not hasattr ( node . layer , 'external' ) or node . layer . external . synchronizer_path is None : return False if hasattr ( node , 'external' ) and node . external . external_id : push_changes_to_external_layers . delay ( node = node . external . external_id , external_layer = node . layer . external , operation = 'delete' ) | sync by deleting nodes from external layers when needed |
52,266 | def save ( self , * args , ** kwargs ) : if not self . pk : old_votes = Vote . objects . filter ( user = self . user , node = self . node ) for old_vote in old_votes : old_vote . delete ( ) super ( Vote , self ) . save ( * args , ** kwargs ) | ensure users cannot vote the same node multiple times but let users change their votes |
52,267 | def update_count ( self ) : node_rating_count = self . node . rating_count node_rating_count . likes = self . node . vote_set . filter ( vote = 1 ) . count ( ) node_rating_count . dislikes = self . node . vote_set . filter ( vote = - 1 ) . count ( ) node_rating_count . save ( ) | updates likes and dislikes count |
52,268 | def clean ( self , * args , ** kwargs ) : if not self . pk : if self . node . participation_settings . voting_allowed is not True : raise ValidationError ( "Voting not allowed for this node" ) if 'nodeshot.core.layers' in settings . INSTALLED_APPS : layer = self . node . layer if layer . participation_settings . voting_allowed is not True : raise ValidationError ( "Voting not allowed for this layer" ) | Check if votes can be inserted for parent node or parent layer |
52,269 | def get_queryset ( self ) : queryset = super ( DeviceList , self ) . get_queryset ( ) search = self . request . query_params . get ( 'search' , None ) if search is not None : search_query = ( Q ( name__icontains = search ) | Q ( description__icontains = search ) ) queryset = queryset . filter ( search_query ) return queryset | Optionally restricts the returned devices by filtering against a search query parameter in the URL . |
52,270 | def save ( self , * args , ** kwargs ) : auto_update = kwargs . get ( 'auto_update' , True ) if auto_update : self . updated = now ( ) if 'auto_update' in kwargs : kwargs . pop ( 'auto_update' ) super ( BaseDate , self ) . save ( * args , ** kwargs ) | automatically update updated date field |
52,271 | def save ( self , * args , ** kwargs ) : if self . order == '' or self . order is None : try : self . order = self . get_auto_order_queryset ( ) . order_by ( "-order" ) [ 0 ] . order + 1 except IndexError : self . order = 0 super ( BaseOrdered , self ) . save ( ) | if order left blank |
52,272 | def check_dependencies ( dependencies , module ) : if type ( dependencies ) == str : dependencies = [ dependencies ] elif type ( dependencies ) != list : raise TypeError ( 'dependencies argument must be of type list or string' ) for dependency in dependencies : if dependency not in settings . INSTALLED_APPS : raise DependencyError ( '%s depends on %s, which should be in settings.INSTALLED_APPS' % ( module , dependency ) ) | Ensure dependencies of a module are listed in settings . INSTALLED_APPS |
52,273 | def get_key_by_value ( dictionary , search_value ) : for key , value in dictionary . iteritems ( ) : if value == search_value : return ugettext ( key ) | searchs a value in a dicionary and returns the key of the first occurrence |
52,274 | def get_layer ( self ) : if self . layer : return try : self . layer = Layer . objects . get ( slug = self . kwargs [ 'slug' ] ) except Layer . DoesNotExist : raise Http404 ( _ ( 'Layer not found' ) ) | retrieve layer from DB |
52,275 | def get_queryset ( self ) : self . get_layer ( ) return super ( LayerNodeListMixin , self ) . get_queryset ( ) . filter ( layer_id = self . layer . id ) | extend parent class queryset by filtering nodes of the specified layer |
52,276 | def get ( self , request , * args , ** kwargs ) : self . get_layer ( ) nodes = self . get_nodes ( request , * args , ** kwargs ) return Response ( nodes ) | Retrieve list of nodes of the specified layer |
52,277 | def save ( self , * args , ** kwargs ) : self . protocol = 'ipv%d' % self . address . version super ( Ip , self ) . save ( * args , ** kwargs ) | Determines ip protocol version automatically . Stores address in interface shortcuts for convenience . |
52,278 | def allow_relation ( self , obj1 , obj2 , ** hints ) : if obj1 . _meta . app_label != 'oldimporter' and obj2 . _meta . app_label != 'oldimporter' : return True return None | Relations between objects are allowed between nodeshot2 objects only |
52,279 | def allow_migrate ( self , db , model ) : if db != 'old_nodeshot' or model . _meta . app_label != 'oldimporter' : return False return True | Make sure the old_nodeshot app only appears in the old_nodeshot database |
52,280 | def metric_details ( request , pk , format = None ) : metric = get_object_or_404 ( Metric , pk = pk ) if request . method == 'GET' : try : results = metric . select ( q = request . query_params . get ( 'q' , metric . query ) ) except InfluxDBClientError as e : return Response ( { 'detail' : e . content } , status = e . code ) return Response ( list ( results . get_points ( metric . name ) ) ) else : if not request . data : return Response ( { 'detail' : 'expected values in POST data or JSON payload' } , status = 400 ) data = request . data . copy ( ) if request . content_type != 'application/json' : for key , value in data . items ( ) : try : data [ key ] = float ( value ) if '.' in value else int ( value ) except ValueError : pass metric . write ( data ) return Response ( { 'detail' : 'ok' } ) | Get or write metric values |
52,281 | def add_client ( self , user_id = None ) : if user_id is None : self . channel = 'public' user_id = uuid . uuid1 ( ) . hex else : self . channel = 'private' self . id = user_id self . channels [ self . channel ] [ self . id ] = self print 'Client connected to the %s channel.' % self . channel | Adds current instance to public or private channel . If user_id is specified it will be added to the private channel If user_id is not specified it will be added to the public one instead . |
52,282 | def broadcast ( cls , message ) : clients = cls . get_clients ( ) for id , client in clients . iteritems ( ) : client . send_message ( message ) | broadcast message to all connected clients |
52,283 | def send_private_message ( self , user_id , message ) : try : client = self . channels [ 'private' ] [ str ( user_id ) ] except KeyError : print '====debug====' print self . channels [ 'private' ] print 'client with id %s not found' % user_id return False client . send_message ( message ) print 'message sent to client #%s' % user_id return True | Send a message to a specific client . Returns True if successful False otherwise |
52,284 | def get_clients ( self ) : public = self . channels [ 'public' ] private = self . channels [ 'private' ] return dict ( public . items ( ) + private . items ( ) ) | return a merge of public and private clients |
52,285 | def open ( self ) : print 'Connection opened.' user_id = self . get_argument ( "user_id" , None ) self . add_client ( user_id ) self . send_message ( "Welcome to nodeshot websocket server." ) client_count = len ( self . get_clients ( ) . keys ( ) ) new_client_message = 'New client connected, now we have %d %s!' % ( client_count , 'client' if client_count <= 1 else 'clients' ) self . broadcast ( new_client_message ) print self . channels [ 'private' ] | method which is called every time a new client connects |
52,286 | def on_close ( self ) : print 'Connection closed.' self . remove_client ( ) client_count = len ( self . get_clients ( ) . keys ( ) ) new_client_message = '1 client disconnected, now we have %d %s!' % ( client_count , 'client' if client_count <= 1 else 'clients' ) self . broadcast ( new_client_message ) | method which is called every time a client disconnects |
52,287 | def create_database ( ) : db = get_db ( ) response = db . query ( 'SHOW DATABASES' ) items = list ( response . get_points ( 'databases' ) ) databases = [ database [ 'name' ] for database in items ] if settings . INFLUXDB_DATABASE not in databases : db . create_database ( settings . INFLUXDB_DATABASE ) print ( 'Created inlfuxdb database {0}' . format ( settings . INFLUXDB_DATABASE ) ) | creates database if necessary |
52,288 | def save ( self , * args , ** kwargs ) : if not self . pk : old_ratings = Rating . objects . filter ( user = self . user , node = self . node ) for old_rating in old_ratings : old_rating . delete ( ) super ( Rating , self ) . save ( * args , ** kwargs ) | ensure users cannot rate the same node multiple times but let users change their rating |
52,289 | def update_count ( self ) : node_rating_count = self . node . rating_count node_rating_count . rating_count = self . node . rating_set . count ( ) node_rating_count . rating_avg = self . node . rating_set . aggregate ( rate = Avg ( 'value' ) ) [ 'rate' ] if node_rating_count . rating_avg is None : node_rating_count . rating_avg = 0 node_rating_count . save ( ) | updates rating count and rating average |
52,290 | def clean ( self , * args , ** kwargs ) : if not self . pk : node = self . node layer = Layer . objects . get ( pk = node . layer_id ) if layer . participation_settings . rating_allowed is not True : raise ValidationError ( "Rating not allowed for this layer" ) if node . participation_settings . rating_allowed is not True : raise ValidationError ( "Rating not allowed for this node" ) | Check if rating can be inserted for parent node or parent layer |
52,291 | def save ( self , * args , ** kwargs ) : created = type ( self . pk ) is not int super ( UpdateCountsMixin , self ) . save ( * args , ** kwargs ) if created : self . update_count ( ) | custom save method to update counts |
52,292 | def delete ( self , * args , ** kwargs ) : super ( UpdateCountsMixin , self ) . delete ( * args , ** kwargs ) self . update_count ( ) | custom delete method to update counts |
52,293 | def update_topology ( ) : for topology in Topology . objects . all ( ) : try : topology . update ( ) except Exception as e : msg = 'Failed to update {}' . format ( topology . __repr__ ( ) ) logger . exception ( msg ) print ( '{0}: {1}\n' 'see networking.log for more information\n' . format ( msg , e . __class__ ) ) | updates all the topology sends logs to the nodeshot . networking logger |
52,294 | def backend_class ( self ) : if not self . backend : return None if not self . __backend_class : self . __backend_class = self . _get_netengine_backend ( ) return self . __backend_class | returns python netengine backend class importing it if needed |
52,295 | def netengine ( self ) : if not self . backend : return None if not self . __netengine : NetengineBackend = self . backend_class arguments = self . _build_netengine_arguments ( ) self . __netengine = NetengineBackend ( ** arguments ) return self . __netengine | access netengine instance |
52,296 | def _validate_backend ( self ) : try : self . backend_class except ( ImportError , AttributeError ) as e : raise ValidationError ( _ ( 'No valid backend found, got the following python exception: "%s"' ) % e ) | ensure backend string representation is correct |
52,297 | def _validate_config ( self ) : if not self . backend : return if len ( self . REQUIRED_CONFIG_KEYS ) < 1 : return self . config = self . config or { } required_keys_set = set ( self . REQUIRED_CONFIG_KEYS ) config_keys_set = set ( self . config . keys ( ) ) missing_required_keys = required_keys_set - config_keys_set unrecognized_keys = config_keys_set - required_keys_set if len ( missing_required_keys ) > 0 : missing_keys_string = ', ' . join ( missing_required_keys ) raise ValidationError ( _ ( 'Missing required config keys: "%s"' ) % missing_keys_string ) elif len ( unrecognized_keys ) > 0 : unrecognized_keys_string = ', ' . join ( unrecognized_keys ) raise ValidationError ( _ ( 'Unrecognized config keys: "%s"' ) % unrecognized_keys_string ) | ensure REQUIRED_CONFIG_KEYS are filled |
52,298 | def _validate_duplicates ( self ) : if not self . id : duplicates = [ ] self . netengine_dict = self . netengine . to_dict ( ) for interface in self . netengine_dict [ 'interfaces' ] : if interface [ 'mac_address' ] in duplicates : continue if Interface . objects . filter ( mac__iexact = interface [ 'mac_address' ] ) . count ( ) > 0 : duplicates . append ( interface [ 'mac_address' ] ) if len ( duplicates ) > 0 : mac_address_string = ', ' . join ( duplicates ) raise ValidationError ( _ ( 'interfaces with the following mac addresses already exist: %s' ) % mac_address_string ) | Ensure we re not creating a device that already exists Runs only when the DeviceConnector object is created not when is updated |
52,299 | def _get_netengine_arguments ( self , required = False ) : backend_class = self . _get_netengine_backend ( ) argspec = inspect . getargspec ( backend_class . __init__ ) args = argspec . args for argument_name in [ 'self' , 'host' , 'port' ] : args . remove ( argument_name ) if required : default_values = list ( argspec . defaults ) default_values = default_values [ 0 : - 1 ] args = args [ 0 : len ( args ) - len ( default_values ) ] return args | returns list of available config params returns list of required config params if required is True for internal use only |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.