API продуктов Opencart

, когда вы рекурсируете, вам нужно return получить результат _finditem

def _finditem(obj, key):
    if key in obj: return obj[key]
    for k, v in obj.items():
        if isinstance(v,dict):
            return _finditem(v, key)  #added return statement

. Чтобы исправить фактический алгоритм, вам нужно понять, что _finditem возвращает None, если он 't найти что-нибудь, поэтому вам нужно проверить это явно, чтобы предотвратить ранний возврат:

def _finditem(obj, key):
    if key in obj: return obj[key]
    for k, v in obj.items():
        if isinstance(v,dict):
            item = _finditem(v, key)
            if item is not None:
                return item

Конечно, это не удастся, если у вас есть None значения в любом из ваших словарей. В этом случае вы можете настроить дозор object() для этой функции и вернуть это в случае, если вы ничего не нашли. Затем вы можете проверить sentinel, чтобы узнать, нашли ли вы что-то или нет.

1
задан Gowri 17 January 2019 в 09:12
поделиться

3 ответа

Итак, у вас уже есть токен:

session.post(
    'http://myopencart.example.com/index.php?route=api/cart/products',
  params={'api_token':'768ef1810185cd6562478f61d2'},
  data={}
)
0
ответ дан MorganFreeFarm 17 January 2019 в 09:12
поделиться

Opencart v.2.1.0.2 , v.2.2.0.0 и amp; v.2.3.0.2

В /catalog/controller/api/
- cart.php
- coupon.php
- [113 ]
- customer.php
- login.php
- order.php
- payment.php
- [118 ]
- shipping.php
- voucher.php

Это то, что вы можете использовать.
Для всего остального вам придется построить его самостоятельно.

0
ответ дан kanenas 17 January 2019 в 09:12
поделиться

Если кто-то ищет OpenCart 3, то это может помочь:

Как вывести продукты json через API в Opencart?

Посмотреть это видео на YouTube , он описывает, как создать пользовательский API OpenCart, и подробно описывает, как его использовать.

На отвечающем сервере перейдите в каталог / controller / api / и создайте product.php и вставьте следующие строки кода:

<?php
class ControllerApiProduct extends Controller
{
    public function index()
    {
        $this->load->language('api/cart');
        $this->load->model('catalog/product');
        $this->load->model('tool/image');
        $json = array();
        $json['products'] = array();
        $filter_data = array();
        $results = $this->model_catalog_product->getProducts($filter_data);
        foreach ($results as $result) {
            if ($result['image']) {
                $image = $this->model_tool_image->resize($result['image'], $this->config->get('theme_' . $this->config->get('config_theme') . '_image_product_width'), $this->config->get('theme_' . $this->config->get('config_theme') . '_image_product_height'));
            } else {
                $image = $this->model_tool_image->resize('placeholder.png', $this->config->get('theme_' . $this->config->get('config_theme') . '_image_product_width'), $this->config->get('theme_' . $this->config->get('config_theme') . '_image_product_height'));
            }
            if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
                $price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
            } else {
                $price = false;
            }
            if ((float) $result['special']) {
                $special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
            } else {
                $special = false;
            }
            if ($this->config->get('config_tax')) {
                $tax = $this->currency->format((float) $result['special'] ? $result['special'] : $result['price'], $this->session->data['currency']);
            } else {
                $tax = false;
            }
            if ($this->config->get('config_review_status')) {
                $rating = (int) $result['rating'];
            } else {
                $rating = false;
            }
            $data['products'][] = array(
                'product_id' => $result['product_id'],
                'thumb' => $image,
                'name' => $result['name'],
                'description' => utf8_substr(trim(strip_tags(html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8'))), 0, $this->config->get('theme_' . $this->config->get('config_theme') . '_product_description_length')) . '..',
                'price' => $price,
                'special' => $special,
                'tax' => $tax,
                'minimum' => $result['minimum'] > 0 ? $result['minimum'] : 1,
                'rating' => $result['rating'],
                'href' => $this->url->link('product/product', 'product_id=' . $result['product_id']),
            );
        }
        $json['products'] = $data['products'];
        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }
}

На вашем запрашивающем сервере создайте файл, скажем, apiproducts.php, и вставьте следующий код и запустите его:

<?php
$url = "https://webocreation.com/nepalbuddha";
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => $url . "/index.php?route=api%2Fproduct",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
        "cache-control: no-cache",
    ),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
    echo "cURL Error #:" . $err;
} else {
    echo $response;
}

Вы получите ответ, как показано ниже:

{
    "products": [{
        "product_id": "30",
        "thumb": "https:\/\/webocreation.com\/nepalbuddha\/image\/cache\/catalog\/demo\/canon_eos_5d_1-228x228.jpg",
        "name": "Canon EOS 5D",
        "description": "Canon's press material for the EOS 5D states that it 'defines (a) new D-SLR category', while we're n..",
        "price": "$122.00",
        "special": "$98.00",
        "tax": "$80.00",
        "minimum": "1",
        "rating": 0,
        "href": "https:\/\/webocreation.com\/nepalbuddha\/index.php?route=product\/product&product_id=30"
    }, {
        "product_id": "47",
        "thumb": "https:\/\/webocreation.com\/nepalbuddha\/image\/cache\/catalog\/demo\/hp_1-228x228.jpg",
        "name": "HP LP3065",
        "description": "Stop your co-workers in their tracks with the stunning new 30-inch diagonal HP LP3065 Flat Panel Mon..",
        "price": "$122.00",
        "special": false,
        "tax": "$100.00",
        "minimum": "1",
        "rating": 0,
        "href": "https:\/\/webocreation.com\/nepalbuddha\/index.php?route=product\/product&product_id=47"
    }]
}

Вы можете проверить следующие сообщения, связанные с API Opencart:

https://webocreation.com/blog/pull-products-json-through-ap-opencart https://webocreation.com/blog/opencart-api-documentation-to-create- read-query-update-and-upsert https://webocreation.com/blog/opencart-api-documentation-developer

0
ответ дан Rupak Nepali 17 January 2019 в 09:12
поделиться
Другие вопросы по тегам:

Похожие вопросы: