Example #1
1
 def update_queue(self, queue_name, options=None):
     body = json.dumps({})
     if options is not None:
         body = json.dumps({"queue": options})
     url = "queues/%s" % queue_name
     response = self.client.patch(url, body=body, headers={"Content-Type": "application/json"})
     return response["body"]["queue"]
Example #2
0
def migrate_rooms(src_rooms, dst_rooms, to_migrate_isps, username):
    history_id = MigrateDal.create_migrage_history(username)

    migrated_isp_rooms = MigrateDal.get_all_abnormal_isps(key='isp', value='room')
    to_migrate_dict = {isp: set(src_rooms) | migrated_isp_rooms.get(isp, set())
                       for isp in to_migrate_isps}

    migrate_isp_domains = MigrateDal.list_migrate_domain_by_isp(to_migrate_dict, dst_rooms)

    has_migrate_domains = False
    for isp, migrate_domains_list in migrate_isp_domains.items():
        migrate_domains_list = [domain for domain in migrate_domains_list if domain['after_enabled_rooms']]
        if len(migrate_domains_list) == 0:
            continue
        has_migrate_domains = True
        MigrateDal.update_history_total(history_id, len(migrate_domains_list))
        m_thread = MigrateThread(username, history_id, migrate_domains_list)
        m_thread.start()

    if has_migrate_domains:
        MigrateDal.add_batch_abnormal_isp(username, to_migrate_dict)
        # send_alert_email("[FROM DNSDB]: 机房{}上运营商{}迁移到{}啦.".format(src_rooms, to_migrate_isps, dst_rooms))
        MigrateDal.update_history_by_id(history_id,
                                        migrate_rooms=json.dumps(src_rooms),
                                        migrate_isps=json.dumps(to_migrate_isps),
                                        dst_rooms=json.dumps(dst_rooms),
                                        migrate_info=json.dumps({}))
    else:
        MigrateDal.delete_history_by_id(history_id)
        raise BadParam("no domain can migrate, isp_rooms: %s"
                       % to_migrate_dict, msg_ch=u'没有可迁移的机房')

    history_info = get_migrate_info(history_id)
    return history_info
Example #3
0
    def loadDatasetToMLDB(cls):
        dataset_name = "null_column_test"
        cls.url = "http://localhost:%d/v1" % cls.port
        cls.dataset_url = cls.url + "/datasets/" + dataset_name
        requests.delete(cls.dataset_url)

        # Register the dataset
        data = json.dumps({
            "type": "sparse.mutable",
            "id": dataset_name,
        })
        requests.post(cls.url + "/datasets", data=data)

        # Fill the data
        #  ___________________
        # |     | col1 | col2 |
        #  -------------------
        # | r1  |  1   |      |
        #  -------------------
        # | r2  |  1   |  2   |
        #  -------------------

        ts = datetime.datetime.now().isoformat(' ')

        cols = [['col1', 1, ts]]
        data = {"rowName": "r1", "columns": cols}
        requests.post(cls.dataset_url + "/rows", json.dumps(data))

        cols = [['col1', 1, ts], ['col2', 2, ts]]
        data = {"rowName": "r2", "columns": cols}
        requests.post(cls.dataset_url + "/rows", json.dumps(data))

        # Commit the dataset
        requests.post(cls.dataset_url + "/commit")
Example #4
0
def main():
    args_file = sys.argv[1]
    args_data = file(args_file).read()
    arguments = shlex.split(args_data)
    worker = 'all'
    action = WorkItemList.display

    for arg in arguments:
        # ignore any arguments without an equals in it
        if '=' in arg:
            (key, value) = arg.split('=')
            if key == 'worker':
                worker = workers[value]
            if key == 'action':
                if value == 'create':
                    action = WorkItemList.create
                elif value == 'teardown':
                    action = WorkItemList.teardown
                elif value == 'display':
                    action = WorkItemList.display

    logging.basicConfig(level=logging.ERROR)

    action(worker)
    print json.dumps({
        'success': True,
        'args': args_data
    })
def add_plan(request, access_token):
	result = login_auth(access_token)
	if result['err']['code'] != 0:
		return HttpResponse(json.dumps(result))	
	userid = result['data']['id']
	try:
		new_plan = Plan()
		user = FBUser.objects.get(fbid=userid)
		new_plan.holder = user
		new_plan.title = request.POST.get('title', "testtitle")
		new_plan.destination = request.POST.get('destination', "testdestination")
		new_plan.description = request.POST.get('description', "testdescription")
		new_plan.depart_time = request.POST.get('depart_time', datetime.today())
		new_plan.length = request.POST.get('length', 2)
		new_plan.limit = request.POST.get('limit', 2)
		visible_type = request.POST.get('visible_type', 1)
		new_plan.visible_type = int(visible_type)
		friend_list = request.POST.getlist('friendlist',[])
		new_plan.full_clean()
		new_plan.save()
		if new_plan.visible_type == 3:
			for friendid in friend_list:
				friend = FBUser.objects.get(fbid=friendid)
				private = PrivatePlan()
				private.accessible_user = friend
				private.accessible_plan = new_plan
				private.full_clean()
				private.save()
		result = format(0, 'create success')
		return HttpResponse(json.dumps(result))	
	except Exception as e:
   		result = format(400, str(e))
        return HttpResponse(json.dumps(result))	
Example #6
0
def loggedIn():
  if 'credentials' not in flask.session:
    return json.dumps({"loggedIn":False})
  elif client.OAuth2Credentials.from_json(flask.session['credentials']).access_token_expired:
    return json.dumps({"loggedIn":False})
  else:
    return json.dumps({"loggedIn":True})
Example #7
0
def send_data(save_path):
    """
    Sends all the data files that are present in the specified path to the Qbike server.
    :param save_path: Requires the path in which the trips are saved.
    :return: Nothing. The data is sent to the Server and the txt files are removed from the path's directory.
    """
    end = False
    Trip_nb = 100
    while end == False:
        if not os.path.isfile('C:\Users\Joren\Documents\Ir 1B\P&O\P&O 3\Tryouts\Trips\Trip1.txt'):
            end = True

        else:
            for nb in reversed(range(0, 100)):
                Trip = os.path.join(save_path, "Trip" + str(nb) + ".txt")
                Trip_nb = str(nb)
                if os.path.isfile(Trip):
                    break

            Trip_path = os.path.join(save_path, r"Trip" + Trip_nb + r".txt")

            with open(Trip_path, "r") as Trip:
                batch = json.load(Trip)

            info = {'purpose': 'batch-sender', 'groupID': "cwa2", 'userID': ID}
            socketIO = SocketIO('dali.cs.kuleuven.be', 8080)
            socketIO.on('server_message', on_response)
            socketIO.emit('start', json.dumps(info), on_response)
            socketIO.wait(2)
            socketIO.emit('batch-tripdata', json.dumps(batch), on_response)
            socketIO.wait(5)

            os.remove(Trip_path)

    print "Sent Data"
 def _get_field_values(self):
     values = {}
     vocabularies_resource = get_resource_service('vocabularies')
     values['anpa_category'] = vocabularies_resource.find_one(req=None, _id='categories')['items']
     req = ParsedRequest()
     req.where = json.dumps({'$or': [{"schema_field": "genre"}, {"_id": "genre"}]})
     genre = vocabularies_resource.get(req=req, lookup=None)
     if genre.count():
         values['genre'] = genre[0]['items']
     values['urgency'] = vocabularies_resource.find_one(req=None, _id='urgency')['items']
     values['priority'] = vocabularies_resource.find_one(req=None, _id='priority')['items']
     values['type'] = vocabularies_resource.find_one(req=None, _id='type')['items']
     subject = vocabularies_resource.find_one(req=None, schema_field='subject')
     if subject:
         values['subject'] = subject['items']
     else:
         values['subject'] = get_subjectcodeitems()
     values['desk'] = list(get_resource_service('desks').get(None, {}))
     values['stage'] = self._get_stage_field_values(values['desk'])
     values['sms'] = [{'qcode': 0, 'name': 'False'}, {'qcode': 1, 'name': 'True'}]
     values['embargo'] = [{'qcode': 0, 'name': 'False'}, {'qcode': 1, 'name': 'True'}]
     req = ParsedRequest()
     req.where = json.dumps({'$or': [{"schema_field": "place"}, {"_id": "place"}, {"_id": "locators"}]})
     place = vocabularies_resource.get(req=req, lookup=None)
     if place.count():
         values['place'] = place[0]['items']
     values['ingest_provider'] = list(get_resource_service('ingest_providers').get(None, {}))
     return values
Example #9
0
 def save_logs(self, actions_log_path=None, http_request_log_path=None):
     if http_request_log_path:
         open(http_request_log_path, 'w').write(json.dumps(
                 self.http_request_log))
     if actions_log_path:
         open(actions_log_path, 'w').write(json.dumps({ 'actions':
                                                        self.actions }))
Example #10
0
    def updateEventRanges(self, event_ranges):
        """ Update an event range on the Event Server """
        pUtil.tolog("Updating event ranges..")

        message = ""
        #url = "https://aipanda007.cern.ch:25443/server/panda"
        url = "https://pandaserver.cern.ch:25443/server/panda"
        # eventRanges = [{'eventRangeID': '4001396-1800223966-4426028-1-2', 'eventStatus':'running'}, {'eventRangeID': '4001396-1800223966-4426028-2-2','eventStatus':'running'}]

        node={}
        node['eventRanges']=json.dumps(event_ranges)

        # open connection
        ret = pUtil.httpConnect(node, url, path=self.__updateEventRangesDir, mode="UPDATEEVENTRANGES")
        # response = json.loads(ret[1])

        status = ret[0]
        if ret[0]: # non-zero return code
            message = "Failed to update event range - error code = %d, error: " % (ret[0], ret[1])
        else:
            response = json.loads(json.dumps(ret[1]))
            status = int(response['StatusCode'])
            message = json.dumps(response['Returns'])

        return status, message
Example #11
0
File: as.py Project: Newky/4thYear
    def handle_ticket(self):
	if "service" in self.jdata:
		if "name" in self.jdata:
			#Note the is_server part, if the request comes from one its own servers.
			if (self.jdata["name"] in names or is_server(self.jdata["name"])) and self.jdata["service"] in services:
				session_key = generate_session_key()
				#Cache the users ip address and session key.
				users[str(self.client_address[0])] = (session_key)
				ticket = [session_key]
				#Randomly choose a server for the request service
				server_id = random.choice(services[self.jdata["service"]])
				server_key = server_id[2]
				server_id = (server_id[0], server_id[1])	
				ticket = secure.encrypt_with_key(json.dumps(ticket), server_key)
				jsonresult = {
					"ticket": ticket,
					"session": session_key,
					"server_id": server_id
				}
				#if a known client
				if(self.jdata["name"] in names):
					data = secure.encrypt_with_key(json.dumps(jsonresult), names[self.jdata["name"]])
				else:
					#we have already checked that its a valid server.
					#Just need to extract its password from the config file.
					pwd = extract_password_from_server(self.jdata["name"])
					data = secure.encrypt_with_key(json.dumps(jsonresult), pwd)
				self.request.send(data)
				return

	self.request.send("[]")
Example #12
0
def deferred_consume_artist_albums(artist_url, response_url=None):
    try:
        existing_albums = list_model.get_list()
        artist_albums = bandcamp.scrape_bandcamp_album_ids_from_artist_page(artist_url)
        new_album_ids = [album_id for album_id in artist_albums if album_id not in existing_albums]
        if response_url and new_album_ids:
            requests.post(response_url,
                          data=json.dumps({'text': f':full_moon: found {len(new_album_ids)} new albums to process...'}))
        elif response_url:
            requests.post(response_url, data=json.dumps({'text': f':new_moon: found no new albums to process'}))
    except DatabaseError as e:
        print('[db]: failed to check existing items')
        print(f'[db]: {e}')
    except NotFoundError:
        print(f'[scraper]: no albums found for artist at {artist_url}')
        if response_url:
            requests.post(response_url, data=json.dumps({'text': ':red_circle: failed to find any albums'}))
    else:
        for new_album_id in new_album_ids:
            try:
                list_model.add_to_list(new_album_id)
                deferred_process_album_details.delay(str(new_album_id))
            except DatabaseError as e:
                print(f'[db]: failed to update list with {new_album_id} from {artist_url}')
                print(f'[db]: {e}')
        if response_url and new_album_ids:
            requests.post(response_url,
                          data=json.dumps({'text': f':full_moon_with_face: done processing artist albums'}))
Example #13
0
def deferred_scrape_channel(scrape_function, callback, channel_id, slack_token, channel_name=None, response_url=None):
    try:
        slack = slacker.Slacker(slack_token)
        if response_url:
            requests.post(response_url,
                          data=json.dumps({'text': f'Getting channel history for {channel_name or channel_id}...'}))
        response = slack.channels.history(channel_id)
    except (KeyError, slacker.Error) as e:
        message = 'There was an error accessing the Slack API'
        if response_url:
            requests.post(response_url, data=json.dumps({'text': message}))
        raise e
    if response.successful:
        messages = response.body.get('messages', [])
        if response_url:
            requests.post(response_url, data=json.dumps({'text': f'Scraping {channel_name or channel_id}...'}))
        album_ids = scrape_function(messages)
        new_album_ids = list_model.check_for_new_list_ids(album_ids)
        try:
            if new_album_ids:
                callback(new_album_ids)
                print(f'[scraper]: {len(new_album_ids)} new albums found and added to the list')
                deferred_process_all_album_details.delay(None)
        except DatabaseError as e:
            message = 'failed to update list'
            print(f'[db]: failed to perform {callback.__name__}')
            print(f'[db]: {e}')
        else:
            message = f'Finished checking for new albums: {len(new_album_ids)} found in {channel_name or channel_id}'
    else:
        message = f'failed to get channel history for {channel_name or channel_id}'
    if response_url:
        requests.post(response_url, data=json.dumps({'text': message}))
Example #14
0
    def pretty_log(self, args, kwargs, resp, body):
        if not _logger.isEnabledFor(logging.DEBUG):
            return

        string_parts = ['curl -i']
        for element in args:
            if element in ('GET', 'POST'):
                string_parts.append(' -X %s' % element)
            else:
                string_parts.append(' %s' % element)

        for element in kwargs['headers']:
            header = ' -H "%s: %s"' % (element, kwargs['headers'][element])
            string_parts.append(header)

        curl_cmd = "".join(string_parts)
        _logger.debug("REQUEST:")
        if 'body' in kwargs:
            _logger.debug("%s -d '%s'" % (curl_cmd, kwargs['body']))
            try:
                req_body = json.dumps(json.loads(kwargs['body']),
                                      sort_keys=True, indent=4)
            except:
                req_body = kwargs['body']
            _logger.debug("BODY: %s\n" % (req_body))
        else:
            _logger.debug(curl_cmd)

        try:
            resp_body = json.dumps(json.loads(body), sort_keys=True, indent=4)
        except:
            resp_body = body
        _logger.debug("RESPONSE HEADERS: %s" % resp)
        _logger.debug("RESPONSE BODY   : %s" % resp_body)
Example #15
0
    def saveList(self):
        nameOfList = self.LNEDTlistName.text()
        restsOfEachDay = self.collect_restaurants()
        foods = self.collect_foods()
        pyJson = {}
        pyJson["version"]=self.form_data_version
        pyJson["restsOfEachDay"] = restsOfEachDay
        pyJson["foods"] = foods
        # write json file
        json_file = json.dumps(pyJson)
        file = open('./foodlists/' + nameOfList + '.json', 'w')
        file.write(json_file)  #write database to file
        file.close()

        json_file = open('./foodlists/' + nameOfList + ".json", "r")
        json_decoded = json.load(json_file)
        json_file.close()

        datas_file = open('./data/_lisnamedata', "r+")
        datas_decoded = json.load(datas_file)
        if nameOfList.upper() not in (name.upper() for name in datas_decoded["listNames"]):
            datas_decoded["listNames"].append(nameOfList)
            # self.CMBXlists.addItem(nameOfList)
            # self.CMBXeditLists.addItem(nameOfList)

        datas_file.seek(0, 0)  #go to begining of file
        datas_file.write(json.dumps(datas_decoded))
        datas_file.close()
        self.fill_list_of_listname()
        self.showInfoMessage(u" لیست جدید",nameOfList+u" ذخیره شد ")
Example #16
0
	def __authCall(self, call, params={}, item="BTC", currency=""):
		# https://en.bitcoin.it/wiki/MtGox/API/Streaming#Authenticated_commands
		# If 'Invalid call' remark is received, this is probably due to a bad nonce.
		nonce =  self.__getNonce()
		requestId = get_hex_md5(str(nonce))
		requestDict = {
				"id":requestId,
				"call":call,
				"nonce":nonce,
				"params":params,
				"item":item,
				"currency":currency,
				}
		request = json.dumps(requestDict)

		# https://en.bitcoin.it/wiki/MtGox/API/HTTP
		binaryKey = apikey_as_binary(self.__apiKey)
		signature = sign_request(request, self.__apiSecret)
		requestDict = {
				"op":"call",
				"id":requestId,
				"call":base64.b64encode(binaryKey + signature + request),
				"context":"mtgox.com",
				}
		msg = json.dumps(requestDict)
		self.send(msg, False)
		return requestId
Example #17
0
    def setUp(self):
        self.username = "test"
        self.email = "mailto:test@example.com"        
        self.password = "test"
        self.auth = "Basic %s" % base64.b64encode("%s:%s" % (self.username, self.password))
        form = {'username':self.username,'email': self.email,'password':self.password,'password2':self.password}
        response = self.client.post(reverse(views.register),form, X_Experience_API_Version="1.0.0")


        self.testparams1 = {"stateId": self.stateId, "activityId": self.activityId, "agent": self.testagent}
        path = '%s?%s' % (self.url, urllib.urlencode(self.testparams1))
        self.teststate1 = {"test":"put activity state 1","obj":{"agent":"test"}}
        self.put1 = self.client.put(path, json.dumps(self.teststate1), content_type=self.content_type, Authorization=self.auth, X_Experience_API_Version="1.0.0")

        self.testparams2 = {"stateId": self.stateId2, "activityId": self.activityId, "agent": self.testagent}
        path = '%s?%s' % (self.url, urllib.urlencode(self.testparams2))
        self.teststate2 = {"test":"put activity state 2","obj":{"agent":"test"}}
        self.put2 = self.client.put(path, json.dumps(self.teststate2), content_type=self.content_type, Authorization=self.auth, X_Experience_API_Version="1.0.0")

        self.testparams3 = {"stateId": self.stateId3, "activityId": self.activityId2, "agent": self.testagent}
        path = '%s?%s' % (self.url, urllib.urlencode(self.testparams3))
        self.teststate3 = {"test":"put activity state 3","obj":{"agent":"test"}}
        self.put3 = self.client.put(path, json.dumps(self.teststate3), content_type=self.content_type, Authorization=self.auth, X_Experience_API_Version="1.0.0")

        self.testparams4 = {"stateId": self.stateId4, "activityId": self.activityId2, "agent": self.otheragent}
        path = '%s?%s' % (self.url, urllib.urlencode(self.testparams4))
        self.teststate4 = {"test":"put activity state 4","obj":{"agent":"other"}}
        self.put4 = self.client.put(path, json.dumps(self.teststate4), content_type=self.content_type, Authorization=self.auth, X_Experience_API_Version="1.0.0")
Example #18
0
def main(argv):
   #put(service)
   flags = parser.parse_args(argv[1:])


  #sample.dat file stores the short lived access tokens, which your application requests user data, attaching the access token to the request.
  #so that user need not validate through the browser everytime. This is optional. If the credentials don't exist
  #or are invalid run through the native client flow. The Storage object will ensure that if successful the good
  # credentials will get written back to the file (sample.dat in this case).
   storage = file.Storage('sample.dat')
   credentials = storage.get()
   if credentials is None or credentials.invalid:
    credentials = tools.run_flow(FLOW, storage, flags)

  # Create an httplib2.Http object to handle our HTTP requests and authorize it
  # with our good Credentials.
   http = httplib2.Http()
   http = credentials.authorize(http)

  # Construct the service object for the interacting with the Cloud Storage API.
   service = discovery.build('storage', _API_VERSION, http=http)
#def put(service):
   starting_time=time.time()
   fileupload=raw_input("please enter the name of the file")

   req = service.objects().insert(
        bucket=_BUCKET_NAME,
        name=fileupload,media_body='all_month.csv')
   resp = req.execute()
   ending_time=time.time()-starting_time
   print ending_time
   fields_to_return = 'nextPageToken,items(bucket,name,metadata(my-key))'

   print json.dumps(resp, indent=2)
Example #19
0
    def post(self, *args, **kwargs):
        self.set_header("Content-Type", "application/json")

        try:
            data = json.loads(self.request.body.decode("utf8"))
            conv = Conveyance(data)
            compose = conv.compose()(conv.definitions, conv.resources)
        except (ValidationError, jsonschema.ValidationError) as e:
            # print('this')
            # raise tornado.web.HTTPError(404, reason=e.args[0])
            # compose = {
            #     "validation_error": e
            # }

            self.set_status(401)
            self.set_header('WWW-Authenticate', 'Basic realm="something"')
            data = {
                "error": str(e)
            }
            self.write(json.dumps(data))
            raise tornado.web.Finish()
        except:
            self.set_status(401)
            self.set_header('WWW-Authenticate', 'Basic realm="something"')
            data = {
                "error": sys.exc_info()[0]
            }
            self.write(json.dumps(data))
            raise tornado.web.Finish()


        self.write(json.dumps(compose))
Example #20
0
    def test_ng_save_create(self):
        # CRUDTestViewWithFK
        request = self.factory.post('/crud/',
                                    data=json.dumps({'name': 'Leonard'}),
                                    content_type='application/json')
        response = CRUDTestView.as_view()(request)
        data = json.loads(response.content.decode('utf-8'))
        pk = data['pk']

        request2 = self.factory.get('/crud/?pk={0}'.format(pk))
        response2 = CRUDTestView.as_view()(request2)
        data2 = json.loads(response2.content.decode('utf-8'))
        self.assertEqual(data2['name'], 'Leonard')

        # CRUDTestViewWithSlug
        request3 = self.factory.post('/crud/',
                                    data=json.dumps({'name': 'Leonard', 'email': 'Leonard@example.com'}),
                                    content_type='application/json')
        CRUDTestViewWithSlug.as_view()(request3)

        request4 = self.factory.get('/crud/?email={0}'.format('Leonard@example.com'))
        response4 = CRUDTestViewWithSlug.as_view()(request4)
        data4 = json.loads(response4.content.decode('utf-8'))
        self.assertEqual(data4['name'], 'Leonard')

        request5 = self.factory.post('/crud/',
                                    data=json.dumps({'name': 'Leonard2', 'email': 'Leonard@example.com'}),
                                    content_type='application/json')
        response5 = CRUDTestViewWithSlug.as_view()(request5)
        self.assertGreaterEqual(response5.status_code, 400)
        data5 = json.loads(response5.content.decode('utf-8'))
        self.assertTrue('detail' in data5 and 'email' in data5['detail'] and len(data5['detail']['email']) > 0)
Example #21
0
def handle(data, con, apikey=None):
  d = json.loads(data)

  handlers = {'import': importit, 'ping': ping,
      'listimported': listimported, 'slice': sliceit,
      'listdone': listdone, 'getdone': getdone,
      'importconfig': importconfig, 'listconfig': listconfigs,
      'listprogress': listprogress, 'getstats': getstats,
      'journal': getjournal, 'del': wipefile, 'wait': waitfor}

  hndlr = noop
  cmd = 'noop'
  if d.has_key('cmd'):
    if d['cmd'] in handlers.keys():
      cmd = d['cmd']
      hndlr = handlers[cmd]

  logging.info('cmd: ' + cmd)

  if not apikey is None:
    if not (d.has_key('key') and d['key'] == apikey):
      logging.info('authentication failed for "{}" key!'.format(
        '' if not d.has_key('key') else d['key']))
      return json.dumps({'r': 'fail',
        'm': 'authentication failed. incorrect apikey'})

  try:
    r = hndlr(d, con)
    result = json.dumps(r)
  except Exception as e:
    logging.error(str(e))
    result = json.dumps({u'm':unicode(e), u'r':u'fail'})
  logaccess(len(data), len(result), unicode(cmd), con)

  return result
Example #22
0
    def test_ng_save_update(self):
        # CRUDTestViewWithFK
        request = self.factory.post('/crud/?pk=1',
                                    data=json.dumps({'pk': 1, 'name': 'John2'}),
                                    content_type='application/json')
        response = CRUDTestView.as_view()(request)
        data = json.loads(response.content.decode('utf-8'))
        self.assertEqual(data['name'], 'John2')

        request2 = self.factory.get('/crud/?pk=1')
        response2 = CRUDTestView.as_view()(request2)
        data2 = json.loads(response2.content.decode('utf-8'))
        self.assertEqual(data2['name'], 'John2')

        # CRUDTestViewWithSlug
        request3 = self.factory.post('/crud/?pk=1',
                                    data=json.dumps({'name': 'John', 'email': 'John2@example.com'}),
                                    content_type='application/json')
        response3 = CRUDTestViewWithSlug.as_view()(request3)
        data3 = json.loads(response3.content.decode('utf-8'))
        self.assertEqual(data3['name'], 'John')
        self.assertEqual(data3['email'], 'John2@example.com')

        request4 = self.factory.get('/crud/?email=John2@example.com')
        response4 = CRUDTestViewWithSlug.as_view()(request4)
        data4 = json.loads(response4.content.decode('utf-8'))
        self.assertEqual(data4['name'], 'John')

        request5 = self.factory.post('/crud/?pk=3',  # Modifying "Chris"
                                    data=json.dumps({'pk': 4, 'name': 'John2', 'email': 'John2@example.com'}),
                                    content_type='application/json')
        response5 = CRUDTestViewWithSlug.as_view()(request5)
        self.assertGreaterEqual(response5.status_code, 400)
        data5 = json.loads(response5.content.decode('utf-8'))
        self.assertTrue('detail' in data5 and 'email' in data5['detail'] and len(data5['detail']['email']) > 0)
 def pretty_print(self, data):
     if data:
         print json.dumps(data, indent=4, separators=(',', ':'))
     elif self.response_body:
         print json.dumps(self.response_body, indent=4, separators=(',', ':'))
     else:
         print "No data to print..."
    def get(self):
        self._validate_tba_app_id()
        team_key = self.request.get('team')
        year = self.request.get('year')

        response_json = {}

        try:
            response_json = ApiHelper.getTeamInfo(team_key)
            if self.request.get('events'):
                response_json = ApiHelper.addTeamEvents(response_json, year)

            # TODO: matches

            self.response.out.write(json.dumps(response_json))

            track_team_key = team_key
            if year:
                track_team_key = track_team_key + ' (' + year + ')'
            self._track_call_defer('teams/details', track_team_key)

        except IndexError:
            response_json = {"Property Error": "No team found for the key given"}
            self.response.set_status(404)
            self.response.out.write(json.dumps(response_json))
def edit_plan(request, access_token, planid):
	result = login_auth(access_token)
	if result['err']['code'] != 0:
		return HttpResponse(json.dumps(result))	
	userid = result['data']['id']
	try:
		plan = Plan.objects.get(id__exact=planid)
		user = FBUser.objects.get(fbid=userid)
		PrivatePlan.objects.filter(accessible_plan=plan).delete()
		plan.holder = user
		plan.title = request.POST.get('title', plan.title)
		plan.destination = request.POST.get('destination', plan.destination)
		plan.description = request.POST.get('description', plan.description)
		plan.depart_time = request.POST.get('depart_time', plan.depart_time)
		plan.length = request.POST.get('length', plan.length)
		plan.limit = request.POST.get('limit', plan.limit)
		visible_type = request.POST.get('visible_type', plan.visible_type)
		plan.visible_type = int(visible_type)
		friend_list = request.POST.getlist('friendlist', [])
		plan.full_clean()
		plan.save()
		if plan.visible_type == 3:
			for friendid in friend_list:
				friend = FBUser.objects.get(fbid=friendid)
				private = PrivatePlan()
				private.accessible_user = friend
				private.accessible_plan = plan
				private.full_clean()
				private.save()
		result = format(0, 'edit success')
		return HttpResponse(json.dumps(result))	
	except Exception as e:
   		result = format(400, str(e))
        return HttpResponse(json.dumps(result))	
Example #26
0
def comment_it(request, f_id):
    user = auth.get_user(request)
    if request.method == 'POST':
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            comment = Comment(text=html.escape(comment_form.cleaned_data['text']),
                              author=user, film=Film.objects.get(pk=f_id))
            comment.save()
            response_data = {
                "code": 0,
                "response": "OK",
                "email": user.email,
                "text": html.escape(comment_form.cleaned_data['text']),
                "c_id": comment.id,
                "f_id": f_id,
                "is_staff": user.is_staff,
            }
            return HttpResponse(json.dumps(response_data),
                                content_type="application/json")
        else:
            return HttpResponse(json.dumps({"code": 0, "response": "Not valid"}),
                                content_type="application/json")

    else:
        return redirect('/plitka/filmbody/%s' % f_id)
Example #27
0
 def test_query(self):
     j = self._api.new_job(self.VALID_QUERY)
     print(json.dumps(j))
     job_id = j["job_id"]
     r = self._api.check_job_loop(job_id)
     print(json.dumps(r))
     print(json.dumps(self._api.get_results(job_id, 1)))
Example #28
0
def markit(request, f_id):
    if request.method == 'POST':
        mark_form = MarkForm(request.POST)
        if mark_form.is_valid():
            film = Film.objects.get(pk=f_id)
            user = auth.get_user(request)
            try:
                mark = Mark.objects.get(user=user, film=film)
                mark.number = mark_form.cleaned_data['number']
                mark.save()
                response_data = {
                    "code": 0,
                    "response": "OK",
                    "your_mark": mark.number,
                    "average_mark": Mark.objects.average_mark(f_id),
                }
                return HttpResponse(json.dumps(response_data),
                                    content_type="application/json")
            except Mark.DoesNotExist:
                mark = Mark(user=user, film=film, number=mark_form.cleaned_data['number'])
                mark.save()
                response_data = {
                    "code": 0,
                    "response": "OK",
                    "your_mark": mark.number,
                    "average_mark": Mark.objects.average_mark(f_id),
                }
                return HttpResponse(json.dumps(response_data),
                                    content_type="application/json")
        else:
            return HttpResponse(json.dumps({"code": 0, "response": "Not valid"}), content_type="application/json")
    else:
        return redirect('/plitka/filmbody/%s' % f_id)
Example #29
0
def push_notification(request):
    #You may or may not get the device ids. Make sure this parameter is optional
    #send to all who has registered for that app
    # Try different ios applications and store device ids and try to send PNs
    if request.method != 'POST':
        result = {'result': 'This is not the correct method use POST method instead GET method!'}
        return HttpResponse(json.dumps(result), content_type='application/json')
    data = eval(str(request.body))
    if not data.has_key('device_key') or not data.has_key('token') or not data.has_key('message'):
        result = {'result': 'Please pass the token provied by us along with the Device Keys and message!'}
        return HttpResponse(json.dumps(result), content_type='application/json')
    try:
        pem_certificate = P12Certificate.objects.get(emb_token=data['token'])
    except:
        result = {'result': 'Please check your token number!'}
        return HttpResponse(json.dumps(result), content_type='application/json')
    '''
    device = GCMDevice.objects.get(registration_id=gcm_reg_id)
    device.send_message({"foo": "bar"}) # The message will be sent and received as json.
    '''
    #device = APNSDevice.objects.get(registration_id=apns_token)
    device_keys = data['device_key']
    for device_key in device_keys:
        try:
            device = APNSDevice.objects.get(registration_id=device_key)
        except:
            device = APNSDevice.objects.create(registration_id=device_key)
        device.save()
        device.send_message(data['message'],  certificate=pem_certificate.pem_file) # The message may only be sent as text.

    result = {'result': 'successfully sent the push notification!'}
    return HttpResponse(json.dumps(result), content_type='application/json')
Example #30
0
 def get(self, action=None):
     self.set_header('Access-Control-Allow-Origin', '*')
     self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
     self.set_header('Access-Control-Max-Age', 1000)
     self.set_header('Access-Control-Allow-Headers', 'Authorization, Origin, X-Requested-With, Content-Type, Accept')
     self.set_header('Content-type', 'application/json')
     #print action
     if action is None: #send saved retentions list back
         self.write(json.dumps({"id": 1, "label": "first segment"}))
     elif action == "data": # get retention data
         start_date = self.get_argument("startDate", None)
         end_date = self.get_argument("endDate", None)
         unit = self.get_argument("unit", "day")
         return_event = self.get_argument("returnEvent", "any event")
         born_event = self.get_argument("bornEvent", 'request demo page')
         interval_count = self.get_argument("intervalCount", 10)
         data_as = self.get_argument("dataAs", 'number')
         by = self.get_argument("by", "")
         where = self.get_argument("where", "")
         viz = self.get_argument("viz", "bar")
         # call the service to get  data
         if return_event == 'any event':
             return_event = None
         retention_data = self.analytics.get_retention_data(born_event, start_date, end_date, 
                     unit, int(interval_count), data_as, return_event, by, where, viz)
         #print segments_data
         self.write(json.dumps(retention_data))