How to attach file via "Bugzilla XMLRPC access module" - python

I am working on bugzilla xml-rpc by using "Bugzilla XMLRPC access module" developed in python.
How I can attach/download bugzilla file by using this module ?
According to guideline of API get_attachments_by_bug($bug_id) retrieves and returns the attachments.
But this function didn't worked for me, I got following error message.
<type 'exceptions.AttributeError'>: 'Bugzilla4' object has no attribute 'get_attachments_by_bug'
Any help would be appreciated.

FYI:
I am in contact with supplier of python-bugzilla tool and here I got response from them.
"Not all bugzilla XMLRPC APIs are wrapped by python-bugzilla, that's one of them.
The 'bugzilla' command line tool that python-bugzilla ships has commands for
attaching files and downloading attachments, take a look at the code there for
guidance."
I've figured out the way how to download/upload attachment by using "Bugzilla XMLRPC access module"
you need to pass the id of attached file as parameter to the following function
Download:
downloaded_file = bz.download_attachment(attachment_id)
file_name = str(downloaded_file.name)
Upload:
kwards = {
'contenttype':'application/octet-stream',
# 'filename': file_path #there could be more parameters if needed
}
#attachfile method will return the id of attached file
bz.attachfile(bug_id, file_path, file_name, **kwards)
However attached file got corrupted due to some xmp-rpc API's internal methods described here, here and here, that's another issue :)

Related

Google Drive API v3 changing metadata of file

i got a problem with changing metada of file on google drive. I got script for downloading files from drive and after download i want to mark file with star (starred = True).
I found solution for v2 API, but its not working for v3, where i reciving error "The resource body includes fields which are not directly writable".
I read a documentation for v3 but didnt find solution how to change metadata.
file = service.files().get(fileId=file_id).execute()
file['starred'] = True
service.files().update(fileId=file_id, body=file).execute()
Thanks for any help.
The issue you are having is you are doing a file.get first.
file = service.files().get(fileId=file_id).execute()
This populates the full file resource object. And since the update method uses patch methodology its trying to update every property that you sent and some of them are not writeable. you should only send the fields you want to update.
Try this.
file_metadata = {'starred': true}
updated_file = service.files().update(
fileId='id_file_in_google_drive',
body=file_metadata ).execute()

Bingads SDK Python Suds sending wrong envelope

Using BingAds SDK for Python I am not able to perform any operation to update because of a bug that I cannot resolve.
The SDK uses Suds for the handling of SOAP operation.
Here is the wsdl:
https://campaign.api.bingads.microsoft.com/Api/Advertiser/CampaignManagement/v13/CampaignManagementService.svc?singleWsdl
# This function internally configures the authorization for BingAdsAPI
campaign_service = bc.get_bing_ads_client(account=account, service='CampaignManagementService')
update_ad_groups_request = campaign_service.factory.create('UpdateAdGroupsRequest')
update_ad_groups_request.CampaignId = campaign_id
ad_group = campaign_service.factory.create('AdGroup')
ad_group.Id = ad_group_id
bid = campaign_service.factory.create('Bid')
bid.Amount = new_bid
ad_group.CpcBid = bid
update_ad_groups_request.AdGroups = campaign_service.factory.create('ArrayOfAdGroup')
update_ad_groups_request.AdGroups.AdGroup.append(ad_group)
campaign_service.UpdateAdGroups(update_ad_groups_request)
When I send it it fails saying:
suds.WebFault: Server raised fault: 'The formatter threw an exception
while trying to deserialize the message: There was an error while
trying to deserialize parameter
https://bingads.microsoft.com/CampaignManagement/v13:CampaignId. The
InnerException message was 'There was an error deserializing the
object of type System.Int64. The value '' cannot be parsed as the type
'Int64'.'. Please see InnerException for more details.'
When I open the soap Envelope:
....</SOAP-ENV:Header><ns1:Body><ns0:UpdateAdGroupsRequest><ns0:CampaignId>
<ns0:CampaignId>377072652</ns0:CampaignId><ns0:AdGroups><ns0:AdGroup><ns0:CpcBid>
<ns0:Amount>0.91</ns0:Amount></ns0:CpcBid><ns0:Id>1256742239729725</ns0:Id>
<ns0:Network/><ns0:PrivacyStatus/><ns0:Status/></ns0:AdGroup></ns0:AdGroups>
</ns0:CampaignId></ns0:UpdateAdGroupsRequest></ns1:Body></SOAP-ENV:Envelope>
Note how the Campaign ID is twice and also it wraps the whole envelope. I tried also directly with Suds and I have the same issue, other functions also have the same issue.
Because moving to parsing the envelopes by myself, I was wondering if someone has had this issue and what could be the reason.
You should not need to explicitly create a 'Request' object i.e., via the SUDS service client you can pass the request parameters directly via the UpdateAdGroups operation. To confirm I started with expanded_text_ads.py and inserted the following snippet immediately after the AddAdGroups example.
ad_groups=campaign_service.factory.create('ArrayOfAdGroup')
ad_group=set_elements_to_none(campaign_service.factory.create('AdGroup'))
ad_group.Id=ad_group_ids['long'][0]
cpc_bid=campaign_service.factory.create('Bid')
cpc_bid.Amount=0.11
ad_group.CpcBid=cpc_bid
ad_groups.AdGroup.append(ad_group)
output_status_message("-----\nUpdateAdGroups:")
add_ad_groups_response=campaign_service.UpdateAdGroups(
CampaignId=campaign_ids['long'][0],
AdGroups=ad_groups
)
output_status_message("PartialErrors:")
output_array_of_batcherror(add_ad_groups_response.PartialErrors)
I hope this helps! Please let me know if you have any follow up questions.

BadParametersError: Invalid signature when using OVH Python wrapper

I'm using OVH API along with python wrapper:
https://pypi.python.org/pypi/ovh
When trying to execute this code:
import ovh
client = ovh.Client()
# Print nice welcome message
print "Welcome", client.get('/me')['firstname']
I get this error:
Traceback (most recent call last):
File "index.py", line 6, in <module>
print "Welcome", client.get('/me')['firstname']
File "/home/rubinhozzz/.local/lib/python2.7/site-packages/ovh/client.py", line 290, in get
return self.call('GET', _target, None, _need_auth)
File "/home/rubinhozzz/.local/lib/python2.7/site-packages/ovh/client.py", line 419, in call
raise BadParametersError(json_result.get('message'))
ovh.exceptions.BadParametersError: Invalid signature
My info is saved in the ovh.conf as the documentation suggests.
[default]
; general configuration: default endpoint
endpoint=ovh-eu
[ovh-eu]
application_key=XXXlVy5SE7dY7Gc5
application_secret=XXXdTEBKHweS5F0P0tb0lfOa8GoQPy4l
consumer_key=pscg79fXXX8ESMIXXX7dR9ckpDR7Pful
It looks that I can connect but when trying to use the services like for instance "/me", the error raises!
It is difficult to reproduce the issue because it requires an application key and it seems that it is only granted to existing customers of OVH. I couldn't even see a link to an account registration page on their site.
By looking at the code of the call() method in /ovh/client.py, it seems that their server doesn't recognise the format or the content off the signature sent by your script. According to the inline documentation the signature is generated from these parameters:
application_secret
consumer_key
METHOD
full request url
body
server current time (takes time delta into account)
Since your call is identical to the example code provided on the OVH Python package web page, the last four parameters should be valid. In that case it looks like either the application secret or the customer key (or both) in your config file are not correct.
See also the documentation on OVH site under the 'Signing requests' heading. They explain how the signature is made and what it should look like.
Perhaps try to re-create a new application API to obtain new key and secret and make sure you copy them without any additional character.

authentification for Google Storage using Python

I want to build an app which has easy interactions with google storage, i.e., list files in bucket, download a file, and upload a file.
Following this tutorial, I decided to use a service account (not a user one) for authentification and followed the procedure. I created a public/private key on my console and download the key on my machine. Then I created the .boto file which points to this private key, and finally launched this program and it worked:
import boto
import gcs_oauth2_boto_plugin
uri = boto.storage_uri('txxxxxxxxxxxxxx9.appspot.com', 'gs')
for obj in uri.get_bucket():
print '%s://%s/%s' % (uri.scheme, uri.bucket_name, obj.name)
As you can see, the package gcs_oauth2_boto_plugin is not used in the code, so I decided to get rid of it. But magically, when I comment the import gcs_oauth2_boto_plugin line and run the program again, I get this error:
C:\Users\...\Anaconda3\envs\snakes\python.exe C:/Users/.../Dropbox/Prog/s3_manifest_builder/test.py
Traceback (most recent call last):
File "C:/Users/.../Dropbox/Prog/s3_manifest_builder/test.py", line 10, in <module>
for obj in uri.get_bucket():
File "C:\Users\...\Anaconda3\envs\snakes\lib\site-packages\boto\storage_uri.py", line 181, in get_bucket
conn = self.connect()
File "C:\Users\...\Anaconda3\envs\snakes\lib\site-packages\boto\storage_uri.py", line 140, in connect
**connection_args)
File "C:\Users\...\Anaconda3\envs\snakes\lib\site-packages\boto\gs\connection.py", line 47, in __init__
suppress_consec_slashes=suppress_consec_slashes)
File "C:\Users\...\Anaconda3\envs\snakes\lib\site-packages\boto\s3\connection.py", line 190, in __init__
validate_certs=validate_certs, profile_name=profile_name)
File "C:\Users\...\Anaconda3\envs\snakes\lib\site-packages\boto\connection.py", line 569, in __init__
host, config, self.provider, self._required_auth_capability())
File "C:\Users\...\Anaconda3\envs\snakes\lib\site-packages\boto\auth.py", line 987, in get_auth_handler
'Check your credentials' % (len(names), str(names)))
boto.exception.NoAuthHandlerFound: No handler was ready to authenticate. 1 handlers were checked. ['HmacAuthV1Handler'] Check your credentials
So my questions are:
1- how can you explain that deleting an import which IS NOT USED in the code makes it fail?
2- more generally, to be sure to understand the authentification process, if I want to run my app on a machine, I must be sure to have the .boto file (which points to my service account private key) generated previously? Or is there a cleaner/easier way to give access to my application to Google Storage for in/out interactions?
For instance, I only have to provide public and private key as strings to my program when I want to connect to a S3 bucket with boto. I don't needto generate a .boto file, importing packages etc..., which makes it so much easier to use, isn't it?
1- how can you explain that deleting an import which IS NOT USED in the code makes it fail?
The first hint is that the module is named a "plugin", although exactly how that's implemented isn't clear on the surface. It intuitively makes some sense that not importing a module would lead to an exception of this kind, though. Initially, I thought it was a bad practice of doing stateful activity on a global during the init of importing that module. In some ways, that is what it was, but only because class hierarchies are "state" in the meta-programmable python.
It turns out (as in many cases) that inspecting the location that stacktrace was thrown from (boto.auth.get_auth_handler()) provides the key to understanding the issue.
(see the linked source for commented version)
def get_auth_handler(host, config, provider, requested_capability=None):
ready_handlers = []
auth_handlers = boto.plugin.get_plugin(AuthHandler, requested_capability)
for handler in auth_handlers:
try:
ready_handlers.append(handler(host, config, provider))
except boto.auth_handler.NotReadyToAuthenticate:
pass
if not ready_handlers:
checked_handlers = auth_handlers
names = [handler.__name__ for handler in checked_handlers]
raise boto.exception.NoAuthHandlerFound(
'No handler was ready to authenticate. %d handlers were checked.'
' %s '
'Check your credentials' % (len(names), str(names)))
Note the reference to the class AuthHandler, which is defined in boto.auth_handler.
So, you can see that we need to look at the contents of boto.plugin.get_plugin(AuthHandler, requested_capability):
def get_plugin(cls, requested_capability=None):
if not requested_capability:
requested_capability = []
result = []
for handler in cls.__subclasses__():
if handler.is_capable(requested_capability):
result.append(handler)
return result
So, it becomes clear, at last finally when we see that the class definition of the class OAuth2Auth in gcs_oauth2_boto_plugin.oauth2_plugin, in which it is declared as a subclass of boto.auth_handler.AuthHandler, signaling its auth capabilities to the boto framework via the following member variable:
capability = ['google-oauth2', 's3']
2- more generally, to be sure to understand the authentification process, if I want to run my app on a machine, I must be sure to have the .boto file (which points to my service account private key) generated previously? Or is there a cleaner/easier way to give access to my application to Google Storage for in/out interactions?
This has a more generalized answer: You can use a .boto file, although you can also use service account credentials, and you could even use the REST API and go through an oauth2 flow to get the tokens needed to send in the Authorization header. The various methods of auth to cloud storage are in the documentation. The tutorial/doc you linked shows some methods, you've used .boto for another method. You can read about the Cloud Storage REST API (JSON) here and you can read about python oauth2 flows of various kinds here.

SUDS python connection

im trying to build an client for an webservice in python with suds. i used the tutorial
on this site: http://www.jansipke.nl/python-soap-client-with-suds. Its working with my own written Webservice and WSDL, but not with the wsdl file i got. The wsdl file is working in soapUI, i can send requests and get an answer. So the problem is, i think, how suds is parsing the wsdl file. I get following error:
urllib2.URLError: <urlopen error [Errno -2] Name or service not known>
Any ideas how to fix that? If you need more information please ask. Thank you!
The error you have given us seems to imply that the URL you are using to access the WSDL is not correct. could you show us a bit more of your code? for example the client instatiation and the url to the WSDL. this might allow others to actually help you.
Olly
# SUDS is primarily built for Python 2.6/7 (Lightweight SOAP client)
# SUDS does not work properly with other version, absolutely no support for 3.x
# Test your code with Python 2.7.12 (I am using)
from suds.client import Client
from suds.sax.text import Raw
# Use your tested URL same format with '?wsdl', Check once in SOAP-UI, below is dummy
# Make sure to use same Method name in below function 'client.service.MethodName'
url = 'http://localhost:8080/your/path/MethodName?wsdl'
#Use your Request XML, below is dummy, format xml=Raw('xml_text')
xml = Raw('<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:diag=" </soapenv:Body></soapenv:Envelope>')
def GetResCode(url, xml):
client = Client(url)
xml_response = (client.service.MethodName(__inject={'msg':xml}))
return xml_response
print(GetResCode(url,xml))

Categories