text stringlengths 81 112k |
|---|
Creates user. Depends on get_username pipeline.
def create_user(backend, details, response, uid, username, user=None, *args, **kwargs):
"""
Creates user. Depends on get_username pipeline.
"""
if user:
return {'user': user}
if not username:
return None
email = details.get('email'... |
Load extra data from provider and store it on current UserSocialAuth extra_data field.
def load_extra_data(backend, details, response, uid, user, social_user=None, *args, **kwargs):
"""
Load extra data from provider and store it on current UserSocialAuth extra_data field.
"""
social_user = social_user ... |
custom validation
def clean(self, *args, **kwargs):
""" custom validation """
if not self.user and (not self.from_name or not self.from_email):
raise ValidationError(_('If sender is not specified from_name and from_email must be filled in.'))
# fill name and email
if self.us... |
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
def send(self):
"""
Sends the email to the recipient
If the sending fails will set the status of the insta... |
Custom save method
def save(self, *args, **kwargs):
"""
Custom save method
"""
# fill name and email
if self.user:
self.from_name = self.user.get_full_name()
self.from_email = self.user.email
# if not sent yet
if int(self.status) < 1:
... |
return n objects according to specified ordering
def slice(self, order_by='pk', n=None):
""" return n objects according to specified ordering """
if n is not None and n < 0:
raise ValueError('slice parameter cannot be negative')
queryset = self.order_by(order_by)
... |
returns all items that have an access level equal or lower than the one specified
def access_level_up_to(self, access_level):
""" returns all items that have an access level equal or lower than the one specified """
# if access_level is number
if isinstance(access_level, int):
value... |
returns all the items that are accessible to the specified user
if user is not authenticated will return public items
:param user: an user instance
def accessible_to(self, user):
"""
returns all the items that are accessible to the specified user
if user is not authenti... |
intercepts changes to is_default
def save(self, *args, **kwargs):
""" intercepts changes to is_default """
ignore_default_check = kwargs.pop('ignore_default_check', False)
# if making this status the default one
if self.is_default != self._current_is_default and self.is_default is True:... |
Custom initial method:
* ensure node exists and store it in an instance attribute
* change queryset to return only links of current node
def initial(self, request, *args, **kwargs):
"""
Custom initial method:
* ensure node exists and store it in an instance attribute... |
patch LayerNodesList view to support external layers
def ready(self):
""" patch LayerNodesList view to support external layers """
from .models import LayerExternal
from nodeshot.core.layers.views import LayerNodeListMixin
def get_nodes(self, request, *args, **kwargs):
try:... |
init celery app without the need of redundant code
def init_celery(project_name):
""" init celery app without the need of redundant code """
os.environ.setdefault('DJANGO_SETTINGS_MODULE', '%s.settings' % project_name)
app = Celery(project_name)
app.config_from_object('django.conf:settings')
app.au... |
Determine recipients depending on selected filtering which can be either:
* group based
* layer based
* user based
Choosing "group" and "layer" filtering together has the effect of sending the message
only to users for which the following conditions are both true:
... |
Sends the email to the recipients
def send(self):
"""
Sends the email to the recipients
"""
# if it has already been sent don't send again
if self.status is OUTWARD_STATUS.get('sent'):
return False
# determine recipients
recipients = self.get_recipien... |
Custom save method
def save(self, *args, **kwargs):
"""
Custom save method
"""
# change status to scheduled if necessary
if self.is_scheduled and self.status is not OUTWARD_STATUS.get('scheduled'):
self.status = OUTWARD_STATUS.get('scheduled')
# call super.s... |
Custom validation
def clean(self, *args, **kwargs):
"""
Custom validation
"""
if self.is_scheduled is 1 and (self.scheduled_date == '' or self.scheduled_date is None
or self.scheduled_time == '' or self.scheduled_time is None):
raise Va... |
Custom save method does the following things:
* converts geometry collections of just 1 item to that item (eg: a collection of 1 Point becomes a Point)
* intercepts changes to status and fires node_status_changed signal
* set default status
def save(self, *args, **kwargs):
"... |
Extend validation of Node by adding a function to the _additional_validation list.
The additional validation function will be called by the clean method
:method function: function to be added to _additional_validation
def add_validation_method(cls, method):
"""
Extend validation of Nod... |
returns location of node. If node geometry is not a point a center point will be returned
def point(self):
""" returns location of node. If node geometry is not a point a center point will be returned """
if not self.geometry:
raise ValueError('geometry attribute must be set before trying... |
Proxy to google elevation API but returns GeoJSON
(unless "original" parameter is passed, in which case the original response is returned).
For input parameters read:
https://developers.google.com/maps/documentation/elevation/
def elevation_profile(request, format=None):
"""
Proxy to google elevat... |
determine user when node is added
def perform_create(self, serializer):
""" determine user when node is added """
if serializer.instance is None:
serializer.save(user=self.request.user) |
Optionally restricts the returned nodes
by filtering against a `search` query parameter in the URL.
def get_queryset(self):
"""
Optionally restricts the returned nodes
by filtering against a `search` query parameter in the URL.
"""
# retrieve all nodes which are publishe... |
Custom initial method:
* ensure node exists and store it in an instance attribute
* change queryset to return only images of current node
def initial(self, request, *args, **kwargs):
"""
Custom initial method:
* ensure node exists and store it in an instance attribut... |
create notifications in a background job to avoid slowing down users
def create_notifications(users, notification_model, notification_type, related_object):
"""
create notifications in a background job to avoid slowing down users
"""
# shortcuts for readability
Notification = notification_model
... |
automatically set Interface.type to ethernet
def save(self, *args, **kwargs):
""" automatically set Interface.type to ethernet """
self.type = INTERFACE_TYPES.get('ethernet')
super(Ethernet, self).save(*args, **kwargs) |
List of all the available resources of this RESTful API.
def root_endpoint(request, format=None):
"""
List of all the available resources of this RESTful API.
"""
endpoints = []
# loop over url modules
for urlmodule in urlpatterns:
# is it a urlconf module?
if hasattr(urlmodule,... |
Custom save method does the following:
* save shortcuts if HSTORE is enabled
def save(self, *args, **kwargs):
"""
Custom save method does the following:
* save shortcuts if HSTORE is enabled
"""
if 'node' not in self.shortcuts:
self.shortcuts['node'] ... |
:param value: a list of ip addresses
def ip_addresses(self, value):
""" :param value: a list of ip addresses """
if not isinstance(value, list):
raise ValueError('ip_addresses value must be a list')
# in soem cases self.data might be none, so let's instantiate an empty dict
... |
updates comment count
def update_count(self):
""" updates comment count """
node_rating_count = self.node.rating_count
node_rating_count.comment_count = self.node.comment_set.count()
node_rating_count.save() |
Check if comments can be inserted for parent node or parent layer
def clean(self, *args, **kwargs):
"""
Check if comments can be inserted for parent node or parent layer
"""
# check done only for new nodes!
if not self.pk:
node = self.node
# ensure commen... |
Retrieve specified layers or all external layers if no layer specified.
def retrieve_layers(self, *args, **options):
"""
Retrieve specified layers or all external layers if no layer specified.
"""
# init empty Q object
queryset = Q()
# if no layer specified
if l... |
execute sync command
def handle(self, *args, **options):
""" execute sync command """
# store verbosity level in instance attribute for later use
self.verbosity = int(options.get('verbosity'))
# blank line
self.stdout.write('\r\n')
# retrieve layers
layers = self... |
sync by creating nodes in external layers when needed
def save_external_nodes(sender, **kwargs):
""" sync by creating nodes in external layers when needed """
node = kwargs['instance']
operation = 'add' if kwargs['created'] is True else 'change'
if node.layer.is_external is False or not hasattr(node.l... |
sync by deleting nodes from external layers when needed
def delete_external_nodes(sender, **kwargs):
""" sync by deleting nodes from external layers when needed """
node = kwargs['instance']
if node.layer.is_external is False or not hasattr(node.layer, 'external') or node.layer.external.synchronizer_path ... |
ensure users cannot vote the same node multiple times
but let users change their votes
def save(self, *args, **kwargs):
"""
ensure users cannot vote the same node multiple times
but let users change their votes
"""
if not self.pk:
old_votes = Vote.objects.fil... |
updates likes and dislikes count
def update_count(self):
""" updates likes and dislikes count """
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()
... |
Check if votes can be inserted for parent node or parent layer
def clean(self, *args, **kwargs):
"""
Check if votes can be inserted for parent node or parent layer
"""
if not self.pk:
# ensure voting for this node is allowed
if self.node.participation_settings.vo... |
Retrieve basic whois information related to a layer2 or layer3 network address.
def whois_list(request, format=None):
"""
Retrieve basic whois information related to a layer2 or layer3 network address.
"""
results = []
# layer3 results
for ip in Ip.objects.select_related().all():
interf... |
Retrieve basic whois information related to a layer2 or layer3 network address.
def whois_detail(request, address, format=None):
"""
Retrieve basic whois information related to a layer2 or layer3 network address.
"""
address_obj = None
try:
address_obj = IPAddress(address)
except AddrFo... |
Optionally restricts the returned devices
by filtering against a `search` query parameter in the URL.
def get_queryset(self):
"""
Optionally restricts the returned devices
by filtering against a `search` query parameter in the URL.
"""
# retrieve all devices which are pu... |
Custom initial method:
* ensure node exists and store it in an instance attribute
* change queryset to return only devices of current node
def initial(self, request, *args, **kwargs):
"""
Custom initial method:
* ensure node exists and store it in an instance attribu... |
Custom initial method:
* ensure device exists and store it in an instance attribute
* change queryset to return only devices of current node
def initial(self, request, *args, **kwargs):
"""
Custom initial method:
* ensure device exists and store it in an instance att... |
Custom initial method:
* ensure interface exists and store it in an instance attribute
* change queryset to return only devices of current node
def initial(self, request, *args, **kwargs):
"""
Custom initial method:
* ensure interface exists and store it in an instan... |
Given kwargs from the view (with view specific keys popped) pull out the
bridge and fetch group from database.
def group_and_bridge(kwargs):
"""
Given kwargs from the view (with view specific keys popped) pull out the
bridge and fetch group from database.
"""
bridge = kwargs.pop("bridge", None... |
automatically update updated date field
def save(self, *args, **kwargs):
"""
automatically update updated date field
"""
# auto fill updated field with current time unless explicitly disabled
auto_update = kwargs.get('auto_update', True)
if auto_update:
self.... |
if order left blank
def save(self, *args, **kwargs):
""" if order left blank """
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
... |
Ensure dependencies of a module are listed in settings.INSTALLED_APPS
:dependencies string | list: list of dependencies to check
:module string: string representing the path to the current app
def check_dependencies(dependencies, module):
"""
Ensure dependencies of a module are listed in settings.INST... |
Converts a readable python dictionary into a django model/form
choice structure (list of tuples) ordered based on the values of each key
:param dictionary: the dictionary to convert
def choicify(dictionary):
"""
Converts a readable python dictionary into a django model/form
choice structure (list ... |
searchs a value in a dicionary and returns the key of the first occurrence
:param dictionary: dictionary to search in
:param search_value: value to search for
def get_key_by_value(dictionary, search_value):
"""
searchs a value in a dicionary and returns the key of the first occurrence
:param dict... |
retrieve layer from DB
def get_layer(self):
""" retrieve layer from DB """
if self.layer:
return
try:
self.layer = Layer.objects.get(slug=self.kwargs['slug'])
except Layer.DoesNotExist:
raise Http404(_('Layer not found')) |
extend parent class queryset by filtering nodes of the specified layer
def get_queryset(self):
""" extend parent class queryset by filtering nodes of the specified layer """
self.get_layer()
return super(LayerNodeListMixin, self).get_queryset().filter(layer_id=self.layer.id) |
this method might be overridden by other modules (eg: nodeshot.interop.sync)
def get_nodes(self, request, *args, **kwargs):
""" this method might be overridden by other modules (eg: nodeshot.interop.sync) """
# ListSerializerMixin.list returns a serializer object
return (self.list(request, *arg... |
Retrieve list of nodes of the specified layer
def get(self, request, *args, **kwargs):
""" Retrieve list of nodes of the specified layer """
self.get_layer()
# get nodes of layer
nodes = self.get_nodes(request, *args, **kwargs)
return Response(nodes) |
Determines ip protocol version automatically.
Stores address in interface shortcuts for convenience.
def save(self, *args, **kwargs):
"""
Determines ip protocol version automatically.
Stores address in interface shortcuts for convenience.
"""
self.protocol = 'ipv%d' % se... |
Relations between objects are allowed between nodeshot2 objects only
def allow_relation(self, obj1, obj2, **hints):
"""
Relations between objects are allowed between nodeshot2 objects only
"""
if obj1._meta.app_label != 'oldimporter' and obj2._meta.app_label != 'oldimporter':
... |
Make sure the old_nodeshot app only appears in the 'old_nodeshot' database
def allow_migrate(self, db, model):
"""
Make sure the old_nodeshot app only appears in the 'old_nodeshot' database
"""
if db != 'old_nodeshot' or model._meta.app_label != 'oldimporter':
return False
... |
ensure email is in the database
def clean_email(self):
""" ensure email is in the database """
if EMAIL_CONFIRMATION:
from .models import EmailAddress
condition = EmailAddress.objects.filter(
email__iexact=self.cleaned_data["email"],
verified=True... |
Get or write metric values
def metric_details(request, pk, format=None):
"""
Get or write metric values
"""
metric = get_object_or_404(Metric, pk=pk)
# get
if request.method == 'GET':
try:
results = metric.select(q=request.query_params.get('q', metric.query))
except ... |
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.
def add_client(self, user_id=None):
"""
Adds current instance to public or private channel.
... |
broadcast message to all connected clients
def broadcast(cls, message):
""" broadcast message to all connected clients """
clients = cls.get_clients()
# loop over every client and send message
for id, client in clients.iteritems():
client.send_message(message) |
Send a message to a specific client.
Returns True if successful, False otherwise
def send_private_message(self, user_id, message):
"""
Send a message to a specific client.
Returns True if successful, False otherwise
"""
try:
client = self.channels['private'][... |
return a merge of public and private clients
def get_clients(self):
""" return a merge of public and private clients """
public = self.channels['public']
private = self.channels['private']
return dict(public.items() + private.items()) |
method which is called every time a new client connects
def open(self):
""" method which is called every time a new client connects """
print 'Connection opened.'
# retrieve user_id if specified
user_id = self.get_argument("user_id", None)
# add client to list of connec... |
method which is called every time a client disconnects
def on_close(self):
""" method which is called every time a client disconnects """
print 'Connection closed.'
self.remove_client()
client_count = len(self.get_clients().keys())
new_client_message = '1 client disconn... |
Returns an ``InfluxDBClient`` instance.
def get_db():
"""Returns an ``InfluxDBClient`` instance."""
return client.InfluxDBClient(
settings.INFLUXDB_HOST,
settings.INFLUXDB_PORT,
settings.INFLUXDB_USER,
settings.INFLUXDB_PASSWORD,
settings.INFLUXDB_DATABASE,
) |
Wrapper around ``InfluxDBClient.query()``.
def query(query, params={}, epoch=None,
expected_response_code=200, database=None):
"""Wrapper around ``InfluxDBClient.query()``."""
db = get_db()
database = database or settings.INFLUXDB_DATABASE
return db.query(query, params, epoch, expected_respon... |
write metrics
def write_async(name, values, tags={}, timestamp=None, database=None):
""" write metrics """
thread = Thread(target=write,
args=(name, values, tags, timestamp, database))
thread.start() |
Method to be called via threading module.
def write(name, values, tags={}, timestamp=None, database=None):
""" Method to be called via threading module. """
point = {
'measurement': name,
'tags': tags,
'fields': values
}
if isinstance(timestamp, datetime):
timestamp = ti... |
creates database if necessary
def create_database():
""" creates database if necessary """
db = get_db()
response = db.query('SHOW DATABASES')
items = list(response.get_points('databases'))
databases = [database['name'] for database in items]
# if database does not exists, create it
if sett... |
ensure users cannot rate the same node multiple times
but let users change their rating
def save(self, *args, **kwargs):
"""
ensure users cannot rate the same node multiple times
but let users change their rating
"""
if not self.pk:
old_ratings = Rating.objec... |
updates rating count and rating average
def update_count(self):
""" updates rating count and rating average """
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... |
Check if rating can be inserted for parent node or parent layer
def clean(self, *args, **kwargs):
"""
Check if rating can be inserted for parent node or parent layer
"""
if not self.pk:
node = self.node
layer = Layer.objects.get(pk=node.layer_id)
if l... |
custom save method to update counts
def save(self, *args, **kwargs):
""" custom save method to update counts """
# the following lines determines if the comment is being created or not
# in case the comment exists the pk attribute is an int
created = type(self.pk) is not int
su... |
custom delete method to update counts
def delete(self, *args, **kwargs):
""" custom delete method to update counts """
super(UpdateCountsMixin, self).delete(*args, **kwargs)
self.update_count() |
updates all the topology
sends logs to the "nodeshot.networking" logger
def update_topology():
"""
updates all the topology
sends logs to the "nodeshot.networking" logger
"""
for topology in Topology.objects.all():
try:
topology.update()
except Exception as e:
... |
Custom save does the following:
* strip trailing whitespace from host attribute
* create device and all other related objects
* store connection config in DB if store attribute is True
def save(self, *args, **kwargs):
"""
Custom save does the following:
*... |
validation
def clean(self, *args, **kwargs):
""" validation """
self._validate_backend()
self._validate_config()
self._validate_netengine()
self._validate_duplicates() |
returns python netengine backend class, importing it if needed
def backend_class(self):
"""
returns python netengine backend class, importing it if needed
"""
if not self.backend:
return None
if not self.__backend_class:
self.__backend_class = self._get_... |
access netengine instance
def netengine(self):
""" access netengine instance """
# return None if no backend chosen yet
if not self.backend:
return None
# init instance of the netengine backend if not already done
if not self.__netengine:
NetengineBacken... |
ensure backend string representation is correct
def _validate_backend(self):
""" ensure backend string representation is correct """
try:
self.backend_class
# if we get an import error the specified path is wrong
except (ImportError, AttributeError) as e:
raise V... |
ensure REQUIRED_CONFIG_KEYS are filled
def _validate_config(self):
""" ensure REQUIRED_CONFIG_KEYS are filled """
# exit if no backend specified
if not self.backend:
return
# exit if no required config keys
if len(self.REQUIRED_CONFIG_KEYS) < 1:
return
... |
call netengine validate() method
verifies connection parameters are correct
def _validate_netengine(self):
"""
call netengine validate() method
verifies connection parameters are correct
"""
if self.backend:
try:
self.netengine.validate()
... |
Ensure we're not creating a device that already exists
Runs only when the DeviceConnector object is created, not when is updated
def _validate_duplicates(self):
"""
Ensure we're not creating a device that already exists
Runs only when the DeviceConnector object is created, not when is u... |
returns list of available config params
returns list of required config params if required is True
for internal use only
def _get_netengine_arguments(self, required=False):
"""
returns list of available config params
returns list of required config params if required is True
... |
returns the netengine backend specified in self.backend
for internal use only
def _get_netengine_backend(self):
"""
returns the netengine backend specified in self.backend
for internal use only
"""
# extract backend class name, eg: AirOS or OpenWRT
backend_class_... |
returns a python dictionary representing arguments
that will be passed to a netengine backend
for internal use only
def _build_netengine_arguments(self):
"""
returns a python dictionary representing arguments
that will be passed to a netengine backend
for internal use on... |
creates device, internal use only
def __create_device(self):
"""
creates device, internal use only
"""
# retrieve netengine dictionary from memory or from network
device_dict = getattr(self, 'netengine_dict', self.netengine.to_dict())
device = Device()
device.nod... |
Cache view response by media type and user group.
The cache_key is constructed this way: "{view_name:path.group.media_type}"
EG: "MenuList:/api/v1/menu/.public.application/json"
Possible groups are:
* public
* superuser
* the rest are retrieved from DB (registered, community, trusted... |
Generate a model class based on the provided JSON Schema
:param schema: dict representing valid JSON schema
:param name: A name to give the class, if `name` is not in `schema`
def model_factory(schema, resolver=None, base_class=model.Model, name=None):
"""Generate a model class based on the provided JSON ... |
Return a jsonpatch object representing the delta
def patch(self):
"""Return a jsonpatch object representing the delta"""
original = self.__dict__['__original__']
return jsonpatch.make_patch(original, dict(self)).to_string() |
Dumber version of 'patch' method
def changes(self):
"""Dumber version of 'patch' method"""
deprecation_msg = 'Model.changes will be removed in warlock v2'
warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2)
return copy.deepcopy(self.__dict__['changes']) |
Apply a JSON schema to an object
def validate(self, obj):
"""Apply a JSON schema to an object"""
try:
if self.resolver is not None:
jsonschema.validate(obj, self.schema, resolver=self.resolver)
else:
jsonschema.validate(obj, self.schema)
e... |
Returns if the files are valid for this filetype
def isSupportedContent(cls, fileContent):
"""Returns if the files are valid for this filetype"""
magic = bytearray(fileContent)[:4]
return magic == p('>I', 0xfeedface) or magic == p('>I', 0xfeedfacf) or magic == p('<I', 0xfeedface) or magic == p(... |
Returns the OatHeader
def _parseOatHeader(self, data):
"""Returns the OatHeader"""
header = OatHeader.from_buffer(data)
if header.magic != b'oat\n':
raise BinaryError('No valid OAT file')
key_value_store_bytes = (c_ubyte * header.keyValueStoreSize).from_buffer(data, sizeof(... |
Returns a dictionary filled with the keys and values of the key value store
def __parseKeyValueStore(self, data):
"""Returns a dictionary filled with the keys and values of the key value store"""
offset = 0
key_value_store = {}
while offset != len(data):
key = get_str(data, ... |
Converts the addr from a rva to a pointer to raw data in the file
def to_raw_address(addr, section):
"""Converts the addr from a rva to a pointer to raw data in the file"""
return addr - section.header.VirtualAddress + section.header.PointerToRawData |
Returns the class which holds the suitable classes for the loaded file
def _getSuitableClasses(self, data, imageDosHeader):
"""Returns the class which holds the suitable classes for the loaded file"""
classes = None
machine = IMAGE_FILE_MACHINE[c_ushort.from_buffer(data,imageDosHeader.header.e_... |
Returns the ImageDosHeader
def _parseImageDosHeader(self, data):
"""Returns the ImageDosHeader"""
ioh = IMAGE_DOS_HEADER.from_buffer(data)
if ioh.e_magic != b'MZ':
raise BinaryError('No valid PE/COFF file')
return ImageDosHeaderData(header=ioh) |
Returns the ImageNtHeaders
def _parseImageNtHeaders(self, data, imageDosHeader):
"""Returns the ImageNtHeaders"""
inth = self._classes.IMAGE_NT_HEADERS.from_buffer(data, imageDosHeader.header.e_lfanew)
if inth.Signature != b'PE':
raise BinaryError('No valid PE/COFF file')
... |
Parses the sections in the memory and returns a list of them
def _parseSections(self, data, imageDosHeader, imageNtHeaders, parse_header_only=False):
"""Parses the sections in the memory and returns a list of them"""
sections = []
optional_header_offset = imageDosHeader.header.e_lfanew + 4 + s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.