Best Python code snippet using localstack_python
shopify_config.py
Source:shopify_config.py
1# -*- coding: utf-8 -*-2# Part of Odoo. See LICENSE file for full copyright and licensing details.3import uuid4from itertools import groupby5from datetime import datetime, timedelta6from werkzeug.urls import url_encode7from odoo import api, fields, models, _8from odoo.exceptions import UserError, AccessError9from odoo.osv import expression10from odoo.tools import float_is_zero, float_compare, DEFAULT_SERVER_DATETIME_FORMAT11from odoo.tools.misc import formatLang12from odoo.addons import decimal_precision as dp13import requests14import json15import logging16_logger = logging.getLogger(__name__)17headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}18import shopify19import re20class ShopifyConfig(models.Model):21 _name = 'shopify.config'22 23 name = fields.Char('Name')24 api_url = fields.Char('URL',default='wisefood-shop.myshopify.com')25 api_key = fields.Char('API Key')26 api_pwd = fields.Char('Password')27 state = fields.Selection([('draft','Draft'),('connected','Connected'),('failed','Failed')],string='State', default='draft')28 29 @api.model30 def create(self, vals):31 shopify = self.env['shopify.config'].search([])32 if shopify:33 raise UserError(_("Cannot Create Second"))34 35 return super(ShopifyConfig,self).create(vals)36 37 @api.multi38 def action_test_connection(self):39 shop=self.api_url.split("//")40 if len(shop) == 2:41 shop_url = shop[0]+"//"+self.api_key+":"+self.api_pwd+"@"+shop[1]+"/admin"42 else :43 shop_url = "https://"+self.api_key+":"+self.api_pwd+"@"+shop[0]+"/admin"44 shopify.ShopifyResource.set_site(shop_url)45 46 47 try:48 shop_id = shopify.Shop.current()49 shopify_resp = shopify50 self.write({'state':'connected'})51 return shopify_resp52 except Exception as e:53 raise Warning(e)54 55 56 @api.multi57 def action_import_products(self):58 for shop in self:59 if shop.state == 'connected':60 shopify_resp = shop.action_test_connection()61 products = shopify_resp.Product().find(limit=250)62 for product in products:63 response_template=product.to_dict()64 65 for variant in response_template.get('variants'):66 print (variant)67 odoo_products = self.env['product.product'].search([('default_code','=',variant.get('sku'))], limit=1)68 if odoo_products:69 odoo_products.write({70 'name' : response_template.get('title') + ' - ' +variant.get('title'),71 #'type' : 'product',72 'shopify_id' : variant.get('id'),73 })74 if not odoo_products:75 odoo_products = self.env['product.product'].create({76 'name' : response_template.get('title') +' - ' +variant.get('title'),77 'type' : 'product',78 'shopify_id' : variant.get('id'),79 'default_code' : variant.get('sku')80 })81 82 @api.multi83 def action_import_order(self):84 for shop in self:85 if shop.state == 'connected':86 shopify_resp = shop.action_test_connection()87 print ('>>>>>>>>>> ',dir(shopify_resp))88 orders = shopify_resp.Order().find(fulfillment_status='unshipped',financial_status='paid',limit=250)89 product_uom = self.env['product.uom.categ'].search([('name','=','Unit')])90 for order in orders:91 response_template = order.to_dict()92 sale_order = self.env['sale.order'].search([('name','=',response_template.get('order_number')),('shopify_id','=',response_template.get('id'))])93 if not sale_order:94 partner_shipping = False95 partner = False96 97 98 customer_resp = response_template.get('customer')99 street_no = ''100 street_no_list = re.findall(r'\d+', customer_resp['default_address'].get('address1'))101 if street_no_list:102 street_no = street_no_list[0]103 104 street_name = ''105 street1 = re.sub(r'\d+', '', customer_resp['default_address'].get('address1'))106 if street1:107 if customer_resp['default_address'].get('address2'):108 street_name = street1 + customer_resp['default_address'].get('address2')109 else:110 street_name = street1 111 country = self.env['res.country'].search([('name','=',customer_resp['default_address'].get('country_name'))])112 partner_vals = {113 'first_name' : customer_resp.get('first_name'),114 'last_name' : customer_resp.get('last_name') if customer_resp.get('last_name') else '-',115 'name' : customer_resp.get('first_name') + ' ' + customer_resp.get('last_name') if customer_resp.get('last_name') else '-',116 'email' : customer_resp.get('email'),117 'custom_company_name' : customer_resp['default_address'].get('company'),118 'street2' : street_name,119 'street' : street_no,120 'city' : customer_resp['default_address'].get('city'),121 'zip' : customer_resp['default_address'].get('zip'),122 'phone' : customer_resp['default_address'].get('phone'),123 'country_id' : country.id if country else False,124 'customer' : True,125 'shopify_id' : customer_resp.get('id'),126 127 }128 129 130 partner = self.env['res.partner'].search([('email','=',customer_resp.get('email')),('shopify_id','=',customer_resp.get('id'))])131 if partner:132 partner.write(partner_vals)133 if not partner:134 partner = self.env['res.partner'].create(partner_vals)135 136 shipcloud_carrier_id = False137 carrier_services_id = False138 package_type_id = False139 140 if response_template.get('shipping_lines'):141 142 shipping_lines = response_template.get('shipping_lines')143 print ('shipping_lines shipping_lines ',shipping_lines)144 if len(shipping_lines) >= 1:145 #if shipping_lines[0].get('code') == 'DHL':146 dhl_id = self.env['shipcloud.carrier'].search([('name','=','dhl')])147 if dhl_id:148 shipcloud_carrier_id = dhl_id.id149 dhl_carrier_services_id = self.env['carrier.services'].search([('name','=','standard')])150 if dhl_carrier_services_id:151 carrier_services_id = dhl_carrier_services_id.id152 dhl_package_type_id = self.env['package.type'].search([('name','=','parcel')])153 if dhl_package_type_id:154 package_type_id = dhl_package_type_id.id155# else:156# hsi_id = self.env['shipcloud.carrier'].search([('name','=','hsi')])157# if hsi_id:158# shipcloud_carrier_id = hsi_id.id159# hsi_carrier_services_id = self.env['carrier.services'].search([('name','=','standard')])160# if hsi_carrier_services_id:161# carrier_services_id = hsi_carrier_services_id.id162# hsi_package_type_id = self.env['package.type'].search([('name','=','parcel')])163# if hsi_package_type_id:164# package_type_id = hsi_package_type_id.id165 166 167 168 if partner:169 country = self.env['res.country'].search([('name','=',response_template['shipping_address'].get('country_name'))])170 if not partner.street2 == response_template['shipping_address'].get('address1'):171 partner_shipping = self.env['res.partner'].search([('type','=','delivery'),('street2','=',response_template['shipping_address'].get('address1'))])172 if not partner_shipping:173 174 175 street_no = ''176 street_no_list = re.findall(r'\d+', response_template['shipping_address'].get('address1'))177 if street_no_list:178 street_no = street_no_list[0]179 180 street_name = ''181 street1 = re.sub(r'\d+', '', response_template['shipping_address'].get('address1'))182 if street1:183 if response_template['shipping_address'].get('address2'):184 street_name = street1 + response_template['shipping_address'].get('address2')185 else:186 street_name = street1187 188 189 190 shipping_vals = {191 'parent_id' : partner.id,192 'type' : 'delivery',193 'street2' : street_name,194 'street' : street_no,195 'city' : response_template['shipping_address'].get('city'),196 'zip' : response_template['shipping_address'].get('zip'),197 'phone' : response_template['shipping_address'].get('phone'),198 'first_name' : response_template['shipping_address'].get('first_name'),199 'last_name' : response_template['shipping_address'].get('last_name') if response_template['shipping_address'].get('last_name') else '-',200 'name' : response_template['shipping_address'].get('first_name') + ' ' + response_template['shipping_address'].get('last_name') if response_template['shipping_address'].get('last_name') else '-', 201 'country_id' : country.id if country else False,202 }203 204 partner_shipping = self.env['res.partner'].create(shipping_vals)205 206 sale_order = self.env['sale.order'].create({207 'shopify_id' : response_template.get('id'),208 'partner_id' : partner.id,209 'partner_shipping_id' : partner_shipping.id if partner_shipping else partner.id,210 'partner_invoice_id' : partner.id,211 'name' : response_template.get('order_number'),212 'date_order' : response_template.get('created_at'),213 'shipcloud_carrier_id' : shipcloud_carrier_id,214 'carrier_services_id' : carrier_services_id,215 'package_type_id' : package_type_id216 })217 print ('sale_order sale_order ',sale_order)218 for line in response_template.get('line_items'):219 if line.get('variant_id'):220 product = self.env['product.product'].search([('shopify_id','=',line.get('variant_id'))])221 if not product:222 shop.action_import_products()223 product = self.env['product.product'].search([('shopify_id','=',line.get('variant_id'))])224 225 if product:226 name = product.name_get()[0][1]227 if product.description_sale:228 name += '\n' + product.description_sale229 sale_line = self.env['sale.order.line'].create({230 'order_id' : sale_order.id,231 'product_id' : product.id,232 'name' : name,233 'product_uom_qty' : line.get('quantity'),234 'price_unit' : line.get('price'), 235 'product_uom' : product_uom.id if product_uom else False #unit236 })237 238 239 240 241 242 243class ProductTemplate(models.Model):244 _inherit = 'product.template'245 246 shopify_id = fields.Char(string='Shopify ID')247class Product(models.Model):248 _inherit = 'product.product'249 250 shopify_id = fields.Char(string='Shopify ID')251class SaleOrder(models.Model):252 _inherit = 'sale.order'253 254 shopify_id = fields.Char(string='Shopify ID')255class Partner(models.Model):256 _inherit = 'res.partner'257 258 shopify_id = fields.Char(string='Shopify ID')259 ...
http_service.py
Source:http_service.py
1# -*- coding: utf-8 -*-2import json3from flask import Flask, request4from jinja2 import Environment5app = Flask(__name__)6environment = Environment()7def jsonfilter(value):8 return json.dumps(value)9environment.filters["json"] = jsonfilter10with open('call_john/contacts.json', "r") as json_file:11 CONTACTS = json.load(json_file)12 CONTACTS["contact_john"]["mobile"] = "0701234567"13 CONTACTS["contact_john"]["home"] = "031122363"14 CONTACTS["contact_john"]["work"] = "0736582934"15 CONTACTS["contact_lisa"]["mobile"] = "0709876543"16 CONTACTS["contact_lisa"]["home"] = "031749205"17 CONTACTS["contact_lisa"]["work"] = "0763559230"18# CONTACTS["contact_andy"]["null"] = 019 CONTACTS["contact_mary"]["mobile"] = "0706574839"20 CONTACTS["contact_mary"]["home"] = "0784736475"21 CONTACTS["contact_mary"]["work"] = "0784736475"22# with open('call_john/contacts.json', "w") as json_file:23# json.dump(CONTACTS, json_file)24def error_response(message):25 response_template = environment.from_string("""26 {27 "status": "error",28 "message": {{message|json}},29 "data": {30 "version": "1.0"31 }32 }33 """)34 payload = response_template.render(message=message)35 response = app.response_class(36 response=payload,37 status=200,38 mimetype='application/json'39 )40 return response41def query_response(value, grammar_entry):42 response_template = environment.from_string("""43 {44 "status": "success",45 "data": {46 "version": "1.1",47 "result": [48 {49 "value": {{value|json}},50 "confidence": 1.0,51 "grammar_entry": {{grammar_entry|json}}52 }53 ]54 }55 }56 """)57 payload = response_template.render(value=value, grammar_entry=grammar_entry)58 response = app.response_class(59 response=payload,60 status=200,61 mimetype='application/json'62 )63 return response64def validator_response(is_valid):65 response_template = environment.from_string("""66 {67 "status": "success",68 "data": {69 "version": "1.0",70 "is_valid": {{is_valid|json}}71 }72 }73 """)74 payload = response_template.render(is_valid=is_valid)75 response = app.response_class(76 response=payload,77 status=200,78 mimetype='application/json'79 )80 return response81@app.route("/dummy_query_response", methods=['POST'])82def dummy_query_response():83 response_template = environment.from_string("""84 {85 "status": "success",86 "data": {87 "version": "1.1",88 "result": [89 {90 "value": "dummy",91 "confidence": 1.0,92 "grammar_entry": null93 }94 ]95 }96 }97 """)98 payload = response_template.render()99 response = app.response_class(100 response=payload,101 status=200,102 mimetype='application/json'103 )104 return response105@app.route("/action_success_response", methods=['POST'])106def action_success_response():107 response_template = environment.from_string("""108 {109 "status": "success",110 "data": {111 "version": "1.1"112 }113 }114 """)115 payload = response_template.render()116 response = app.response_class(117 response=payload,118 status=200,119 mimetype='application/json'120 )121 return response122@app.route("/call", methods=['POST'])123def call():124 payload = request.get_json()125 select_contact = payload["context"]["facts"]["select_contact"]["value"]126 select_number = payload["context"]["facts"]["select_number"]["value"]127 if CONTACTS[select_contact][select_number]:128 # if select_contact == "contact_john":129 # CONTACTS["contact_john"]["mobile"]130 # CONTACTS["contact_john"]["home"]131 # CONTACTS["contact_john"]["work"]132 # elif select_contact == "contact_lisa":133 # CONTACTS["contact_lisa"]["mobile"]134 # CONTACTS["contact_lisa"]["home"]135 # CONTACTS["contact_lisa"]["work"] 136 # elif select_contact == "contact_mary":137 # CONTACTS["contact_mary"]["mobile"] 138 # CONTACTS["contact_mary"]["home"] 139 # CONTACTS["contact_mary"]["work"] 140 # elif selected_alarm_time == "off":141 # CLOCK["current_alarm"]["alarm_hour"] = 0142 # CLOCK["current_alarm"]["alarm_minute"] = 0143 # CLOCK["current_alarm"]["alarm_on"] = False144 # with open('time/clock.json', "w") as json_file:145 # json.dump(CLOCK, json_file)146 return action_success_response()147 148@app.route("/find_number", methods=['POST'])149def find_number():150 payload = request.get_json()151 select_contact = payload["context"]["facts"]["select_contact"]["value"]152 select_number = payload["context"]["facts"]["select_number"]["value"]153 number = CONTACTS[select_contact][select_number]154 print(number)155 # print(find_number)156 # with open('time/clock.json', "w") as json_file:157 # json.dump(CONTACTS, json_file)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!