def add_new(request): context = RequestContext(request) if request.method=='POST': n = eval(request.POST['tipo_new']) n.nombre=request.POST['nombre_new'] n.desc=request.POST['desc_new'] if su(request): n.active = True n.save() if not su(request): tipo_a = request.POST['tipo_new'] sender = {"Idioma()":'idiomas',"Lenguaje()":'lenguajes',"Jobs()":'trabajos'} pager = {"Idioma()":'obj_i.html',"Lenguaje()":'obj_l.html',"Jobs()":'obj_t.html'} helper = "#r_" + sender[tipo_a].partition("s")[0] print helper template = get_template(pager[tipo_a]) print template aux = tipo_a.partition("(")[0] + ".objects.filter(active = False)" objs = eval(aux) context[sender[tipo_a]]=objs print context html = template.render(context) print html publish( 'proy', 'su', { 'loader' : helper, 'data' : html}, sender='server' # sender id of the event, can be None. ) return HttpResponse(status=202)
def new_message(request): post_data = request.POST message = post_data['message'] user = request.user Message.objects.create(user=user, message=post_data['message']) publish('chatapp', 'new_msg', {'text': message, 'username': user.username}, sender='server') return HttpResponse(json.dumps({'success': True}), content_type="application/json")
def recargar(helper, result): publish( 'module_recargar', 'reload', { 'loader' : helper, 'data' : result}, sender='server' # sender id of the event, can be None. )
def IrrigatorUpdated(sender, **kwargs): if (kwargs["update_fields"] and kwargs["update_fields"] == ["in_watering_cycle"]): publish( "pidrator", "irrigator-%d" % kwargs["instance"].pk, {"in_watering_cycle": kwargs["instance"].in_watering_cycle}) else: CheckIrrigators.delay(pk=kwargs["instance"].pk)
def SensorUpdated(sender, **kwargs): CheckThermostats.delay(sensor=kwargs["instance"]) if kwargs["instance"].temperature is not None: kwargs["instance"].temperature = float(kwargs["instance"].temperature) publish( "pimostat", "sensor-%d" % kwargs["instance"].pk, {"temperature": kwargs["instance"].temperature})
def update(self, canal="chat", typ="msg", info={"msg":"alive"}): print("TYP> "+ typ + "INFO>" + unicode(info)) publish( canal, typ, info, sender='server' )
def send_hello_world(): publish( 'foo', # the name of the channel 'bar', # the `type` of the message/event, clients use this name # to register event handlers {'text': 'Hello world'}, # payload of the event, needs to be # a dict which is JSON dumpable. sender='server' # sender id of the event, can be None. )
def server_publish(cls, channel, payload_type, data, sender='server'): print "Server publish in %s " % cls.form_channel_full_name(channel) publish( cls.form_channel_full_name(channel), # Send to the root payload_type, data, sender='server')
def send_message(self, message): message = Bot.objects.create(message=message, date=timezone.now(), nickname='Бот').__str__() publish( 'mychannel', 'message', {'message': message}, sender='server' )
def on_success(self, data): if 'coordinates' in data and data['coordinates']: tweet = { 'tweet_id': data['id_str'], 'coordinates': data['coordinates']['coordinates'] } logger.info('Tweet {0} from {1}'.format( tweet['tweet_id'], tweet['coordinates'])) api.publish('tweets', 'tweet', tweet)
def mod_proy(request, proj): context = RequestContext(request) proj = Proj.objects.get(id=proj) if perm(request, proj.owner) and request.method == 'POST': print request.POST proj.nombre = request.POST['name'] proj.desc = request.POST['desc_proy'] proj.save() p_i = request.POST.getlist("idiomas") proj.nescesita_i.clear() for i in p_i: aux = Idioma.objects.get(id=i) proj.nescesita_i.add(aux) p_l = request.POST.getlist("lenguajes") proj.nescesita_l.clear() for i in p_l: aux = Lenguaje.objects.get(id=i) proj.nescesita_l.add(aux) for i in proj.rol_set.all(): rol_user = Rol.objects.get(id=i.id) if proj in rol_user.proj_user.all(): if discover(proj, rol_user): rol_user.proj_user.add(proj) else: rol_user.proj_user.remove(proj) else: if discover(proj, rol_user): rol_user.proj_user.add(proj) publish( 'proy', 'reload', {"id_proy": proj.id}, sender='server' # sender id of the event, can be None. ) return redirect('/') idiomas = Idioma.objects.filter(active=True) lenguajes = Lenguaje.objects.filter(active=True) trabajos = Jobs.objects.filter(active=True) rol_user = Rol.objects.get(user=request.user) return render_to_response( 'm_proj.html', { 'idiomas': idiomas, 'lenguajes': lenguajes, 'trabajos': trabajos, 'proj': proj, 'works': proj.nescesita_w, 'rol_user': rol_user, 'perm': perm(request, proj.owner) }, context)
def post(self, request, *args, **kwargs): chat_user_id = request.POST.get("user_id") chat_room_id = request.POST.get("room_id") message = request.POST.get("message") chat_message = ChatMessage() chat_message.chat_user_id = int(chat_user_id) chat_message.chat_room_id = int(chat_room_id) chat_message.message = message chat_message.save() publish('chat', 'message', chat_message.to_dict(), sender=None) return JsonResponse(chat_message.to_dict(), safe=False)
def add_active(request): context = RequestContext(request) if request.method == 'POST' and su(request): tipo_a = request.POST['tipo'] id_a = request.POST['id'] print id_a, tipo_a pos = {"Idioma": Idioma, "Lenguaje": Lenguaje, "Jobs": Jobs} sender = { "Idioma": 'idiomas', "Lenguaje": 'lenguajes', "Jobs": 'trabajos' } pager = { "Idioma": 'obj_i.html', "Lenguaje": 'obj_l.html', "Jobs": 'obj_t.html' } aux = tipo_a + ".objects.get(id = " + id_a + ")" print aux obj = eval(aux, pos) print obj if request.POST['tDo'] == "True": obj.active = True obj.save() else: obj.delete() aux = tipo_a + ".objects.filter(active = False)" objs = eval(aux, pos) print "----" helper = "#r_" + sender[tipo_a].partition("s")[0] print helper template = get_template(pager[tipo_a]) print template context[sender[tipo_a]] = objs print context html = template.render(context) print html publish( 'proy', 'su', { 'loader': helper, 'data': html }, sender='server' # sender id of the event, can be None. ) return render_to_response(pager[tipo_a], {sender[tipo_a]: objs}, context)
def mod_proy(request, proj): context = RequestContext(request) proj = Proj.objects.get(id = proj) if perm(request, proj.owner) and request.method=='POST': print request.POST proj.nombre = request.POST['name'] proj.desc = request.POST['desc_proy'] proj.save() p_i = request.POST.getlist("idiomas") proj.nescesita_i.clear() for i in p_i: aux = Idioma.objects.get(id = i) proj.nescesita_i.add(aux) p_l = request.POST.getlist("lenguajes") proj.nescesita_l.clear() for i in p_l: aux = Lenguaje.objects.get(id = i) proj.nescesita_l.add(aux) for i in proj.rol_set.all(): rol_user = Rol.objects.get(id = i.id) if proj in rol_user.proj_user.all(): if discover(proj,rol_user): rol_user.proj_user.add(proj) else: rol_user.proj_user.remove(proj) else: if discover(proj,rol_user): rol_user.proj_user.add(proj) publish( 'proy', 'reload', {"id_proy":proj.id}, sender='server' # sender id of the event, can be None. ) return redirect('/') idiomas = Idioma.objects.filter(active = True) lenguajes = Lenguaje.objects.filter(active = True) trabajos = Jobs.objects.filter(active = True) rol_user = Rol.objects.get(user = request.user) return render_to_response('m_proj.html', {'idiomas':idiomas, 'lenguajes':lenguajes, 'trabajos':trabajos, 'proj':proj, 'works':proj.nescesita_w, 'rol_user':rol_user, 'perm':perm(request, proj.owner)}, context)
def send_hello_world(): while True: time.sleep(0.5) message = "".join([random.choice(string.ascii_letters) for i in range(10)]) timestamp = str(datetime.now()) print("Sending: %s, %s" % (message, timestamp)) publish( "24", # the name of the channel "approval", # the `type` of the message/event, # clients use this name # to register event handlers # payload of the event, needs to be # a dict which is JSON dumpable. {"message": message, "timestamp": timestamp}, sender="server", # sender id of the event, can be None. )
def add_new(request): context = RequestContext(request) if request.method == 'POST': n = eval(request.POST['tipo_new']) n.nombre = request.POST['nombre_new'] n.desc = request.POST['desc_new'] if su(request): n.active = True n.save() if not su(request): tipo_a = request.POST['tipo_new'] sender = { "Idioma()": 'idiomas', "Lenguaje()": 'lenguajes', "Jobs()": 'trabajos' } pager = { "Idioma()": 'obj_i.html', "Lenguaje()": 'obj_l.html', "Jobs()": 'obj_t.html' } helper = "#r_" + sender[tipo_a].partition("s")[0] print helper template = get_template(pager[tipo_a]) print template aux = tipo_a.partition("(")[0] + ".objects.filter(active = False)" objs = eval(aux) context[sender[tipo_a]] = objs print context html = template.render(context) print html publish( 'proy', 'su', { 'loader': helper, 'data': html }, sender='server' # sender id of the event, can be None. ) return HttpResponse(status=202)
def main(): while True: fromid = callid() message = {} cust = get_customer(fromid['phone'], fromid['NAME']) message['callernumber'] = fromid['phone'] message['callername'] = fromid['NAME'] message['calledat'] = fromid['time'] message['NMBR'] = fromid['NMBR'] message['customer'] = cust['name'] message['pk'] = cust['pk'] message['url'] = cust['url'] message['custtype'] = cust['custtype'] publish('callerid', 'caller', message) print("published...", message) crs.execute("insert into customers_call " "values (default, '{}','{}','{}',{}) ".format( fromid['phone'], fromid['NAME'], fromid['time'], cust["pk"])) crs.execute("commit")
def publish(channel, payload_type, payload=None, sender=None): """ calling this publish method sends a push notification to all the registered clients :param channel: name of the channel :param payload_type: the `type` of the message/event, clients use this name to register event handlers :param payload: payload of the event, needs to be a dict which is JSON dumpable. """ return api.publish(channel, payload_type, payload, sender)
def add_active(request): context = RequestContext(request) if request.method=='POST' and su(request): tipo_a = request.POST['tipo'] id_a = request.POST['id'] print id_a, tipo_a pos = {"Idioma":Idioma,"Lenguaje":Lenguaje,"Jobs":Jobs} sender = {"Idioma":'idiomas',"Lenguaje":'lenguajes',"Jobs":'trabajos'} pager = {"Idioma":'obj_i.html',"Lenguaje":'obj_l.html',"Jobs":'obj_t.html'} aux = tipo_a + ".objects.get(id = "+ id_a + ")" print aux obj = eval(aux, pos) print obj if request.POST['tDo']=="True": obj.active = True obj.save() else: obj.delete() aux = tipo_a + ".objects.filter(active = False)" objs = eval(aux, pos) print "----" helper = "#r_" + sender[tipo_a].partition("s")[0] print helper template = get_template(pager[tipo_a]) print template context[sender[tipo_a]]=objs print context html = template.render(context) print html publish( 'proy', 'su', { 'loader' : helper, 'data' : html}, sender='server' # sender id of the event, can be None. ) return render_to_response(pager[tipo_a], {sender[tipo_a]:objs}, context)
def RelayUpdated(sender, **kwargs): publish( "pimostat", "relay-%d" % kwargs["instance"].pk, {"actuated": str(kwargs["instance"].actuated)})
def SensorUpdated(sender, **kwargs): CheckIrrigators.delay(sensor=kwargs["instance"]) publish( "pidrator", "sensor-%d" % kwargs["instance"].pk, {"moisture": None if not kwargs["instance"].moisture else float(kwargs["instance"].moisture)})
def send_message(): api.publish('channel', 'type', {'test': 'works!'}) time.sleep(1) api.publish('channel', 'type', {'test': 'works!'})
def RelayUpdated(sender, **kwargs): publish( "pidrator", "relay-%d" % kwargs["instance"].pk, {"actuated": kwargs["instance"].actuated})
def test_publish(publish_mock): result = publish('mychan', 'thetype', payload={1: 2}, sender='snd') assert result == publish_mock.return_value assert publish_mock.call_args[0] == ('mychan', 'thetype', {1: 2}, 'snd')
def RelayUpdated(sender, **kwargs): publish( "lazylight", "update-relay", {"relay_pk": kwargs["instance"].pk, "actuated": kwargs["instance"].actuated})
def update(self, canal="chat", typ="msg", info={"msg": "alive"}): print("TYP> " + typ + "INFO>" + unicode(info)) publish(canal, typ, info, sender='server')
def aws_create(request, playground): reqData = request.POST sgroups = str(reqData.getlist('secGroups[]', [])) """ Create the instance and initiate chef-zero using Vagrant """ aws_access_key = UserConfig.objects.findOrCreate_AwsKey(request.user).val aws_secret_key = UserConfig.objects.findOrCreate_AwsSecret(request.user).val create_private_key(aws_access_key, aws_secret_key) http_proxy = UserConfig.objects.findOrCreate_ProxyHttp(request.user).val https_proxy = UserConfig.objects.findOrCreate_ProxyHttps(request.user).val print("Printing create post", flush=True) print(request.POST) # Names rather than django ids are used since the sandbox id isn't generated until later. This is a chicken/egg problem. sandbox_name = request.POST['name'] m = hashlib.sha256() m.update(sandbox_name.encode('utf-8')) m.update(playground.name.encode('utf-8')) vm_id = m.hexdigest() # We already track sandbox's through the SandboxVM model, the check should occur there. if os.path.exists(VAGRANT_PATH + vm_id): print("VM already exists: " + VAGRANT_PATH + vm_id, flush=True) return "error" # Consider better error handling else: os.makedirs(VAGRANT_PATH + vm_id) # Fix Berksfile path resolution to work with both 'geoq' and 'geoq::default' formats berksfile_dirname = request.POST['recipe'].split("::")[0] #Generate the Vagrantfile in the cookbook directory file = open(VAGRANT_PATH + vm_id + '/Vagrantfile', 'w') file.write('Vagrant.configure(2) do |config|\n') if platform.system() == "Windows": file.write(' ENV["VAGRANT_DETECTED_OS"] = ENV["VAGRANT_DETECTED_OS"].to_s + " cygwin"\n') else: file.write(' ENV["VAGRANT_DETECTED_OS"] = ENV["VAGRANT_DETECTED_OS"].to_s\n') file.write(' config.ssh.username = "******"\n') file.write(' config.ssh.private_key_path = "' + PRIVATE_KEY_PATH + '"\n') file.write(' config.ssh.pty = true\n') # The Berksfile is located in the specific cookbook directory file.write(' config.berkshelf.berksfile_path = "' + COOKBOOK_PATH + berksfile_dirname + '/Berksfile"\n') file.write(' config.berkshelf.enabled = true\n') file.write(' config.vm.synced_folder "", "/vagrant", type: "rsync", rsync__exclude: ".git/"\n') file.write(' config.proxy.http = "' + http_proxy + '"\n') file.write(' config.proxy.https = "' + https_proxy + '"\n') file.write(' config.vm.box = "dummy"\n') file.write(' config.trigger.before [:reload, :up, :provision], stdout: true do\n') file.write(' SYNCED_FOLDER = ".vagrant/machines/default/aws/synced_folders"\n') file.write(' info "Trying to delete folder #{SYNCED_FOLDER}"\n') file.write(' # Delete synced folders as workaround to known vagrant bug.\n') file.write(' begin\n') file.write(' File.delete(SYNCED_FOLDER)\n') file.write(' rescue Exception => ex\n') file.write(' warn "Could not delete folder #{SYNCED_FOLDER}."\n') file.write(' warn ex.message\n') file.write(' end\n') file.write(' end\n') file.write(' config.vm.provider :aws do |aws|\n') file.write(' aws.user_data = "#!/bin/bash\\nsed -i -e \'s/^Defaults.*requiretty/# Defaults requiretty/g\' /etc/sudoers"\n') file.write(' aws.access_key_id = "'+ aws_access_key + '"\n') file.write(' aws.secret_access_key = "'+aws_secret_key+'"\n') file.write(' aws.keypair_name = "'+ COCREATELITE_KEYNAME +'"\n') file.write(' aws.instance_type = "'+ request.POST['type'] +'"\n') file.write(' aws.region = "'+ DEFAULT_REGION + '"\n') file.write(' aws.security_groups = '+ sgroups +'\n') file.write(' aws.ami = "'+ request.POST['ami'] + '"\n') file.write(' aws.subnet_id = "'+ request.POST['subnet']+'"\n') file.write(' aws.tags = {\n') file.write(' "Name" => "'+ request.POST['name'] +' "\n') file.write(' }\n') file.write(' aws.associate_public_ip = true\n') file.write(' end\n') file.write(' config.vm.provision "chef_zero" do |chef|\n') file.write(' chef.cookbooks_path = "'+ COOKBOOK_PATH + '"\n') file.write(' chef.nodes_path = "/tmp"\n') file.write(' chef.add_recipe "' + request.POST['recipe'] + '"\n') file.write(' chef.environment = "cocreatelite"\n') file.write(' chef.environments_path = "' + ENVIRONMENT_PATH + '"\n') file.write(' end\n') file.write('end') file.close() # TODO: a separate process using something like Celery or Twisted to # create/provision the new resource and provide better status info # Run cwd_path = VAGRANT_PATH + vm_id aws_name = request.POST['name'] # needed to force the provider in some environments (like mine) os.environ['VAGRANT_DEFAULT_PROVIDER'] = 'aws' os.environ['HOME'] = '/root' vagrant_cmd = 'vagrant up --no-provision --provider=aws' print("executing: " + vagrant_cmd, flush=True) api.publish('vagrants', aws_name, {'text': ''}) # omnibus appears to eat first event api.publish('vagrants', aws_name, {'text': vagrant_cmd}) vagrantProcess = subprocess.Popen(vagrant_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=cwd_path) print("bout to print stdout", flush=True) if vagrantProcess.stdout is not None: for line in iter(vagrantProcess.stdout.readline, b''): line = line.decode("utf-8").rstrip() print("<stdout> " + line, flush=True) api.publish('vagrants', aws_name, {'text': line}) print("bout to print stderror", flush=True) if vagrantProcess.stderr is not None: for line in iter(vagrantProcess.stderr.readline, b''): line = line.decode("utf-8").rstrip() print("<stderr> " + line, flush=True) api.publish('vagrants', aws_name, {'text': line}) # add space between api.publish('vagrants', aws_name, {'text': ''}) vagrant_cmd = 'vagrant awsinfo -m default -p' print("executing: " + vagrant_cmd, flush=True) api.publish('vagrants', aws_name, {'text': vagrant_cmd}) vagrantProcess = subprocess.Popen(vagrant_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=cwd_path) instance_id = '' if vagrantProcess.stdout is not None: aws_info = '' for line in iter(vagrantProcess.stdout.readline, b''): line = line.decode("utf-8").rstrip() print("<stdout> " + line, flush=True) api.publish('vagrants', aws_name, {'text': line}) aws_info += line # TODO: so this will fail if aws_stdout doesn't hhave the expected string # need to trap and better handle either here or by what calls this # method instance_id = json.loads(aws_info)['instance_id'] print("set instance_id = " + instance_id) if vagrantProcess.stderr is not None: for line in iter(vagrantProcess.stderr.readline, b''): line = line.decode("utf-8").rstrip() print("<stderr> " + line, flush=True) api.publish('vagrants', aws_name, {'text': line}) # add space between api.publish('vagrants', aws_name, {'text': ''}) vagrant_cmd = 'vagrant provision' print("executing: " + vagrant_cmd, flush=True) api.publish('vagrants', aws_name, {'text': vagrant_cmd}) vagrantProcess = subprocess.Popen(vagrant_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=cwd_path) if vagrantProcess.stdout is not None: for line in iter(vagrantProcess.stdout.readline, b''): line = line.decode("utf-8").rstrip() print("<stdout> " + line, flush=True) api.publish('vagrants', aws_name, {'text': line}) if vagrantProcess.stderr is not None: for line in iter(vagrantProcess.stderr.readline, b''): line = line.decode("utf-8").rstrip() print("<stderr> " + line, flush=True) api.publish('vagrants', aws_name, {'text': line}) # add space between api.publish('vagrants', aws_name, {'text': ''}) api.publish('vagrants', aws_name, {'text': 'Done. Goodbye.'}) return instance_id