Взаимодействие с SuiteCRM API V7.9 с Python запросами - PullRequest
1 голос
/ 27 января 2020

Я уже некоторое время пытаюсь подключиться к API SuiteCRM с помощью модуля запросов Python, но безрезультатно, в официальном руководстве используется PHP: https://docs.suitecrm.com/developer/api/api-4_1/

Я не могу создать Python эквивалент этого запроса, независимо от того, что я получаю один и тот же ответ:

<pre>/**
 * SugarWebServiceImplv4_1.php
 *
 * This class is an implementation class for all the web services.  Version 4_1 adds limit/off support to the
 * get_relationships function.  We also added the sync_get_modified_relationships function call from version 
 * one to facilitate querying for related meetings/calls contacts/users records.
 *
 */
Class [ <user> class SugarWebServiceImplv4_1 extends SugarWebServiceImplv4 ] {


  - Constants [0] {
  }

  - Static properties [1] {
    Property [ public static $helperObject ]
  }

  - Static methods [0] {
  }

  - Properties [0] {
  }

  - Methods [36] {
    /**
     * Class Constructor Object
     *
     */
    Method [ <user, overwrites SugarWebServiceImplv4, ctor> public method __construct ] {

    }

    /**
     * Retrieve a collection of beans that are related to the specified bean and optionally return relationship data for those related beans.
     * So in this API you can get contacts info for an account and also return all those contact's email address or an opportunity info also.
     *
     * @param String $session -- Session ID returned by a previous call to login.
     * @param String $module_name -- The name of the module that the primary record is from.  This name should be the name the module was developed under (changing a tab name is studio does not affect the name that should be passed into this method)..
     * @param String $module_id -- The ID of the bean in the specified module
     * @param String $link_field_name -- The name of the lnk field to return records from.  This name should be the name the relationship.
     * @param String $related_module_query -- A portion of the where clause of the SQL statement to find the related items.  The SQL query will already be filtered to only include the beans that are related to the specified bean.

... что продолжается, похоже на некоторую документацию .

Это мой код:

def get_info():

    headers = {
            "Content-Type": "application/json"
        }

    creds = OrderedDict()
    creds = {"user_auth": {'user_name':"***", "password": "***"}}
    creds = json.dumps(creds)

    data = {
        'method':'login', 
        'input_type': 'JSON', 
        'response_type':'JSON', 
        'rest_data': creds
    }

    data = json.dumps(data)
    response = requests.post("http://example.com/suitecrm/service/v4_1/rest.php", headers=headers, data=data)
    print(response.text)
    return response.text

У кого-нибудь есть такой опыт? Спасибо

edit: это PHP звонок из их документов:

<?php

$url = "http://example.com/suitecrm/service/v4_1/rest.php";

function restRequest($method, $arguments){
 global $url;
 $curl = curl_init($url);
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
 $post = array(
         "method" => $method,
         "input_type" => "JSON",
         "response_type" => "JSON",
         "rest_data" => json_encode($arguments),
 );

 curl_setopt($curl, CURLOPT_POSTFIELDS, $post);

 $result = curl_exec($curl);
 curl_close($curl);
 return json_decode($result,1);
}


$userAuth = array(
        'user_name' => 'suitecrmuser',
        'password' => md5('suitecrmpassword'),
);
$appName = 'My SuiteCRM REST Client';
$nameValueList = array();

$args = array(
            'user_auth' => $userAuth,
            'application_name' => $appName,
            'name_value_list' => $nameValueList);

$result = restRequest('login',$args);
$sessId = $result['id'];

$entryArgs = array(
 //Session id - retrieved from login call
    'session' => $sessId,
 //Module to get_entry_list for
    'module_name' => 'Accounts',
 //Filter query - Added to the SQL where clause,
    'query' => "accounts.billing_address_city = 'Ohio'",
 //Order by - unused
    'order_by' => '',
 //Start with the first record
    'offset' => 0,
 //Return the id and name fields
    'select_fields' => array('id','name',),
 //Link to the "contacts" relationship and retrieve the
 //First and last names.
    'link_name_to_fields_array' => array(
        array(
                'name' => 'contacts',
                        'value' => array(
                        'first_name',
                        'last_name',
                ),
        ),
),
   //Show 10 max results
        'max_results' => 10,
   //Do not show deleted
        'deleted' => 0,
 );
 $result = restRequest('get_entry_list',$entryArgs);

print_r($result);

1 Ответ

1 голос
/ 08 февраля 2020

Пожалуйста, проверьте этот рабочий пример, он должен помочь вам начать. Его использование python3.

import urllib.request
import json
import hashlib

encode = hashlib.md5("MasterPass".encode('utf-8'))
encodedPassword = encode.hexdigest()
args = {'user_auth': {'user_name': 'admin','password': encodedPassword}}
crmUrl="https://yourname.crm.cr/service/v4_1/rest.php"
data = json.dumps(args)
args = {'method': 'login', 'input_type': 'json',
        'response_type' : 'json', 'rest_data' : data}
params = urllib.parse.urlencode(args).encode('utf-8')
response = urllib.request.urlopen(crmUrl, params)
response = response.read().strip()
if not response:
    print( "error: " , response)
result = json.loads(response.decode('utf-8'))
print (result)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...