How to query the sys_user table using REST? - python

I am using v2.0.1 of servicenow from PyPi to interact with ServiceNow. I need to be able to look up a user in the sys_user table so I can find the sys_id assigned to them. If anyone has some sample code they can share it would be appreciated.
I have tried using the following with no success:
from servicenow import Connection
from servicenow import ServiceNow
conn = conn = Connection.Auth(username='abc', password='xyz', instance='demo')
user = ServiceNow.Base(conn)
user.__table__ = 'sys_user.do'
rec = user.fetch_all({'user_name': 'abc123'})
This fails with
AttributeError: 'Base' object has no attribute 'fetch_all'

I am not familiar with PyPi, but I will tell you you can make standard REST calls to the /api/now/table/sys_user?sysparm_query=user_nameSTARTSWITH
Also, make sure to review the notes regarding JSON, JSONv2, vs SOAP and use the right connection auth string

Related

Error trying to replace Vimeo file using Python library

I am using the Vimeo Python Library example. After setting up a simple example, I am getting an error below. Do I need to create a new token?
Error
window.vimeo.exception_data = {"title":"Unauthorized","message":"Oops! This action could not be completed because your form session expired. Please make sure your cookies are enabled, then return to the previous page and try again.","notification":null,"search":true,"videos":null,"ad_config":{"house_ads_enabled":false},"page_type":"exception","module_type":"standard_multi"};
CODE
import vimeo
import os
VIMEO_TOKEN=os.environ.get("TOKEN")
VIMEO_KEY=os.environ.get("KEY")
VIMEO_SECRET=os.environ.get("SECRET")
client = vimeo.VimeoClient(
token=VIMEO_TOKEN,
key=VIMEO_KEY,
secret=VIMEO_SECRET
)
video_uri = client.replace(
'https://vimeo.com/745944239',
'test_replace_test.mov'
)
You need to use the video's API URI, something to the effect of
client.replace('/videos/745944239', 'file_to_replace.mov')

InvalidRequestError: Must provide an 'engine' parameter while invoking openAI API for text generation

I was trying this code given in OpenAI.
Link:- API for text generation
Code
import openai
prompt = """We’re releasing an API for accessing new AI models developed by OpenAI. Unlike most AI systems which are designed for one use-case, the API today provides a general-purpose “text in, text out” interface, allowing users to try it on virtually any English language task. You can now request access in order to integrate the API into your product, develop an entirely new application, or help us explore the strengths and limits of this technology."""
response = openai.Completion.create(model="davinci", prompt=prompt, stop="\n", temperature=0.9, max_tokens=100)
print(response)
I'm getting an error
Error
"Must provide an 'engine' parameter to create a %s" % cls, "engine".
openai.error.InvalidRequestError: Must provide an 'engine' parameter to create a <class 'openai.api_resources.completion.Completion'>
I'm using python 3.7.6
It seems you have confused the engine parameter with the model parameter. Please have a look at this documentation for the correct way to call: https://beta.openai.com/docs/developer-quickstart/python-bindings
Please change model = "davinci" to engine = "davinci"
and you should be good to go.
If you get the error code:
...
InvalidRequestError: Engine not found
One possible problem could be your account setting does not offer you access to the engine. For example, embedding engines are only available for "private beta." You may need to request access to it for your account.
The following code may get you the available engines to your account:
import openai
openai.api_key = your_openai_api_key
data = openai.Engine.list() for eng in data['data']:
print(eng['id'])
Here is complete prompt in a function, for a successful query:
import os
import openai
openai.api_key = os.environ["openai_key"]
start = "Your are a AI Search Engine, answer the following query with a witty answer and include validated facts only."
def generate(prompt):
start_sequence = "{}.{}".format(start,prompt)
completions = openai.Completion.create(
model="text-davinci-003",
prompt=start_sequence,
temperature=0.1,
max_tokens=256,
top_p=1,
frequency_penalty=0.51,
presence_penalty=0.5,
#stream = False,
#echo = True
)
message = completions.choices[0].text
print(message)
return message

Configuring sqlalchemy engine with user containing ":"

I am trying to configure an engine in sqlalchemy to connect with temporary credentials from an AWS IAM role using get_cluster_credentials api.
When I do so this is the user I get 'IAM:user_rw'. Problem comes when I configure the engine string as
engine_string = "postgresql+pygresql://{user}:{password}#{endpoint}:{port}/{dbname}".format(
user=cluster_creds['DbUser'],
password=cluster_creds['DbPassword'],
endpoint='big endpointstring',
port=8192,
dbname='small dbname')
I create the engine without errors but when running any query I get: FATAL: password authentication failed for user "IAM"
Tested the user and pass in DataGrip it works so it seems evident sqlalchemy is getting the user just as "IAM" instead of 'IAM:user_rw'.
Do you know how can I force sqlalchemy to get the correct user?
I managed to solve the issue using urllib parse_quote in a similar fashion to what Gord is pointing. Final code
from urllib.parse import quote_plus
engine_string = "postgresql+pygresql://%s:%s#%s:%d/%s" % (
quote_plus(user),
quote_plus(passw),
endpoint,
port,
dbname,
)

Is it possible to get changesets created between a specific date using TFSAPI?

I'm writing a program to find changesets based on created date using Microsoft TFS Python Library (TFS API Python client).
I read through the documentation and found that the get_changesets() method can be used for this. But there are no arguments that can help filter out the changesets based on date.
On further reading, I found that get_tfs_resource() could be used, but being new to using APIs, I cannot figure out how to set payload for the method call, that would help me to filter out the changesets using date.
Can someone help me out with the correct methods to be used, or the payload that can be sent as specified?
You can use the TFS Rest API get get changeset and do this
https://{instance}/{collection}/{project}/_apis/tfvc/changesets?searchCriteria.fromDate=2020-03-11&searchCriteria.toDate=2020-03-12&api-version=4.1
You may check the code below:
from azure.devops.connection import Connection
from msrest.authentication import BasicAuthentication
import pprint
# Fill in with your personal access token and org URL
personal_access_token = 'YOURPAT'
organization_url = 'https://dev.azure.com/YOURORG'
# Create a connection to the org
credentials = BasicAuthentication('', personal_access_token)
connection = Connection(base_url=organization_url, creds=credentials)
tfsv_client = connection.clients.get_tfvc_client()
project_name="myprojname"
search_criteria = type('',(object,),{"item_path":'$/myprojname/Trunk/Main',"fromDate":'01-01-2019', "toDate":'11-13-2019-2:00PM'})
changeset_info = tfvcclient.get_changesets(project=project_name,search_criteria=search_criteria)
Reference from:
https://github.com/microsoft/azure-devops-python-api
https://github.com/microsoft/azure-devops-python-api/blob/dev/azure-devops/azure/devops/v5_1/tfvc/tfvc_client.py
How to access azure Dev Ops data such as Changeset between dates using python?

How to get all work items(Epics, Features, Issue, Task, Test Case, User Story, etc) for an Azure Devops project?

I am trying to fetch all the work items(Epics, Features, Issue, Task, Test Case, User Story, etc) and then classify them for a given project using Microsoft's azure devops python api(aka vsts) library.
In the work_item_tracking I am unable to find any function to get all work item or fetch all work item on the basis of it's type.
Is there already a function for getting all work items that I am unable to find or should I write a WIQL query to fetch the required data?
I'm following this documentation to implement this.
With Wiql we can do queries to the new version Azure Devops or TFS. In order to test it out I'm using Postman to consume the services before implement it.
The first step is use de following url:
https://dev.azure.com/{organization}/{projectId}/_apis/wit/wiql?api-version=5.0
You must do a Post request to the URL using the following json body to make the the query. Check below the json payload.
{
"query": "Select [System.Id], [System.Title], [System.State], [System.WorkItemType] From WorkItems"
}
Finally if the request is good you will receive a 200 HTTP response with the content of the query, if in the other hand you receive an error the request will rise the erro description and the HTTP code.
Check my response in the following link and check the data structure that is returning the request:
Result of my query
Is there already a function for getting all work items that I am unable to find or should I write a WIQL query to fetch the required data?
You are right. We could use write a WIQL query to fetch the System Ids, then we could according system.Ids to query the workitems. The following is the demo code to fetch all of the workitems with python code.
from vsts.vss_connection import VssConnection
from msrest.authentication import BasicAuthentication
import json
from vsts.work_item_tracking.v4_1.models.wiql import Wiql
def emit(msg, *args):
print(msg % args)
def print_work_item(work_item):
emit(
"{0} {1}: {2}".format(
work_item.fields["System.WorkItemType"],
work_item.id,
work_item.fields["System.Title"],
)
)
personal_access_token = 'YourPATToken'
organization_url = 'https://dev.azure.com/YourorgName'
# Create a connection to the org
credentials = BasicAuthentication('', personal_access_token)
connection = VssConnection(base_url=organization_url, creds=credentials)
wiql = Wiql(
query="""select [System.Id] From WorkItems """
)
wit_client = connection.get_client('vsts.work_item_tracking.v4_1.work_item_tracking_client.WorkItemTrackingClient')
wiql_results = wit_client.query_by_wiql(wiql).work_items
if wiql_results:
# WIQL query gives a WorkItemReference with ID only
# => we get the corresponding WorkItem from id
work_items = (
wit_client.get_work_item(int(res.id)) for res in wiql_results
)
for work_item in work_items:
print_work_item(work_item)
For more demo code, you could refer to this link.
First of all, I am not using the python library, but I can tell you which APIs you have to use.
There is an API to retrieve all the work items. This is just an JSON object with all the work item types and properties. Be aware that this is limited to only 200 workitems each request. If you want more workitems, you have to write a WIQL query.
GET https://dev.azure.com/{organization}/{project}/_apis/wit/workitems?ids={ids}&api-version=5.0-preview.3
Personally I would like to advise you to use WIQL Queries to retrieve data from Azure DevOps. It is very flexible and it could be used in any situation.
Here you can find more information about WIQL queries
Here you can find the detailed information about the Azure DevOps Rest API for WIQL Queries

Categories