How do I add a user to groups by using the Bugzilla API? - bugzilla

Here is my code:
data = {
'groups': [{'add':{'S8','ALL'}}]
}
r = requests.put(bugzilla_host + '/rest.cgi/user/user_name?token=' + token, data=data)
And I get the following error:
> {"error":true,"message":"Can't use string (\"add\") as a HASH ref
> while \"strict refs\" in use at Bugzilla/User.pm line
> 419.\n","code":100500,"documentation":"https://bugzilla.readthedocs.org/en/5.0/api/"}

I found i should change data=data to json=data

Related

Player command failed: Premium required. However i have premium

Im am using a family account (premium) and this code returns a'Premium required' error. My code is as follows:
device_id = '0d1841b0976bae2a3a310dd74c0f3df354899bc8'
def playSpotify():
client_credentials_manager = SpotifyClientCredentials(client_id='<REDACTED>', client_secret='<REDACTED>')
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
playlists = sp.user_playlists('gh8gflxedxmp4tv2he2gp92ev')
#while playlists:
#for i, playlist in enumerate(playlists['items']):
#print("%4d %s %s" % (i + 1 + playlists['offset'], playlist['uri'], playlist['name']))
#if playlists['next']:
#playlists = sp.next(playlists)
#else:
#playlists = None
#sp.shuffle(true, device_id=device_id)
#sp.repeat(true, device_id=device_id)
sp.start_playback(device_id=device_id, context_uri='spotify:playlist:4ndG2qFEFt1YYcHYt3krjv')
When using SpotifyClientCredentials the token that is generated doesn't belong to any user but to an app, hence the error message.
What you need to do is use SpotifyOAuth instead. So to initialize spotipy, just do:
sp = spotipy.Spotify(auth_manager=spotipy.SpotifyOAuth())
This will open a browser tab and require you to sign in to your account.

Batch Request for get in gmail API

I have a list of around 2500 mail ids and I'm stuck to only use requests library, so so far i do it this way to get mail headers
mail_ids = ['']
for mail_id in mails_ids:
res = requests.get(
'https://www.googleapis.com/gmail/v1/users/me/messages/{}?
format=metadata'.format(mail_id), headers=headers).json()
mail_headers = res['payload']['headers']
...
But its very inefficient and i would rather like to POST list of Ids instead, but on their documentation https://developers.google.com/gmail/api/v1/reference/users/messages/get, i don't see BatchGet, any workaround? I'm using Flask framework Thanks a lot
This is a bit late, but in case it helps anyone, here's the code I used to do a batch get of emails:
First I get a list of relevant emails. Change the request according to your needs, I'm getting only sent emails for a certain time period:
query = "https://www.googleapis.com/gmail/v1/users/me/messages?labelIds=SENT&q=after:2020-07-25 before:2020-07-31"
response = requests.get(query, headers=header)
events = json.loads(response.content)
email_tokens = events['messages']
while 'nextPageToken' in events:
response = requests.get(query+f"&pageToken={events['nextPageToken']}",
headers=header)
events = json.loads(response.content)
email_tokens += events['messages']
Then I'm batching a get request to get 100 emails at a time, and parsing only the json part of the email and putting it into a list called emails. Note that there's some repeated code here, so you may want to refactor it into a method. You'll have to set your access token here:
emails = []
access_token = '1234'
header = {'Authorization': 'Bearer ' + access_token}
batch_header = header.copy()
batch_header['Content-Type'] = 'multipart/mixed; boundary="email_id"'
data = ''
ctr = 0
for token_dict in email_tokens:
data += f'--email_id\nContent-Type: application/http\n\nGET /gmail/v1/users/me/messages/{token_dict["id"]}?format=full\n\n'
if ctr == 99:
data += '--email_id--'
print(data)
r = requests.post(f"https://www.googleapis.com/batch/gmail/v1",
headers=batch_header, data=data)
bodies = r.content.decode().split('\r\n')
for body in bodies:
if body.startswith('{'):
parsed_body = json.loads(body)
emails.append(parsed_body)
ctr = 0
data = ''
continue
ctr+=1
data += '--email_id--'
r = requests.post(f"https://www.googleapis.com/batch/gmail/v1",
headers=batch_header, data=data)
bodies = r.content.decode().split('\r\n')
for body in bodies:
if body.startswith('{'):
parsed_body = json.loads(body)
emails.append(parsed_body)
[Optional] Finally, I'm decoding the text in the email and storing only the last sent email instead of the whole thread. The regex used here splits on strings that I found were usually at the end of emails. For instance, On Tue, Jun 23, 2020, x#gmail.com said...:
import re
import base64
gmail_split_regex = r'On [a-zA-z]{3}, ([a-zA-z]{3}|\d{2}) ([a-zA-z]{3}|\d{2}),? \d{4}'
for email in emails:
if 'parts' not in email['payload']:
continue
for part in email['payload']['parts']:
if part['mimeType'] == 'text/plain':
if 'uniqueBody' not in email:
plainText = str(base64.urlsafe_b64decode(bytes(str(part['body']['data']), encoding='utf-8')))
email['uniqueBody'] = {'content': re.split(gmail_split_regex, plainText)[0]}
elif 'parts' in part:
for sub_part in part['parts']:
if sub_part['mimeType'] == 'text/plain':
if 'uniqueBody' not in email:
plainText = str(base64.urlsafe_b64decode(bytes(str(sub_part['body']['data']), encoding='utf-8')))
email['uniqueBody'] = {'content': re.split(gmail_split_regex, plainText)[0]}

Alway get an error "No attribute named 'name' is defined" if try to process multiple lines from csv data feed

In my test script I try to process 100 lines data from csv data feed via following statement:
private val scn = scenario("test_scn").feed(insertFeeder, 100).exec(httpReq)
But I always get an error:
[ERROR] HttpRequestAction - 'httpRequest-1' failed to execute: No attribute named 'name' is defined
Could you please help me to find out the root cause? thank you.
Here is the script:
private val insertFeeder = csv("test_data.csv").queue
private val csvHeader = GeneralUtil.readFirstLine(""test_data.csv"")
private val httpConf = http .baseURL("http://serviceURL") .disableFollowRedirect .disableWarmUp .shareConnections
private var httpReq = http("insert_request") .post("/insert")
for (i <- 0 to 99) {
val paramsInArray = csvHeader.split(",")
for (param <- paramsInArray) {
if (param.equalsIgnoreCase("name")) {
httpReq = httpReq.formParam(("name" + "[" + i +"]").el[String] , "${name}")
}
if (param.equalsIgnoreCase("url")) {
httpReq = httpReq.formParam(("url" + "[" + i +"]").el[String] , "${url}")
}
if (!param.equalsIgnoreCase("name") && !param.equalsIgnoreCase("url")) {
val firstArg = param + "[" + i + "]"
val secondArg = "${" + param + "}"
httpReq = httpReq.formParam(firstArg, secondArg)
}
}
}
private val scn = scenario("test_scn") .feed(insertFeeder, 100) .exec(httpReq)
setUp( scn.inject( constantUsersPerSec(1) during (1200 seconds) ).protocols(httpConf) ).assertions(global.failedRequests.count.lte(5))
And the data in test_data.csv is:
name,url,price,size,gender
image_1,http://image_1_url,100,xl,male
image_2,http://image_2_url,90,m,female
image_3,http://image_3_url,10,s,female
...
image_2000,http://image_2000_url,200,xl,male
By the way, if I process only 1 line, it works well.
Read the document again, and fixed the issue. If feed multiple records all at once, the attribute names will be suffixed from 1.
https://gatling.io/docs/current/session/feeder/#csv-feeders

Dapper Contrib Insert MySQL Syntax Error

Hey I am getting syntax error in MySQL using Dapper.Contrib
MySQL server version for the right syntax to use near '[cause_code],[cause_name]) values ('000-DDH', 'No Money')' at line 1
the correct syntax for Insert in mysql is
"Insert Into `tbl_cause` (`cause_code`, `cause_name`) VALUES('blah', 'blah')";
my code:
var entity = new Cause { cause_code = "000-DDH", cause_name = "No Money" };
using (IDbConnection cn = ConStr.Conn())
{
long ins = cn.Insert(entity);
if (ins > 0)
{
MessageBox.Show("Cause Code: " + entity.cause_code + " Successfully Added!");
GDRD();
}
else {
MessageBox.Show("Cause Code: " + entity.cause_code + " While trying to Add an Error Occurred!");
}
}
how to solve this? thanks in Advance
It's you again :)
Does the class Cause have a Table("tbl_cause") directive?
Read the dapper contrib extensions documentation here

Save not working using mssql

I'm trying the following code but not working in mssql and not producing any error message in CakePHP, using version 2.6:
$product_id = $this->request->data['products']['product_id'];
$this->request->data['ProductTbl']['id'] = strtotime(date('Y-m-d H:i:s'));
$this->request->data['ProductTbl']['retailerId'] = $this->request->data['products']['retailer_id'];
$this->request->data['ProductTbl']['productCode'] = $product_id;
$this->request->data['ProductTbl']['productType'] = $this->request->data['products']['product_type'];
//$this->request->data['ProductTbl']['mmGroupId'] = $this->request->data['products']['merchandise_id'];
$this->request->data['ProductTbl']['name'] = $this->request->data['products']['product_name'];
$this->request->data['ProductTbl']['description'] = $this->request->data['products']['product_desp'];
$this->request->data['ProductTbl']['isLayawayable'] = $this->request->data['products']['product_layway'];
$this->request->data['ProductTbl']['isTaxExemptible'] = $this->request->data['products']['product_tax'];
$this->request->data['ProductTbl']['productURL'] = $this->request->data['products']['product_url'];
$this->request->data['ProductTbl']['status'] = 2;
$this->request->data['ProductTbl']['lastModified'] = date('Y-m-d H:i:s');
$this->request->data['ProductTbl']['isDeleted'] = 0;
if(!empty($this->request->data['pjosn'])){
$pjson_arr = $this->request->data['pjosn'];
$this->request->data['ProductTbl']['propertiesJson'] = json_encode($pjson_arr);
}
$this->ProductTbl->save($this->request->data['ProductTbl'],false);
$last_id = $this->ProductTbl->getLastInsertID();
Thanks.
why are u using second argument 'false' in save function ???
i thinks possible issue should be second argument. I am using cakePHP 2.7.5 and according to me your save query will be ::
$res = $this->ProductTbl->save($this->request->data);
if($res){
// do whatever you wants
}
Or the second issue may be in following code :
if(!empty($this->request->data['pjosn'])){
$pjson_arr = $this->request->data['pjosn'];
$this->request->data['ProductTbl'['propertiesJson']=json_encode($pjson_arr);
}
in json_encode your data will be in joson format ( like : {"key1":value1,"key2":value2,"key3":value3,"key4":value4,"key5":value5} ) which will not be accepted by cakePHP insert query.

Resources