text stringlengths 81 112k |
|---|
return list of open 311 services
def get(self, request, *args, **kwargs):
""" return list of open 311 services """
# init django rest framework specific stuff
serializer_class = self.get_serializer_class()
context = self.get_serializer_context()
# init empty list
servi... |
Return the serializer instance that should be used for validating and
deserializing input, and for serializing output.
def get_serializer(self, instance=None, data=None,
many=False, partial=False):
"""
Return the serializer instance that should be used for validating and
... |
Retrieve list of service requests
def get(self, request, *args, **kwargs):
""" Retrieve list of service requests """
if 'service_code' not in request.GET.keys():
return Response({ 'detail': _('A service code must be inserted') }, status=404)
service_code = request.GET['service_code... |
Post a service request (requires authentication)
def post(self, request, *args, **kwargs):
""" Post a service request (requires authentication) """
service_code = request.data['service_code']
if service_code not in SERVICES.keys():
return Response({ 'detail': _('Service not found')... |
Add user info to ExtensibleNodeSerializer
def ready(self):
""" Add user info to ExtensibleNodeSerializer """
from nodeshot.core.nodes.base import ExtensibleNodeSerializer
from .models import Vote
from .serializers import (CommentRelationSerializer,
Part... |
send notification when a new node is created according to users's settings
def node_created_handler(sender, **kwargs):
""" send notification when a new node is created according to users's settings """
if kwargs['created']:
obj = kwargs['instance']
queryset = exclude_owner_of_node(obj)
... |
send notification when the status of a node changes according to users's settings
def node_status_changed_handler(**kwargs):
""" send notification when the status of a node changes according to users's settings """
obj = kwargs['instance']
obj.old_status = kwargs['old_status'].name
obj.new_status = kwa... |
shortcut to netdiff.diff
def diff(self):
""" shortcut to netdiff.diff """
latest = self.latest
current = NetJsonParser(self.json())
return diff(current, latest) |
returns a dict that represents a NetJSON NetworkGraph object
def json(self):
""" returns a dict that represents a NetJSON NetworkGraph object """
nodes = []
links = []
for link in self.link_set.all():
if self.is_layer2:
source = link.interface_a.mac
... |
Updates topology
Links are not deleted straightaway but set as "disconnected"
def update(self):
"""
Updates topology
Links are not deleted straightaway but set as "disconnected"
"""
from .link import Link # avoid circular dependency
diff = self.diff()
s... |
Call self.synchronizer.clean method
def clean(self, *args, **kwargs):
"""
Call self.synchronizer.clean method
"""
if self.synchronizer_path != 'None' and self.config:
# call synchronizer custom clean
try:
self.synchronizer.load_config(self.config)... |
call synchronizer "after_external_layer_saved" method
for any additional operation that must be executed after save
def save(self, *args, **kwargs):
"""
call synchronizer "after_external_layer_saved" method
for any additional operation that must be executed after save
"""
... |
access synchronizer
def synchronizer(self):
""" access synchronizer """
if not self.synchronizer_path or self.synchronizer_path == 'None' or not self.layer:
return False
# ensure data is up to date
if (self._synchronizer is not None and self._synchronizer_class.__name__ not ... |
returns synchronizer class
def synchronizer_class(self):
""" returns synchronizer class """
if not self.synchronizer_path or self.synchronizer_path == 'None' or not self.layer:
return False
# ensure data is up to date
if (self._synchronizer_class is not None and self._synchr... |
returns true if user has permission to edit, false otherwise
def get_can_edit(self, obj):
""" returns true if user has permission to edit, false otherwise """
view = self.context.get('view')
request = copy(self.context.get('request'))
request._method = 'PUT'
try:
vie... |
returns uri of API image resource
def get_details(self, obj):
""" returns uri of API image resource """
args = {
'slug': obj.node.slug,
'pk': obj.pk
}
return reverse('api_node_image_detail',
kwargs=args,
request=self.... |
parse data
def parse(self):
""" parse data """
super(GeoRss, self).parse()
# support RSS and ATOM
tag_name = 'item' if '<item>' in self.data else 'entry'
self.parsed_data = self.parsed_data.getElementsByTagName(tag_name) |
applies to social-link-list
def has_permission(self, request, view):
""" applies to social-link-list """
if request.method == 'POST':
user = Profile.objects.only('id', 'username').get(username=view.kwargs['username'])
return request.user.id == user.id
return True |
delete image when an image record is deleted
def delete(self, *args, **kwargs):
""" delete image when an image record is deleted """
try:
os.remove(self.file.file.name)
# image does not exist
except (OSError, IOError):
pass
super(Image, self).delete(*args... |
used to determine color of links
def get_quality(self, type='etx'):
""" used to determine color of links"""
if type == 'etx':
if 0 < self.etx < 1.5:
quality = 1
elif self.etx < 3:
quality = 2
else:
quality = 3
eli... |
ensure new nodes are allowed for this layer
def new_nodes_allowed_for_layer(self):
"""
ensure new nodes are allowed for this layer
"""
if not self.pk and self.layer and not self.layer.new_nodes_allowed:
raise ValidationError(_('New nodes are not allowed for this layer')) |
if minimum distance is specified, ensure node is not too close to other nodes;
def nodes_minimum_distance_validation(self):
"""
if minimum distance is specified, ensure node is not too close to other nodes;
"""
if self.layer and self.layer.nodes_minimum_distance:
minimum_distance = self.layer.n... |
if layer defines an area, ensure node coordinates are contained in the area
def node_contained_in_layer_area_validation(self):
"""
if layer defines an area, ensure node coordinates are contained in the area
"""
# if area is a polygon ensure it contains the node
if self.layer and isinstance(self.lay... |
intercepts changes to is_published and fires layer_is_published_changed signal
def save(self, *args, **kwargs):
"""
intercepts changes to is_published and fires layer_is_published_changed signal
"""
super(Layer, self).save(*args, **kwargs)
# if is_published of an existing layer... |
publish or unpublish nodes of current layer
def update_nodes_published(self):
""" publish or unpublish nodes of current layer """
if self.pk:
self.node_set.all().update(is_published=self.is_published) |
get HTTP method
def get(self, request, format=None):
""" get HTTP method """
action = request.query_params.get('action', 'unread')
# action can be only "unread" (default), "count" and "all"
action = action if action == 'count' or action == 'all' else 'unread'
# mark as read para... |
return unread notifications and mark as read
(unless read=false param is passed)
def get_unread(self, request, notifications, mark_as_read):
"""
return unread notifications and mark as read
(unless read=false param is passed)
"""
notifications = notifications.filter(is_r... |
return count of unread notification
def get_count(self, request, notifications, mark_as_read=False):
""" return count of unread notification """
return Response({'count': notifications.filter(is_read=False).count()}) |
return all notifications with pagination
def get_all(self, request, notifications, mark_as_read=False):
""" return all notifications with pagination """
return self.list(request, notifications) |
get privacy settings of current user
def get_object(self, queryset=None):
""" get privacy settings of current user """
try:
obj = self.get_queryset()
except self.model.DoesNotExist:
raise Http404()
self.check_object_permissions(self.request, obj)
return o... |
Custom validation
1. interface_a and interface_b mandatory except for planned links
2. planned links should have at least node_a and node_b filled in
3. dbm and noise fields can be filled only for radio links
4. interface_a and interface_b must differ
5. inter... |
Custom save does the following:
* determine link type if not specified
* automatically fill 'node_a' and 'node_b' fields if necessary
* draw line between two nodes
* fill shortcut properties node_a_name and node_b_name
def save(self, *args, **kwargs):
"""
... |
Find link between source and target, (or vice versa, order is irrelevant).
:param source: ip or mac addresses
:param target: ip or mac addresses
:param topology: optional topology relation
:returns: Link object
:raises: LinkNotFound
def get_link(cls, source, target, topology=Non... |
Tries to find a link with get_link, creates a new link if link not found.
def get_or_create(cls, source, target, cost, topology=None):
"""
Tries to find a link with get_link, creates a new link if link not found.
"""
try:
return cls.get_link(source, target, topology)
... |
ensure link properties correspond to the specified ones
perform save operation only if necessary
def ensure(self, status, cost):
"""
ensure link properties correspond to the specified ones
perform save operation only if necessary
"""
changed = False
status_id = L... |
Send action available in change outward list
def send(self, request, queryset):
"""
Send action available in change outward list
"""
send_outward_mails.delay(queryset)
# show message in the admin
messages.info(request, _('Message sent successfully'), fail_silently=True) |
Contact node owner.
def post(self, request, *args, **kwargs):
"""
Contact node owner.
"""
try:
self.get_object(**kwargs)
except Http404:
return Response({'detail': _('Not Found')}, status=404)
if not self.is_contactable():
return Resp... |
return profile of current user if authenticated otherwise 401
def get(self, request, *args, **kwargs):
""" return profile of current user if authenticated otherwise 401 """
serializer = self.serializer_reader_class
if request.user.is_authenticated():
return Response(serializer(reque... |
authenticate
def post(self, request, format=None):
""" authenticate """
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
login(request, serializer.instance)
if request.data.get('remember'):
# TODO: remember configurable
... |
validate password change operation and return result
def post(self, request, format=None):
""" validate password change operation and return result """
serializer_class = self.get_serializer_class()
serializer = serializer_class(data=request.data, instance=request.user)
if serializer.i... |
This is the method that does everything automatically (at least attempts to).
Steps:
0. Call "before_start" method (which might be implemented by children classes)
1. Retrieve data from external source
2. Parse the data
3. Save the data locally
4. Cal... |
retrieve data from an HTTP URL
def retrieve_data(self):
""" retrieve data from an HTTP URL """
# shortcuts for readability
url = self.config.get('url')
timeout = float(self.config.get('timeout', 10))
# perform HTTP request and store content
self.data = requests.get(url, ... |
returns text content of an xml tag
def get_text(item, tag, default=False):
""" returns text content of an xml tag """
try:
xmlnode = item.getElementsByTagName(tag)[0].firstChild
except IndexError as e:
if default is not False:
return default
e... |
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
:param item: object representing parsed item
def _convert_item(self, item):
"""
take a parsed item as input and... |
save data into DB:
1. save new (missing) data
2. update only when needed
3. delete old data
4. generate report that will be printed
constraints:
* ensure new nodes do not take a name/slug which is already used
* validate through django before saving
... |
Returns only objects which are accessible to the current user.
If user is not authenticated all public objects will be returned.
Model must implement AccessLevelManager!
def get_queryset(self):
"""
Returns only objects which are accessible to the current user.
If user is not au... |
custom put method to support django-reversion
def put(self, request, *args, **kwargs):
""" custom put method to support django-reversion """
with reversion.create_revision():
reversion.set_user(request.user)
reversion.set_comment('changed through the RESTful API from ip %s' % re... |
custom patch method to support django-reversion
def patch(self, request, *args, **kwargs):
""" custom patch method to support django-reversion """
with reversion.create_revision():
reversion.set_user(request.user)
reversion.set_comment('changed through the RESTful API from ip %s... |
custom put method to support django-reversion
def post(self, request, *args, **kwargs):
""" custom put method to support django-reversion """
with reversion.create_revision():
reversion.set_user(request.user)
reversion.set_comment('created through the RESTful API from ip %s' % r... |
when creating a new record fill CPU and RAM info if available
def save(self, *args, **kwargs):
""" when creating a new record fill CPU and RAM info if available """
adding_new = False
if not self.pk or (not self.cpu and not self.ram):
# if self.model.cpu is not empty
if ... |
disconnect signals
def disconnect():
""" disconnect signals """
post_save.disconnect(node_created_handler, sender=Node)
node_status_changed.disconnect(node_status_changed_handler)
pre_delete.disconnect(node_deleted_handler, sender=Node) |
reconnect signals
def reconnect():
""" reconnect signals """
post_save.connect(node_created_handler, sender=Node)
node_status_changed.connect(node_status_changed_handler)
pre_delete.connect(node_deleted_handler, sender=Node) |
from_user and to_user must differ
def clean(self, *args, **kwargs):
""" from_user and to_user must differ """
if self.from_user and self.from_user_id == self.to_user_id:
raise ValidationError(_('A user cannot send a notification to herself/himself')) |
custom save method to send email and push notification
def save(self, *args, **kwargs):
"""
custom save method to send email and push notification
"""
created = self.pk is None
# save notification to database only if user settings allow it
if self.check_user_settings(me... |
send email notification according to user settings
def send_email(self):
""" send email notification according to user settings """
# send only if user notification setting is set to true
if self.check_user_settings():
send_mail(_(self.type), self.email_message, settings.DEFAULT_FRO... |
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.
def check_user_settings(self, medium='email'):
"""
Ensure user is ok with receiving this no... |
compose complete email message text
def email_message(self):
""" compose complete email message text """
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 a... |
parse data
def parse(self):
""" parse data """
super(OpenWisp, self).parse()
self.parsed_data = self.parsed_data.getElementsByTagName('item') |
Generate a new email confirmation key and return it.
def generate_key(self, email):
"""
Generate a new email confirmation key and return it.
"""
salt = sha1(str(random())).hexdigest()[:5]
return sha1(salt + email).hexdigest() |
Create an email confirmation obj from the given email address obj
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_addres... |
collect metrics about user logins
def user_loggedin(sender, **kwargs):
""" collect metrics about user logins """
values = {
'value': 1,
'path': kwargs['request'].path,
'user_id': str(kwargs['user'].pk),
'username': kwargs['user'].username,
}
write('user_logins', values=v... |
collect metrics about new users signing up
def user_deleted(sender, **kwargs):
""" collect metrics about new users signing up """
if kwargs.get('created'):
write('user_variations', {'variation': 1}, tags={'action': 'created'})
write('user_count', {'total': User.objects.count()}) |
Return node_rating_count record
or create it if it does not exist
usage:
node = Node.objects.get(pk=1)
node.rating_count
def _node_rating_count(self):
"""
Return node_rating_count record
or create it if it does not exist
usage:
node = Node.objects.get(pk=1)
node.rating_count
... |
Return node_participation_settings record
or create it if it does not exist
usage:
node = Node.objects.get(pk=1)
node.participation_settings
def _node_participation_settings(self):
"""
Return node_participation_settings record
or create it if it does not exist
usage:
node = Node.o... |
participation actions can be disabled on layer level, or disabled on a per node basis
def _action_allowed(self, action):
"""
participation actions can be disabled on layer level, or disabled on a per node basis
"""
if getattr(self.layer.participation_settings, '{0}_allowed'.format(action)) is False:
... |
create node rating count and settings
def create_node_rating_counts_settings(sender, **kwargs):
""" create node rating count and settings"""
created = kwargs['created']
node = kwargs['instance']
if created:
# create node_rating_count and settings
# task will be executed in background un... |
create layer rating settings
def create_layer_rating_settings(sender, **kwargs):
""" create layer rating settings """
created = kwargs['created']
layer = kwargs['instance']
if created:
# create layer participation settings
# task will be executed in background unless settings.CELERY_ALW... |
performs actions on create:
* ensure instance has usable password
* set default group
* keep in sync with email address model
def save(self, *args, **kwargs):
"""
performs actions on create:
* ensure instance has usable password
* set default ... |
set is_active to False if needs email confirmation
def needs_confirmation(self):
"""
set is_active to False if needs email confirmation
"""
if EMAIL_CONFIRMATION:
self.is_active = False
self.save()
return True
else:
return False |
Changes password and sends a signal
def change_password(self, new_password):
"""
Changes password and sends a signal
"""
self.set_password(new_password)
self.save()
password_changed.send(sender=self.__class__, user=self) |
Custom initial method:
* ensure node exists and store it in an instance attribute
* change queryset to return only comments of current node
def initial(self, request, *args, **kwargs):
"""
Custom initial method:
* ensure node exists and store it in an instance attrib... |
Decorator which adds fields dynamically to User Notification Settings models.
Each of the keys in the TEXTS dictionary
are added as a field and DB column.
def add_notifications(myclass):
"""
Decorator which adds fields dynamically to User Notification Settings models.
Each of the keys in the TEXT... |
checks if login credentials are correct
def validate(self, attrs):
""" checks if login credentials are correct """
user = authenticate(**self.user_credentials(attrs))
if user:
if user.is_active:
self.instance = user
else:
raise serializer... |
return detail url
def get_details(self, obj):
""" return detail url """
return reverse('api_user_social_links_detail',
args=[obj.user.username, obj.pk],
request=self.context.get('request'),
format=self.context.get('format')) |
return user's location
def get_location(self, obj):
""" return user's location """
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 ... |
password_confirmation check
def validate_password_confirmation(self, value):
""" password_confirmation check """
if value != self.initial_data['password']:
raise serializers.ValidationError(_('Password confirmation mismatch'))
return value |
current password check
def validate_current_password(self, value):
""" current password check """
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 valu... |
password_confirmation check
def validate_password2(self, value):
""" password_confirmation check """
if value != self.initial_data['password1']:
raise serializers.ValidationError(_('Password confirmation mismatch'))
return value |
ensure email is in the database
def validate_email(self, value):
""" ensure email is in the database """
if EMAIL_CONFIRMATION:
queryset = EmailAddress.objects.filter(email__iexact=value, verified=True)
else:
queryset = User.objects.get(email__iexact=value, is_active=Tru... |
change password
def update(self, instance, validated_data):
""" change password """
instance.user.set_password(validated_data["password1"])
instance.user.full_clean()
instance.user.save()
# mark password reset object as reset
instance.reset = True
instance.full_c... |
Custom save method does the following:
* automatically inherit node coordinates and elevation
* save shortcuts if HSTORE is enabled
def save(self, *args, **kwargs):
"""
Custom save method does the following:
* automatically inherit node coordinates and elevation
... |
create password reset for specified user
def create_for_user(self, user):
""" create password reset for specified user """
# support passing email address too
if type(user) is unicode:
from .profile import Profile as User
user = User.objects.get(email=user)
temp... |
execute synchronize command
def handle(self, *args, **options):
""" execute synchronize command """
self.options = options
delete = False
try:
# blank line
self.stdout.write('\r\n')
# store verbosity level in instance attribute for later use
... |
Ask user what to do when an old node is contained in more than one layer.
Possible answers are:
* use default layer (default answer if pressing enter)
* choose layer
* discard node
def prompt_layer_selection(self, node, layers):
"""Ask user what to do when an old nod... |
ensure status map does not contain status values which are not present in DB
def check_status_mapping(self):
""" ensure status map does not contain status values which are not present in DB """
self.verbose('checking status mapping...')
if not self.status_mapping:
self.message('no ... |
retrieve nodes from old mysql DB
def retrieve_nodes(self):
""" retrieve nodes from old mysql DB """
self.verbose('retrieving nodes from old mysql DB...')
self.old_nodes = list(OldNode.objects.all())
self.message('retrieved %d nodes' % len(self.old_nodes)) |
extract user info
def extract_users(self):
""" extract user info """
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 ... |
save admins to local DB
def import_admins(self):
""" save admins to local DB """
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.... |
save users to local DB
def import_users(self):
""" save users to local DB """
self.message('saving users into local DB')
saved_users = self.saved_admins
# loop over all extracted unique email addresses
for email in self.email_set:
owner = self.users_dict[email].get... |
import nodes into local DB
def import_nodes(self):
""" import nodes into local DB """
self.message('saving nodes into local DB...')
saved_nodes = []
# loop over all old node and create new nodes
for old_node in self.old_nodes:
# if this old node is unconfirmed skip... |
delete imported nodes that are not present in the old database
def check_deleted_nodes(self):
""" delete imported nodes that are not present in the old database """
imported_nodes = Node.objects.filter(data__contains=['imported'])
deleted_nodes = []
for node in imported_nodes:
... |
create user notification settings on user creation
def create_settings(sender, **kwargs):
""" create user notification settings on user creation """
created = kwargs['created']
user = kwargs['instance']
if created:
UserWebNotificationSettings.objects.create(user=user)
UserEmailNotificat... |
Add user info to ExtensibleNodeSerializer
def ready(self):
""" Add user info to ExtensibleNodeSerializer """
from nodeshot.core.nodes.base import ExtensibleNodeSerializer
from .serializers import ProfileRelationSerializer
ExtensibleNodeSerializer.add_relationship(
name='use... |
parse geojson and ensure is collection
def parse(self):
""" parse geojson and ensure is collection """
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:
... |
adds a relationship to serializer
:param name: relationship name (dictionary key)
:type name: str
:param view_name: view name as specified in urls.py
:type view_name: str
:param lookup_field: lookup field, usually slug or id/pk
:type lookup_field: str
:param seria... |
parse data
def parse(self):
""" parse data """
url = self.config.get('url')
self.cnml = CNMLParser(url)
self.parsed_data = self.cnml.getNodes() |
Retrieve notifications older than X days, where X is specified in settings
def retrieve_old_notifications(self):
"""
Retrieve notifications older than X days, where X is specified in settings
"""
date = ago(days=DELETE_OLD)
return Notification.objects.filter(added__lte=date) |
Purge notifications
def handle(self, *args, **options):
""" Purge notifications """
# retrieve layers
notifications = self.retrieve_old_notifications()
count = len(notifications)
if count > 0:
self.output('found %d notifications to purge...' % count)
not... |
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.
:param node: the node which should be updated on the external layer.
:type node: Node model instanc... |
writes message to pipe
def send_message(message, pipe='public'):
"""
writes message to pipe
"""
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 P... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.