def __init__(self, url, username, password): self.client = coreapi.Client() self.url = url result = requests.request('POST', url + '/api/v1/token/', data={ 'username': username, 'password': password }) b = result.json() auth = coreapi.auth.TokenAuthentication(token=b['token']) self.client = coreapi.Client(auth=auth)
def connect_client(self): logger.info("Node.connect_client, start of") logger.info("Node.connect_client, trying to reach : {}".format( self.hostname)) assert self.node_connection is not None, "NodeConnection.connect_client, node_connection is None" try: self.node_connection.ready_for_connect() except AssertionError as aerr: logger.error( "Node.connect_client, connection data not properly filled") logger.error("Node.connect_client, {}".format(aerr)) raise aerr node_client = coreapi.Client() node_schema = node_client.get(self.hostname) logger.info("####Not Logged schema") logger.info(node_schema) action = ['api-token-auth', 'create'] node_user = self.node_connection.get_user() params = { 'username': node_user['username'], 'password': node_user['pwd'] } try: logger.info("Node.connect_client, getting token") result = node_client.action(node_schema, action, params) logger.info("Node.connect_client, new token {}".format(result)) except coreapi.exceptions.ErrorMessage as err: logger.error("Node.connect_client : {}".format(err.error)) raise err auth = coreapi.auth.TokenAuthentication(scheme='JWT', token=result['token']) logger.info("Node.connect_client, creating authenticated client") node_client = coreapi.Client(auth=auth) node_schema = node_client.get(self.hostname) logger.info("####Logged in schema") logger.info(node_schema) logger.info( "Node.connect_client, store user,client,schema and token in connection object" ) self.node_connection = NodeConnection(user=node_user, client=node_client, schema=node_schema, token=result['token']) logger.info("Node.connect_client, end of") return None
def test_client_connection(): client = coreapi.Client() schema = client.get('http://fas.42king.com:8197/api/schema/') action = ['token', 'create'] params = {'username': "******", 'password': '******'} result = client.action(schema, action, params) action = ['login', 'create'] print(result) auth = coreapi.auth.TokenAuthentication(scheme='OAUTH', token=result['token']) result = client.action(schema, action, params) print(result) clent = coreapi.Client(auth=auth) print(client.get('http://fas.42king.com:8197/api/apps/'))
def main(self): recentmjd = date_to_mjd(datetime.datetime.utcnow() - datetime.timedelta(14)) survey_obs = SurveyObservation.objects.filter(obs_mjd__gt=recentmjd) field_pk = survey_obs.values('survey_field').distinct() survey_fields = SurveyField.objects.filter(pk__in = field_pk).select_related() for s in survey_fields: width_corr = 3.1/np.abs(np.cos(s.dec_cen)) ra_offset = Angle(width_corr/2., unit=u.deg) dec_offset = Angle(3.1/2., unit=u.deg) sc = SkyCoord(s.ra_cen,s.dec_cen,unit=u.deg) ra_min = sc.ra - ra_offset ra_max = sc.ra + ra_offset dec_min = sc.dec - dec_offset dec_max = sc.dec + dec_offset result_set = [] for page in range(500): print(s,page) marsurl = '%s/?format=json&sort_value=jd&sort_order=desc&ra__gt=%.7f&ra__lt=%.7f&dec__gt=%.7f&dec__lt=%.7f&jd__gt=%i&rb__gt=0.5&page=%i'%( self.options.ztfurl,ra_min.deg,ra_max.deg,dec_min.deg,dec_max.deg,recentmjd+2400000.5,page+1) client = coreapi.Client() try: schema = client.get(marsurl) if 'results' in schema.keys(): result_set = np.append(result_set,schema['results']) else: break except: break #break transientdict,nsn = self.parse_data(result_set,date_to_mjd(datetime.datetime.utcnow() - datetime.timedelta(2))) print('uploading %i transient detections'%nsn) self.send_data(transientdict)
def queryApi(date): # lambda function to check the rate exists in the fetched data exists = lambda x, y: y[x] if x in y else None # Coreapi fetches an OrderedDict client = coreapi.Client() result = client.get('https://api.fixer.io/{}?base=USD'.format( date.strftime("%Y-%m-%d"))) latest = rates( date=datetime.datetime.strptime(result['date'], '%Y-%m-%d'), curencyAUD=exists('AUD', result['rates']), curencyCAD=exists('CAD', result['rates']), curencyCHF=exists('CHF', result['rates']), curencyCNY=exists('CNY', result['rates']), curencyEUR=exists('EUR', result['rates']), curencyGBP=exists('GBP', result['rates']), curencyNZD=exists('NZD', result['rates']), curencyZAR=exists('ZAR', result['rates']), ) try: latest.save() except: pass return latest
def getNearbyRestautants(request): client = coreapi.Client() schema = client.get( 'https://maps.googleapis.com/maps/api/place/nearbysearch/json') data = request.data location = (data['lat'], data['lng']) radius = 3000 placetype = 'restaurant' key = '' params = { "location": location, "radius": radius, "type": placetype, "key": key } #result = client.action(schema, [], params) results = datajson.data['results'] toreturn = [] for place in results: obj = {} obj['location'] = place['geometry']['location'] obj['name'] = place['name'] obj['place_id'] = place['place_id'] ecart = distance( lonlat(*(data['lng'], data['lat'])), lonlat(*(place['geometry']['location']['lng'], place['geometry']['location']['lat']))) obj['distance'] = ecart.miles toreturn.append(obj) return Response(toreturn)
def create(self, validated_data): #CALL API TO GET THE CURRENT PATIENT now = datetime.datetime.now() date = str(now.strftime("%Y-%m-%d")) time = str(now.strftime("%H:%M:%S")) tempTime = validated_data.get('time', '') if str(tempTime) == "23:59:59": hr = HeartRateEveryMinute( heartRate=validated_data.get('heartRate', ''), date=date, time=time, idPatient_id=10, ) hr.save() # return hr else: client = coreapi.Client() schema = client.get("http://192.168.100.214:8000/docs") action = ["patient", "list"] result = client.action(schema, action) patient = result[0]['idPatient'] hr = HeartRateEveryMinute( heartRate=validated_data.get('heartRate', ''), date=validated_data.get('date', ''), time=validated_data.get('time', ''), idPatient_id=patient, ) hr.save() return hr
def readRFID(): arduino = serial.Serial('/dev/ttyUSB1/', 9600, timeout=.1) store = "" value = "" while(True): try: store = arduino.readline() time.sleep(1) store = arduino.readline() ## print(store) value = store.decode('utf-8') if value != "": print("HI") client = coreapi.Client() # schema = client.get("http://192.168.100.222:8000/docs") schema = client.get("http://192.168.100.222:8000/docs") action = ["rfid","create"] params = { "RFIDnumber": value, } result = client.action(schema,action,params=params) except: print("Cannot read arduino")
def sendData(): threading.Timer(1.0, sendData).start() client = coreapi.Client() tempSchema = client.get("http://192.168.100.222:8000/docs") tempAction = ['temperature','create'] tempParams = { "temperature":33.1, "date": "2018-10-10", "time": "23:59:59" } hrResult = client.action(tempSchema, tempAction, params = tempParams) hrAction = ['heartrate','create'] hrParams = { "heartRate": 73, "date": "2018-10-10", "time": "23:59:59" } hrResult = client.action(tempSchema, hrAction, params = hrParams) posAction = ['position','create'] posParams = { "position": "back", "date": "2018-10-10", "time": "23:59:59", }
def inventory_list(request): client = coreapi.Client() schema = client.get("http://35.227.154.9:8080/api-doc/") action = ["stock", "list"] params = { "page": '1', # "quantity": ..., # "part": ..., # "location": ..., # "min_stock": ..., # "max_stock": ..., } result = client.action(schema, action, params=params) #Iterates over list to access OrderedDict() object. for item in result: print(item['url']) print("--------------") ###Screwed this up. Just use the damn OrderedDict(...) ###by iterating the list.. #Removes OrderedDict(...) #data = json.dumps(result) #Removes Unnecessary [] #data = json.loads(data[1:-1]) return render(request, 'inventory/createItem.html')
def login(opt, client, schema): while True: username = input('username:'******'password:'******'username or password not valid') continue params = {'username': username, 'password': password} try: action = ['login', 'create'] result = client.action(schema, action, params) action = ['token', 'create'] result = client.action(schema, action, params) print(formHeader()) except Exception as e: print(e) print('validation failed') return False global SESSION_TOKEN SESSION_TOKEN = result['token'] print(SESSION_TOKEN, formHeader()) auth = coreapi.auth.TokenAuthentication(scheme='OAUTH', token=SESSION_TOKEN) client = coreapi.Client(auth=auth) print(username + ' logged in') return True #{'client':client}
def get_band_from_DB(self,fieldname,instrumentid,debug=False): tablename = 'photometricbands' if debug: tstart = time.time() auth = coreapi.auth.BasicAuthentication( username=self.dblogin, password=self.dbpassword, ) client = coreapi.Client(auth=auth) try: schema = client.get('%s%s?limit=100000'%(self.dburl,tablename)) except: raise RuntimeError('Error : couldn\'t get schema!') idlist,namelist,instlist = [],[],[] for i in range(len(schema['results'])): namelist += [schema['results'][i]['name']] idlist += [schema['results'][i]['url']] instlist += [schema['results'][i]['instrument']] if debug: print('GET took %.1f seconds'%(time.time()-tstart)) if not len(np.where((np.array(namelist) == fieldname) & (np.array(instlist) == instrumentid))[0]): return(None) return(np.array(idlist)[np.where((np.array(namelist) == fieldname) & (np.array(instlist) == instrumentid))][0])
def __init__(self, token=None, domain=None): if token is None: token = os.getenv(self.CARAVAGGIO_TOKEN, None) if token is None: raise EnvironmentError("No {0} was found in the environment" ". Please, make sure you have define" " the {0} environment.".format( self.CARAVAGGIO_TOKEN)) if domain is None: domain = os.getenv(self.CARAVAGGIO_DOMAIN, self.default_domain) self.domain = domain auth = coreapi.auth.TokenAuthentication(scheme="Token", token=token) # Codecs are responsible for decoding a bytestring into a Document # instance, or for encoding a Document instance into a bytestring. decoders = list(codec_plugins.decoders.values()) self.client = coreapi.Client(decoders=decoders, auth=auth) if self.domain not in self.schemas: self.schema = self.client.get('{}{}swagger/?format=openapi'.format( self.domain, "/" if not self.domain.endswith("/") else "")) self.schemas[self.domain] = self.schema else: self.schema = self.schemas[self.domain]
def run_client(): t = True client = coreapi.Client() try: schema = client.get('http://fas.42king.com:8197/api/schema') print('Welcome to Krby CLI Client!') display(None, None, None) except Exception as e: print(e) print('server down for maintenence') t = False result = None while t: opt = input('$> ').split() opt.append(None) if opt[0] in func: result = func[opt[0]](opt[1], client, schema) if result == False: print('there was an error with your request') continue elif isinstance(result, dict): print('client updated with auth') client = result['client'] schema = client.get('http://fas.42king.com:8197/api/schema') elif result == 'exit': t = False print('Goodbye!')
def dispatch(self, request, *args, **kwargs): """Search and show results. If none, show near words.""" context = self.get_context_data(**kwargs) query = request.GET.get('q', None) lex_code = request.GET.get('l', '') if query is not None: client = coreapi.Client() schema = client.get(settings.LINGUATEC_LEXICON_API_URL) querystring_args = {'q': query, 'l': lex_code} url = schema['words'] + 'search/?' + \ urllib.parse.urlencode(querystring_args) response = client.get(url) results = response["results"] for word in results: self.groupby_word_entries(word) context.update({ 'query': query, 'results': results, 'selected_lexicon': lex_code, 'lexicons': get_lexicons(), }) if response["count"] == 0: context["near_words"] = utils.retrieve_near_words(query, lex_code) return TemplateResponse(request, 'linguatec_lexicon_frontend/search_results.html', context)
def getZTFPhotometry(self,sc): ztfurl = '%s/?format=json&sort_value=jd&sort_order=desc&cone=%.7f%%2C%.7f%%2C0.0014'%( self.ztfurl,sc.ra.deg,sc.dec.deg) client = coreapi.Client() schema = client.get(ztfurl) if 'results' in schema.keys(): PhotUploadAll = {"mjdmatchmin":0.01, "clobber":self.clobber} photometrydict = {'instrument':'ZTF-Cam', 'obs_group':'ZTF', 'photdata':{}} for i in range(len(schema['results'])): phot = schema['results'][i]['candidate'] PhotUploadDict = {'obs_date':jd_to_date(phot['jd']), 'band':'%s-ZTF'%phot['filter'], 'groups':[]} PhotUploadDict['mag'] = phot['magap'] PhotUploadDict['mag_err'] = phot['sigmagap'] PhotUploadDict['flux'] = None PhotUploadDict['flux_err'] = None PhotUploadDict['data_quality'] = 0 PhotUploadDict['forced'] = None PhotUploadDict['flux_zero_point'] = None PhotUploadDict['discovery_point'] = 0 photometrydict['photdata']['%s_%i'%(jd_to_date(phot['jd']),i)] = PhotUploadDict PhotUploadAll['ZTF'] = photometrydict return PhotUploadAll else: return None
def test_api_update_ed_signed(): ''' update ed_signed via API requires PVZDweb runnning on dev database (no fixture yet for this) ''' fn = Path(ed_path(22, dir=fixture_testdata_basedir())) with fn.open('rb') as fd: django_file = django.core.files.File(fd) mds = MDstatement() count = MDstatement.objects.filter( entityID='https://idp22.identinetics.com/idp.xml', statusgroup=STATUSGROUP_FRONTEND) if count: mds = MDstatement.objects.get( entityID='https://idp22.identinetics.com/idp.xml', statusgroup=STATUSGROUP_FRONTEND) mds.ed_signed = '' mds.save() else: django_file = django.core.files.File(fd) mds = MDstatement() mds.ed_file_upload.save(fn.name, django_file, save=True) update_id = mds.id client = coreapi.Client() schema = client.get("http://localhost:8000/docs/") action = ["mdstatement", "partial_update"] params = { "id": update_id, "admin_note": "Updated ed_signed from REST API", "ed_signed": fn.read_text(), } result = client.action(schema, action, params=params)
def main(): # Parse arguments args = parse_args() # Globals global client client = coreapi.Client() global codec codec = coreapi.codecs.CoreJSONCodec() global cwd cwd = os.getcwd() global devnull devnull = subprocess.DEVNULL global jaspar_url jaspar_url = "https://testjaspar.uio.no/" global clusters_file_ext clusters_file_ext = ".clusters.json" global pfam_file_ext pfam_file_ext = ".pfam.json" global profiles_file_ext profiles_file_ext = ".profiles.json" global uniprot_file_ext uniprot_file_ext = ".uniprot.json" out_dir = os.path.abspath(args.o) # Get files get_files(out_dir)
def __init__(self, api_url, username=None, password=None): """ Set up authentication using basic authentication. """ # Create session and give it with auth self.session = requests.Session() if username is not None and password is not None: self.session.auth = (username, password) # Tell Tantalus we're sending JSON self.session.headers.update({"content-type": "application/json"}) # Record the base API URL self.base_api_url = api_url self.document_url = self.base_api_url + "swagger/?format=openapi" auth = None if username is not None and password is not None: auth = coreapi.auth.BasicAuthentication(username=username, password=password) decoders = [OpenAPICodec(), JSONCodec()] self.coreapi_client = coreapi.Client(auth=auth, decoders=decoders) self.coreapi_schema = self.coreapi_client.get(self.document_url, format="openapi")
def book_list(request): auth = coreapi.auth.BasicAuthentication( username='******', password='******' ) client = coreapi.Client(auth=auth) schema = client.get('http://localhost:8000/book/') # users = client.action(schema, ['users', 'list']) # users = client.action(schema) print('----------------pld----------------------') od = OrderedDict(schema) r = od['results'] # print(schema) result_list: list = list() for key in r: author = key['author'] print(key['title']) print(key['summary']) print(key['isbn']) print(key['author']) result_list.append((key['title'], key['author'], key['summary'], key['isbn'])) print(' .......') print('--------------------------------------') paginator = Paginator(result_list, 30) # Show 30 contacts per page. page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, "showstore/book_list.html", {'page_obj': page_obj})
def main(): parser = argparse.ArgumentParser( description="Use OMA api to download OMA groups by their id") parser.add_argument( "-i", "--ids", type=str, nargs='+', default=None, required=True, help="group ids, needs at least one, multiple divided by spaces") parser.add_argument( "-o", "--outpath", type=str, default='.', help= "folder where fasta files will be written, all fasta file will be named after their " "group id") args = parser.parse_args() client = coreapi.Client() schema = client.get("https://omabrowser.org/api/docs") for groupid in args.ids: print('Getting: ' + groupid) getomagroup(groupid, args.outpath, client, schema) print('done!')
def __init__(self) -> None: super().__init__() self.client = coreapi.Client(auth=coreapi.auth.BasicAuthentication( username=os.getenv('API_NAME'), password=os.getenv('API_PASS') )) self.schema = self.client.get(os.getenv('API_URL'))
def get_client(format=None): codecs = get_installed_codecs() if format is None: decoders = list(codecs.values()) else: decoders = [codecs[format]] return coreapi.Client(decoders=decoders)
def home(request): client = coreapi.Client() schema = client.get('http://127.0.0.1:8000/pool/poolservices/') # pools = client.action(schema, ['post'], params={"PoolService":{"method":"get"}}) return render(request, 'pool_2/index.html', { 'id': 2, # 'text': pools })
def __init__(self, url, username, password): # Basic auth only auth = coreapi.auth.BasicAuthentication( username=username, password=password ) self.client = coreapi.Client(auth=auth) self.url = url
def create_infra_client(): credentials = { settings.INFRA_IP: 'Token {}'.format(settings.INFRA_AUTH_TOKEN) } transports = [coreapi.transports.HTTPTransport(credentials=credentials)] client = coreapi.Client(transports=transports) schema = client.get(settings.INFRA_API_SCHEMA_ADDRESS) return client, schema
def __init__(self, token=None): # Default to environment variable, if no token was provided. if token is None: token = os.environ['HEROKU_TOKEN'] self.__token = token self.client = coreapi.Client(auth=self) self.schema = self.load(self.schema_url)
def save_video(url, languages): client = coreapi.Client() normalized_url = query_string_remove(url) schema = client.get(normalized_url) soup = BeautifulSoup(schema, "html.parser") video_meta_unprocessed = soup.find("div", attrs={ "itemscope": True, "itemtype": "https://schema.org/VideoObject" }) video_meta = BeautifulSoup(str(video_meta_unprocessed), "html.parser") duration = video_meta.find("meta", attrs={"itemprop": "duration"})["content"] license_url = video_meta.find("link", attrs={"itemprop": "license"})["href"] title = video_meta.find("meta", attrs={"itemprop": "name"})["content"] description = video_meta.find("meta", attrs={"itemprop": "description"})["content"] script_unprocessed = str(soup.find("script", attrs={"data-spec": "q"})) openIndex = script_unprocessed.index('{') closeIndex = script_unprocessed.rindex('}') jsonSubstring = script_unprocessed[openIndex:closeIndex + 1] talk_meta = json.loads(jsonSubstring)["__INITIAL_DATA__"] video_id = talk_meta["current_talk"] url = talk_meta["url"] viewed_count = talk_meta["viewed_count"] event = talk_meta["event"] speakers = [] for speaker in talk_meta["speakers"]: name = construct_name(speaker) speakers.append(name) video = Video(video_id=video_id, duration=duration, url=url, license_url=license_url, title=title, description=description, speakers=speakers, event=event, viewed_count=viewed_count) video.save() video_serializer = VideoSerializer(video) django_rq.enqueue(func=save_subtitles, args=[video_id, languages], retry=Retry(max=3, interval=[10, 30, 60])) print(video_serializer.data)
def ajaxAddPatient(request): firstName = request.GET.get('firstName') middleName = request.GET.get('middleName') lastName = request.GET.get('lastName') birthDate = request.GET.get('birthDate') religion = request.GET.get('religion') minTemp = request.GET.get('minTemp') maxTemp = request.GET.get('maxTemp') minHeartRate = request.GET.get('minHeartRate') maxHeartRate = request.GET.get('maxHeartRate') contactperson = request.GET.get('contactperson') contactNum = request.GET.get('contactNum') bedNumber = request.GET.get('bedNumber') bday = parse_date(birthDate) # age = (datetime.now().date() - bday).days / 365.25 print(bday) doctors = request.GET.getlist('doctors[]') patient_var = Patient(firstName=firstName, middleName=middleName, lastName=lastName, birthDate=birthDate, religion=religion, minTemp=minTemp, maxTemp=maxTemp, minHeartRate=minHeartRate, maxHeartRate=maxHeartRate, contactperson=contactperson, contactNum=contactNum, bedNumber_id=int(bedNumber), status="RESERVED") patient_var.save() patient_bed = Patient_Table(idBeds_id=bedNumber, idPatient_id=patient_var.pk) patient_bed.save() client = coreapi.Client() schema = client.get("http://192.168.100.214:8000/docs") action = ["patient", "create"] params = {"idPatient": patient_var.pk} result = client.action(schema, action, params=params) for x in range(0, len(doctors)): patient_doctor = Patient_Doctors(Doctor_id=doctors[x], Patient_id=patient_var.pk) patient_doctor.save() body = "Your patient, " + str(patient_var.firstName) + " " + str( patient_var.lastName) + ", is now in the recovery room." now = datetime.datetime.now() date = now.date() time = now.time() news = News(body=body, date=date, time=time, idPatient_id=patient_var.pk) news.save() bed = Beds.objects.get(pk=bedNumber) bed.bedStatus = "Occupied" bed.save() return HttpResponse()
def test_error(monkeypatch, document): def mockreturn(self, request): return MockResponse(b'{"_type": "error", "message": ["failed"]}') monkeypatch.setattr(requests.Session, 'send', mockreturn) client = coreapi.Client() with pytest.raises(coreapi.exceptions.ErrorMessage): client.action(document, ['next'])