Как создать пользователя в Moodle Rest WS с помощью модуля Python Requests?

Я пытаюсь создать пользователя с помощью Moodle Webservices - Rest Server, но я застрял на проверке параметров: S Мой код следующий:

import requests

token = 'TOKENNUMBER'
function = 'core_user_create_users'


url = 'http://localhost/webservice/rest/server.php?wstoken={0}&wsfunction={1}&moodlewsformat=json'.format(token,function)

user1 = {'email': '[email protected]','firstname': 'firstname',
'lastname': 'lastname', 'createpassword': 1,
'username': 'username'}

Затем я пытаюсь опубликовать данные (двумя разными способами):

requests.post(url,data={'users': user1})
requests.post(url,data={'users': [user1,]})

И Moodle продолжает возвращать ошибку:

Only arrays accepted. The bad value is: \'username\'</DEBUGINFO>

В документации (доступной из собственного moodle) указано:

Argumentos
users (Obrigatório)


Estrutura geral

list of ( 
object {
username string   //Username policy is defined in Moodle security config.
password string  Opcional //Plain text password consisting of any characters
createpassword int  Opcional //True if password should be created and mailed to user.
firstname string   //The first name(s) of the user
lastname string   //The family name of the user
email string   //A valid and unique email address
auth string  Padrão para "manual" //Auth plugins include manual, ldap, imap, etc
idnumber string  Padrão para "" //An arbitrary ID code number perhaps from the institution
lang string  Padrão para "pt_br" //Language code such as "en", must exist on server
calendartype string  Padrão para "gregorian" //Calendar type such as "gregorian", must exist on server
theme string  Opcional //Theme name such as "standard", must exist on server
timezone string  Opcional //Timezone code such as Australia/Perth, or 99 for default
mailformat int  Opcional //Mail format code is 0 for plain text, 1 for HTML etc
description string  Opcional //User profile description, no HTML
city string  Opcional //Home city of the user
country string  Opcional //Home country code of the user, such as AU or CZ
firstnamephonetic string  Opcional //The first name(s) phonetically of the user
lastnamephonetic string  Opcional //The family name phonetically of the user
middlename string  Opcional //The middle name of the user
alternatename string  Opcional //The alternate name of the user
preferences  Opcional //User preferences
list of ( 
object {
type string   //The name of the preference
value string   //The value of the preference
} 
)customfields  Opcional //User custom fields (also known as user profil fields)
list of ( 
object {
type string   //The name of the custom field
value string   //The value of the custom field
} 
)} 
)

Итак, имея это в виду, как я могу создать пользователя Moodle с помощью модуля запросов Python? Что не так с переданными данными?


person arthas_dk    schedule 02.04.2016    source источник


Ответы (1)


Чтобы использовать службу REST в Moodle, параметры функции должны быть отформатированы в виде простого словаря. Структура аргументов отражается в именах ключей. В вашем примере у вас есть один аргумент курсы, который представляет собой список. Таким образом, ключами вашего словаря будут курсы [0] электронная почта, курсы [0] имя, ... для первого пользователя и курсы [1] электронная почта. , курсы [1] имя, ... для второго и т. д.

users = {'users[0]email': '[email protected]',
         'users[0]firstname': 'firstname',
         'users[0]lastname': 'lastname', 
         'users[0]createpassword': 1,
         'users[0]username': 'username'}
requests.post(url,data=users)
person mrcin    schedule 05.09.2016
comment
Спасибо за ответ. Для меня формат действительно очень странный ... Кажется, они используют столбец массива или что-то в этом роде, чтобы получить индекс ... - person arthas_dk; 05.09.2016
comment
похоже, что в более новых версиях Moodle он немного изменился. У меня сработало что-то вроде {'users[0][email]': '[email protected]' , ...}, добавление скобок к ключу. - person Enric Mieza; 03.05.2017