Add new Domain Zone in OVH using API - python

I want to add a new DNS zone in OVH with Python using the OVH API.
I wrote a script with these steps:
Create a new cart
Add a new DNS zone to the cart
Check the cart content
Confirm the order
Check the order status
Did I forget a step or is there an error somewhere? Because when I look in GET orders I don't see new orders and also they don't appear in the GUI.
cart = client.post('/order/cart', ovhSubsidiary='PL')
#Get the cart ID
cart_id = cart.get('cartId')
#Set data for the new DNS zone
zone_name = 'testttt.pl' # DNS zone name
#Add the new DNS zone to the cart
result = client.post(f'/order/cart/{cart_id}/dns',
domain=zone_name,
duration="P1Y",
planCode="zone",
pricingMode="default",
quantity=1)
#Check if the operation was successful
if 'itemId' in result:
print(f'DNS zone {zone_name} was added to the cart.')
else:
print('Error while adding DNS zone to the cart.')
#Display the cart contents
cart_info = client.get(f'/order/cart/{cart_id}')
print(f'Cart contents:\n{json.dumps(cart_info, indent=4)}')
#Make sure the cart is ready to order
order = client.post(f'/order/cart/{cart_id}/checkout', autoPayWithPreferredPaymentMethod=True)
print(f'Order {order.get("orderId")} has been placed.')
order_id = cart_info['orders'][-1]
#Check the status of the order
order_status = client.get(f'/me/order/{order_id}/status')
print(f'Order {order_id} status: {order_status}')```

After creating the cart, and before adding your DNS zone (or any other products) to this cart, you need to assign this cart to yourself.
It can be done with this route:
# Assign a shopping cart to an loggedin client
POST /order/cart/{cartId}/assign
So your script should looks like:
import ovh
# For these 3 keys, refer to the documentation:
# - https://github.com/ovh/python-ovh#use-the-api-on-behalf-of-a-user
# - Generate the keys easily via https://www.ovh.com/auth/api/createToken
client = ovh.Client(
endpoint='ovh-eu',
application_key='<app_key>',
application_secret='<app_secret>',
consumer_key='<consumer_key>'
)
# Initiate a new cart
cart = client.post(
'/order/cart',
ovhSubsidiary='PL'
)
cart_id = cart.get('cartId')
# Assign this cart to the currently logged-in user
assign = client.post(
f'/order/cart/{cart_id}/assign'
)
zones_to_order = ['domain-1.ovh', 'domain-2.ovh', 'domain-3.ovh']
for domain in zones_to_order:
# Add a new DNS zone to the cart
result = client.post(
f'/order/cart/{ cart_id }/dns',
duration="P1Y",
planCode="zone",
pricingMode="default"
)
itemId = result.get("idemId")
# Configure the DNS zone in the cart
client.post(
f'/order/cart/{cart_id}/item/{ itemId }/configuration',
label="zone",
value=domain
)
# Finalyze your order
checkout = client.post(
f'/order/cart/{cart_id}/checkout'
)

Related

Shopify Python - Set inventory quantity

I'm trying to set inventory quantity of a product in shopify using the Shopify Python Api.
As i understand it, i need to set the 'inventory_level' of the 'inventory_item' that belongs to the product, but after a few days of searching and testing i still have no luck.
Where i'm at
I have my products showing up in my store with all the data but the inventory quantity.
I'm not sure how to proceed as there's not a whole lot of documentation.
Here's my code for creating a product
def CreateShopifyProduct(data):
# CREATE PRODUCT
product = shopify.Product()
# Add stuff to product, variant and inventoryItem here
product.title = data['title']
#product.status = ""
#product.tags = data['tags']
product.body_html = data['description']
if 'catagory' in data:
product.product_type = data['category']
if 'vendor' in data:
product.vendor = data['vendor']
if 'image_url' in data:
image_path = data['image_url']
image = shopify.Image()
image.src = image_path
product.images = [image]
else:
try:
image = GetLocalImageFiles(data['id'])
product.images = [image]
except:
print("No local images found")
success = product.save() #returns false if the record is invalid
# CREATE VARIANT
variant = shopify.Variant()
if 'ean' in data:
variant.barcode = data['ean']
variant.price = data['gross_price']
variant.weight = data['weight']
#variant.count = data['inventory']
variant.inventory_management = 'shopify'
product.variants = [variant]
variant.product_id = product.id
s = variant.save()
success = product.save() #returns false if the record is invalid
# CREATE INVENTORYITEM
inventoryItem = shopify.InventoryItem()
#inventoryItem = variant.inventory_item
inventoryItem.tracked = True
inventoryItem.id = product.id
variant.inventory_quantity = data['inventory']
inventoryItem.inventory_quantity = data['inventory']
variant.inventory_item = inventoryItem
s = variant.save()
success = product.save()
#ii = inventoryItem.save() # this returns 406
#inv_level = shopify.InventoryLevel.find(inventory_item_ids=6792364982390, location_ids=61763518582)
#quantity = inv_level[0].__dict__['attributes']['available']
#shopify.InventoryLevel.set(location_id=61763518582, inventory_item_id=variant.inventory_item.id, available=data['inventory'])
#shopify.InventoryLevel.connect(61763518582, variant.inventory_item.id)
if product.errors:
#something went wrong, see new_product.errors.full_messages() for example
print("error")
print(product.errors.full_messages())
If i try to set the InventoryLevel with
shopify.InventoryLevel.set(61527654518, inventoryItem.id, 42)
# or
shopify.InventoryLevel.set(location_id=61527654518, inventory_item_id=inventoryItem.id, available=17)
I recieve a
pyactiveresource.connection.ResourceNotFound: Not Found: https://domain.myshopify.com/admin/api/2022-07/inventory_levels/set.json
You need three things to update an inventory level. One, you need a valid location ID. Two, you need the inventory item ID. Finally, you need the amount to adjust inventory to, that will adjust the inventory there to match your needs.
You should really play at the command-line and ensure you can quickly get the information you need, then try your updates. In other words, ensure you are getting a good location ID, inventory item ID and finally, that you know the amount of inventory already in Shopify. Since you have to calculate a delta change, these are the minimum steps most people take.
Note that once you get good at doing one item, you'll realize Shopify also accepts up to 100 at a time, making your updates a lot faster.

[Odoo][v10] Add subscription types for a follower from Python in Odoo v10

I building my own module, and for each project, I add a calendar event with followers from the project.
So i write a method:
def create_calendar_event(self):
create_event = self.env['calendar.event'].create({'start': self.start_date, 'stop': self.end_date, 'name': self.title})
self.calendar_id = create_event
partner_list = []
for follower in self.project_id.message_follower_ids:
partner_list.append(follower.partner_id.id)
self.testfield = str(partner_list) # Debug
calendar_fallowers = []
for follower2 in self.calendar_id.message_follower_ids:
calendar_fallowers.append(follower2.partner_id.id)
self.testfield_calendar = str(calendar_fallowers) # Debug
# add followers from project to calendar
for partner in partner_list:
if partner not in calendar_fallowers:
res_id = self.calendar_id.id
res_model = 'calendar.event'
partner_id = partner
self.env['mail.followers'].create({'res_id': res_id, 'res_model': res_model, 'partner_id': partner_id})
self.env.cr.commit()
So I have calendar event with followers, but I don't have any default subscription types.
and I wanna add default subscription types for all followers: Discussions and Note
How to do this?
To add followers odoo provide a method for :
self.calendar_id.message_subscribe(partner_list)
And to remove folowers :
some_record.message_unsubscribe(partner_list)

Python - How to Set Custom Fields using NetSuite webservices

I'm trying to be able to set a custom fields in NetSuite using webservices.
The WSDL I'm using is: https://webservices.netsuite.com/wsdl/v2017_2_0/netsuite.wsdl
Currently I'm testing it on creating a customer. Here's what I have so far:
def add_customer():
client = login_client()
RecordRef = client.get_type('ns0:RecordRef')
Customer = client.get_type('ns13:Customer')
customer = Customer(
companyName='TEST',
subsidiary = RecordRef(internalId='5', type='subsidiary')
)
response = client.service.add(customer)
print(response)
add_customer()
This Works perfectly, but now I'm trying to set a custom field with id custfield1
After doing some searching, I found:
http://www.netsuite.com/help/helpcenter/en_US/srbrowser/Browser2016_2/schema/other/customfieldlist.html?mode=package
From this link I know that I'll be needing to use CustomFieldRef, I'm just not sure how it would be implemented.
I found a way to do this:
def add_customer():
client = login_client()
RecordRef = client.get_type('ns0:RecordRef')
StringCustomFieldRef = client.get_type('ns0:StringCustomFieldRef') #StringCustomFieldRef
CustomFieldList = client.get_type('ns0:CustomFieldList') #To go from object to list
#Cust field 1
acctName = StringCustomFieldRef()
acctName.internalID = '1569'
acctName.scriptId = 'custentity_account_name'
acctName.value = 'testData'
#custField2
acctID= StringCustomFieldRef()
acctID.internalId= '1596'
acctID.scriptId= 'custentity_sf_account_id'
acctID.value = 'FIELD DATA'
Customer = client.get_type('ns13:Customer')
customer = Customer(
companyName='TEST',
entityId='TEST ID',
subsidiary = RecordRef(internalId='5', type='subsidiary'),
customFieldList = CustomFieldList([acctID,acctName]) #List of cust objects
)
response = client.service.add(customer)
print(response)
add_customer()
You have to use the Ref type for the field you are working with: https://system.na1.netsuite.com/app/help/helpcenter.nl?fid=section_n3458179.html

How to correctly Update Odoo / Openerp website context?

I trying to adapt the module https://www.odoo.com/apps/modules/9.0/website_sale_product_brand/ to have a select box on the shop page, and filter by brand and category, and not to have to go to a diferent page and select the brand.
In that module they update context with the brand_id so the sale_product_domain function could append to the domain. In the module, it filter it as a charm, but in my code not....
Any guest?
When I debug self.env.context in the sale_product_domain function not brand if append, but in the website_sale_product_brand yes, with the exactly same code
controller.py
class WebsiteSale(website_sale):
#http.route(['/shop',
'/shop/page/<int:page>',
'/shop/category/<model("product.public.category"):category>',
'/shop/category/<model("product.public.category"):category>/page/<int:page>',
],type='http',auth='public',website=True)
def shop(self, page=0, category=None, search='', brand=None, **post):
# Update context to modify sale_product_domain function from website model
if brand:
context = dict(request.env.context)
context.setdefault('brand', int(brand))
request.env.context = context
result = super(WebsiteSale, self).shop(page=page, category=category,
brand=brand, search=search,
**post)
#append brand to keep so links mantain brand filter
keep = QueryURL('/shop',
brand=brand,
category=category and int(category),
search=search,)
#attrib=attrib_list TODO
#Update result
result.qcontext['keep'] = keep
result.qcontext['brands'] = http.request.env['product.brand'].search([]) #use to populate template select box
result.qcontext['sel_brand_id'] = brand #use to select the selected brand on brand select box
return result
models.py
class WebSite(models.Model):
_inherit = 'website'
#api.multi
def sale_product_domain(self):
domain = super(WebSite, self).sale_product_domain()
print self.env.context
if 'brand' in self.env.context:
domain.append(
('product_brand_id', '=', self.env.context['brand']))
return domain
ctx = dict (request.context)
ctx.update ({'bin_size': True})
request.context = ctx
That's it!

return all objects associated with a user

how can I get objects that are associated with a user
I am creating this app for managing/tracking customers
I have form which is used to save customer personal info and another field which is how much they are willing to spend + We can assign the customer to a user to be dealt with.
e.g. user1 assigned to customer1, customer2, customer3
I want to get one amount they willing to spend from all customers assigned to user1
So for example something like this
[<user1: <customer1:$10> <customer2:$100> <customer3:$1000>]
And then sum the prices together so something like this [<user1: total:$1110>]
this is what I done but doesn't seem to work
annual_spend = Lead.objects.filter(assign_to=User).exclude(lead_status='converted').aggregate(Sum('annual_spend'))
How could I do this any ideas?
For specific user:
this_user = User.objects.get(id=ENTER USER ID HERE)
annual_spend['annual_spend__sum'] = Lead.objects.filter(assign_to=this_user).exclude(lead_status='converted').aggregate(Sum('annual_spend'))
or if you want it for the user that is authenticated:
annual_spend['annual_spend__sum'] = Lead.objects.filter(assign_to=request.user).exclude(lead_status='converted').aggregate(Sum('annual_spend'))
grand total for all Lead instances:
annual_spend['annual_spend__sum'] = Lead.objects.all().exclude(lead_status='converted').aggregate(Sum('annual_spend'))
For a table with value for each user:
all_users = User.objects.all()
values = {}
for this_user in all_users:
values[this_user.id] = Lead.objects.filter(assign_to=this_user).exclude(lead_status='converted').aggregate(Sum('annual_spend'))['annual_spend__sum']

Categories