In the following code snippet at the bottom, how do I explicitly set {0} and {1} to variables like:
0=host-123
1=128.24.22.21
such that I can keep the URL with the variables and call those variables elsewhere without actually explicitly setting them as host-123 and 128.24.22.21 elsewhere ?
def getipam(host, neighboraddr, token):
"""Fetch IPAM data for host and neighbor ip"""
url = 'https://ipam.app.secretcdn.net/v1/hosts/{0}/bgp/neighbors/neighbor/{1}'.format(host, neighboraddr)
response = requests.get(url, headers={'x-api-rw': token})
results = response.json()
return results
0/1/integers are immutable in python. You cannot change the value. You might want to call it by some other name like x or y something and then you can assign it
Related
I am using a script i've downloaded from the web to access our service API.
I am trying to run the function, but keep getting errors no matter what I am trying to do.
from PyBambooHR import PyBambooHR
bamboo = PyBambooHR(subdomain='domain', api_key='apicode')
changes = bamboo.get_employee_changes()
When I run this, I get the following error:
ValueError: Error: since argument must be a datetime.datetime instance
Now, no matter what I set as arguments, I still getting errors. I've also tried the syntax from: https://www.bamboohr.com/api/documentation/changes.php
The function is:
def get_employee_changes(self, since=None):
"""
Returns a list of dictionaries, each with id, action, and lastChanged keys, representing
the employee records that have changed since the datetime object passed in the since= argument.
#return List of dictionaries, each with id, action, and lastChanged keys.
"""
if not isinstance(since, datetime.datetime):
raise ValueError("Error: since argument must be a datetime.datetime instance")
url = self.base_url + 'employees/changed/'
params = {'since': since.strftime('%Y-%m-%dT%H:%M:%SZ')}
r = requests.get(url, params=params, headers=self.headers, auth=(self.api_key, ''))
r.raise_for_status()
return utils.transform_change_list(r.content)
Thanks for your help
As you see in that function is a parameter since of type datetime.datetime expected.
import datetime
changes = bamboo.get_employee_changes(since=datetime.datetime.now() - datetime.timedelta(days=365))
Should give you the changes since last year
Pass a variable of type datetime.datetime while calling the function bamboo.get_employee_changes()
I have bunch of test methods that i need to run and then after each test i want to update my results somewhere else.
This is what i have:
#pytest.mark.testcasename('1234')
#pytest.mark.parametrize('lang',
["EN", "FR"])
def test_text(self, request, base_url, lang):
testrail_conn = TestrailHelper()
test_case_id = request.node.get_marker("testcasename").args[0]
base_url = base_url.replace("testEN", "testFR") if lang == "FR" else base_url
self.navigate(base_url)
self.wait_for_page_loaded()
results = self.check_text(lang)
try:
assert results
testrail_conn.update_test_status(test_case_id, test_result=1)
except AssertionError:
testrail_conn.update_test_status(test_case_id, test_result=5)
My problem is that i want the update_test_status to be in a teardown fixture where i can pass my test_result to it. This way i dont need to write same code for each test method..
Any ideas?
Thanks
You could store something on the request object, e.g. on request.node - see the docs. Alternatively, you could use your fixture (as an argument) from the test, and store something there - or make the fixture return/yield some kind of data structure to store things in.
I'm trying to create several URLs on my serv thanks to a loop . The issue is that each function I create in a app.route can't have the same name than the others . And I don't know how to create different function names ...
Here is the code :
json_tweets = []
for line in open('C:\Users\Benjamin\Desktop\DashboardProject\last_rated_set.json',"r"):
json_tweets.append(json.loads(line,"ISO-8859-1"))
cashtag_tab = []
for tweet in json_tweets:
if not(tweet['cashtag'] in cashtag_tab) :
cashtag_tab.append(tweet['cashtag'])
for i in range(0,(len(cashtag_tab)-1)) :
var=cashtag_tab[i]
#app.route("/"+var)
def company(var) :
finance=Share(var)
datas = finance.get_historical('2014-01-01', '2014-12-31')
datas = json.dumps(datas, default=json_util.default)
return datas
I'm getting the error AssertionError : View function mapping is overwritting an existing endpoint function : company
This fails because Flask derives the endpoint name from the function by default, but it would anyway fail later because the function company requires an argument var and the route is not parameterised. The simplest option would be just checking the value inside the handler:
#api.route('/<var>')
def company(var):
if var not in cashtag_tab:
abort(404)
If you want all the routes to be in the routing map for any reason, I once needed a similar thing and came up with something like this:
def url_family(source, methods=('GET',)):
def decorator(f):
for entry in source:
# create a handler that delegates to your function
def view_func(entry=entry, **kwargs):
return f(entry, **kwargs)
endpoint = '{0}_{1}'.format(f.__name__, entry)
url = '/{0}'.format(entry)
api.add_url_rule(url,
methods=methods,
endpoint=endpoint,
view_func=view_func)
return decorator
Then you register the handlers as:
#url_family(cashtag_tab)
def company(var):
...
Assuming that you are using flask now, you should consider Custom URL Converter. Check links below
http://flask.pocoo.org/docs/0.10/api/#flask.Flask.url_map - url_map UrlConverter API
https://exploreflask.com/views.html#url-converters - example url converter
https://stackoverflow.com/a/5872904/3451543 - RegexConverter by Philip Southam
Anyway, specifying more details on your question is always helpful to get accurate answer :)
I tried to create multiple routes in one go by using the variables from the database and a for loop.
I tried this
temp = "example"
#app.route("/speaker/<temp>")
def getSpeakerAtr(temp):
return '''%s''' % temp
It works very well. BUT:
for x in models.Speaker.objects:
temp = str(x.name)
#app.route("/speaker/<temp>")
def getSpeakerAtr(temp):
return '''%s''' % temp
Doesn't work. The error message:
File "/Users/yang/Documents/CCPC-Website/venv/lib/python2.7/site-packages/flask/app.py", line 1013, in decorator
02:03:04 web.1 | self.add_url_rule(rule, endpoint, f, **options)
**The reason I want to use multiple routes is that I need to get the full data of an object by querying from the route. For example:
if we type this url:
//.../speaker/sam
we can get the object who has the 'name' value as 'sam'. Then I can use all of the values in this object like bio or something.**
You don't need multiple routes. Just one route that validates its value, eg:
#app.route('/speaker/<temp>')
def getSpeakerAtr(temp):
if not any(temp == str(x.name) for x in models.Speaker.objects):
# do something appropriate (404 or something?)
# carry on doing something else
Or as to your real intent:
#app.route('/speaker/<name>')
def getSpeakerAtr(name):
speaker = # do something with models.Speaker.objects to lookup `name`
if not speaker: # or whatever check is suitable to determine name didn't exist
# raise a 404, or whatever's suitable
# we have a speaker object, so use as appropriate
I am using SUDS (Like SOAP) to test WSDL files. The methods contain types that are linked to further functions. I am not sure how to access the variables stored in the types that are displayed. Some sample code is below:
from suds.client import Client
client=Client('http://eample.wsdl')
print client
response is:
Ports (1):
(PTZ)
Methods (4):
AbsoluteMove(ns4:ReferenceToken ProfileToken, ns4:PTZVector Destination, ns4:PTZSpeed Speed, )
Types (303):
ns4:PTZSpeed
I am able to get access to these functions. I cannot find any documentation on how to test functions in SUDS. I want to test to see if functions work and checking their return values. Does anyone know how to do this?
I used the command below to display all child functions.
client.factory.create('AbsoluteMove.PTZSpeed.Speed.PanTilt')
I main problem is basically passing values into the functions and getting return values.
I have tried to pass the arguments but the parameters have attributes stored in the attributes. Below shows the layout for the structure of the parameters I'm trying to access.
(AbsoluteMove){
ProfileToken = None
Destination =
(PTZVector){
PanTilt =
(Vector2D){
_x = ""
_y = ""
_space = ""
}
Zoom =
(Vector1D){
_x = ""
_space = ""
}
}
Speed =
(PTZSpeed){
PanTilt =
(Vector2D){
_x = ""
_y = ""
_space = ""
}
Zoom =
(Vector1D){
_x = ""
_space = ""
The parameters are more complex than just entering simple values.
Try to invoke the method on the service:
from suds.client import Client
client=Client('http://eample.wsdl')
res = client.service.AbsoluteMove(profile_token, destination, speed)
print res
You'll need to determine what values to put in for those arguments to the AbsoluteMove method.
Client.factory.create is for the instantiation of object types that are internal to the service you are utilizing. If you're just doing a method call (which it seems you are), invoke it directly.