- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在尝试使用 Python 的请求库访问 Moodle 安装的 Web 服务。我有 API 的文档和一个用 php 编写的示例项目(我以前没有看过 php,它比我期望的要理解的难得多)但是我真的很难正确地格式化请求。该站点返回检测到的无效参数,因此我非常确定我的端点、授权 token 和服务器配置正常工作,只是数据格式让我失望。
首先这里是错误...
<?xml version="1.0" encoding="UTF-8" ?>
<EXCEPTION class="invalid_parameter_exception">
<ERRORCODE>invalidparameter</ERRORCODE>
<MESSAGE>Invalid parameter value detected</MESSAGE>
</EXCEPTION>
现在我的代码...
import requests
target = 'http://example.com/moodle/webservice/rest/server.php?'
moodle_create_token = 'xxx'
moodle_enrol_token = 'yyy'
url_payload = {
"wstoken":moodle_create_token,
"wsfunction":"core_user_create_users"
}
###not sure if I should just be passing this as a dict or some deeper more layered struct
payload = {
"username":"testuser",
"password":'testpass',
"firstname":'testf',
"lastname":'testl',
"email":"test@example.com",
"idnumber":"1234"
}
###not sure how to include the payload as the last argument in the function (currently data=)
###I feel like at this point I've just been throwing random data at it and hoping something sticks haha.
r=requests.post(target, params=url_payload, data=payload)
这是网站的文档
moodle api XML-RPC (PHP structure)
moodle api REST (POST parameters)
最后是 php 中的示例。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>V6</title>
</head>
<body>
<?php
//load curl.php
require_once('curl.php');
function randomPassword() //according to Moodle password requirements
{
$part1 = "";
$part2 = "";
$part3 = "";
//alphanumeric LOWER
$alphabet = "abcdefghijklmnopqrstuwxyz";
$password_created = array(); //remember to declare $pass as an array
$alphabetLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 3; $i++)
{
$pos = rand(0, $alphabetLength); // rand(int $min , int $max)
$password_created[] = $alphabet[$pos];
}
$part1 = implode($password_created); //turn the array into a string
//echo"<br/>part1 = $part1";
//alphanumeric UPPER
$alphabet = "ABCDEFGHIJKLMNOPQRSTUWXYZ";
$password_created = array(); //remember to declare $pass as an array
$alphabetLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 3; $i++)
{
$pos = rand(0, $alphabetLength); // rand(int $min , int $max)
$password_created[] = $alphabet[$pos];
}
$part2 = implode($password_created); //turn the array into a string
//echo"<br/>part2 = $part2";
//alphanumeric NUMBER
$alphabet = "0123456789";
$password_created = array(); //remember to declare $pass as an array
$alphabetLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 2; $i++)
{
$pos = rand(0, $alphabetLength); // rand(int $min , int $max)
$password_created[] = $alphabet[$pos];
}
$part3 = implode($password_created); //turn the array into a string
//echo"<br/>part3 = $part3";
$password = $part1 . $part2 . $part3 . "#";
return $password;
}
function getCDate()
{
$format = "Ymd";
$fulldate = date($format);
//echo"<br/>fulldate = $fulldate";
return $fulldate;
}
function enrol($user_id, $course_id)
{
$role_id = 5; //assign role to be Student
$domainname = 'http://www.yoursite.eu'; //paste your domain here
$wstoken = '8486ed14f3ghjec8967a0229d0a28zzz'; //here paste your enrol token
$wsfunctionname = 'enrol_manual_enrol_users';
$enrolment = array( 'roleid' => $role_id, 'userid' => $user_id, 'courseid' => $course_id );
$enrolments = array($enrolment);
$params = array( 'enrolments' => $enrolments );
header('Content-Type: text/plain');
$serverurl = $domainname . "/webservice/rest/server.php?wstoken=" . $wstoken . "&wsfunction=" . $wsfunctionname;
$curl = new curl;
$restformat = ($restformat == 'json')?'&moodlewsrestformat=' . $restformat:'';
$resp = $curl->post($serverurl . $restformat, $params);
print_r($resp);
}
function getUserDetails()
{
$firstname = "TestUser";
$lastname = "TestUser";
$email = "TestUser@zzz.gr";
$city = "Thessaloniki";
$country = "EL";
$description= "ZZZ";
//assign username
//get first two letters of name and surname
//$strlength_user = strlen($firstname);
//$strlength_pass = strlen($lastname);
$rest_firstname = substr($firstname, 0, 2);
$rest_lastname = substr($lastname, 0, 2);
$part1 = $rest_firstname . $rest_lastname;
$part1 = strtolower($part1);
//echo"<br/>part1 = $part1";
$dt = getCDate();
$part2 = substr($dt, -4);
//echo"<br/>part2 = $part2";
$username = $part1 . "." . $part2;
echo"<br/>Username = $username";
//assign password
$password = randomPassword();
echo"<br/>Password = $password";
//call WS core_user_create_user of moodle to store the new user
$domainname = 'http://www.yoursite.eu';
$wstoken = 'ed1f6d3ebadg372f95f28cd96bd43zzz'; //here paste your create user token
$wsfunctionname = 'core_user_create_users';
//REST return value
$restformat = 'xml';
//parameters
$user1 = new stdClass();
$user1->username = $username;
$user1->password = $password;
$user1->firstname = $firstname;
$user1->lastname = $lastname;
$user1->email = $email;
$user1->auth = 'manual';
$user1->idnumber = 'numberID';
$user1->lang = 'en';
$user1->city = $city;
$user1->country = $country;
$user1->description = $description;
$users = array($user1);
$params = array('users' => $users);
//REST call
header('Content-Type: text/plain');
$serverurl = $domainname . "/webservice/rest/server.php?wstoken=" . $wstoken . "&wsfunction=" . $wsfunctionname;
$curl = new curl;
$restformat = ($restformat == 'json')?'&moodlewsrestformat=' . $restformat:'';
$resp = $curl->post($serverurl . $restformat, $params);
print_r($resp);\
//get id from $resp
$xml_tree = new SimpleXMLElement($resp);
print_r($xml_tree);
$value = $xml_tree->MULTIPLE->SINGLE->KEY->VALUE;
$user_id = intval(sprintf("%s",$value));
echo"<br/>user_id number = $user_id";
//enrol_manual_enrol_users
//for($i = 64; $i < 70; $i++) //where 64,65,66,67,68,69 are the six ids of the six courses of phase 1
for($i = 64; $i < 65; $i++)
{
echo "\nThe user has been successfully enrolled to course " . $i;
$course_id = $i;
enrol($user_id, $course_id);
}
}
getUserDetails();
?>
</body>
</html>
最佳答案
这是从 mrcinv/moodle_api.py 中提取的示例显示了 Python 的 requests
用于访问 Moodle Web 服务 API 的用法:
from requests import get, post
# Module variables to connect to moodle api
KEY = "SECRET API KEY"
URL = "https://moodle.site.com"
ENDPOINT="/webservice/rest/server.php"
def rest_api_parameters(in_args, prefix='', out_dict=None):
"""Transform dictionary/array structure to a flat dictionary, with key names
defining the structure.
Example usage:
>>> rest_api_parameters({'courses':[{'id':1,'name': 'course1'}]})
{'courses[0][id]':1,
'courses[0][name]':'course1'}
"""
if out_dict==None:
out_dict = {}
if not type(in_args) in (list,dict):
out_dict[prefix] = in_args
return out_dict
if prefix == '':
prefix = prefix + '{0}'
else:
prefix = prefix + '[{0}]'
if type(in_args)==list:
for idx, item in enumerate(in_args):
rest_api_parameters(item, prefix.format(idx), out_dict)
elif type(in_args)==dict:
for key, item in in_args.items():
rest_api_parameters(item, prefix.format(key), out_dict)
return out_dict
def call(fname, **kwargs):
"""Calls moodle API function with function name fname and keyword arguments.
Example:
>>> call_mdl_function('core_course_update_courses',
courses = [{'id': 1, 'fullname': 'My favorite course'}])
"""
parameters = rest_api_parameters(kwargs)
parameters.update({"wstoken": KEY, 'moodlewsrestformat': 'json', "wsfunction": fname})
response = post(URL+ENDPOINT, parameters).json()
if type(response) == dict and response.get('exception'):
raise SystemError("Error calling Moodle API\n", response)
return response
class CourseList():
"""Class for list of all courses in Moodle and order them by id and idnumber."""
def __init__(self):
# TODO fullname atribute is filtered
# (no <span class="multilang" lang="sl">)
courses_data = call('core_course_get_courses')
self.courses = []
for data in courses_data:
self.courses.append(Course(**data))
self.id_dict = {}
self.idnumber_dict = {}
for course in self.courses:
self.id_dict[course.id] = course
if course.idnumber:
self.idnumber_dict[course.idnumber] = course
def __getitem__(self, key):
if 0<= key < len(self.courses):
return self.courses[key]
else:
raise IndexError
def by_id(self, id):
"Return course with given id."
return self.id_dict.get(id)
def by_idnumber(self, idnumber):
"Course with given idnumber"
return self.idnumber_dict.get(idnumber)
def update_courses(courses_to_update, fields):
"Update a list of courses in one go."
if not ('id' in fields):
fields.append('id')
courses = [{k: c.__dict__[k] for k in fields} for c in courses_to_update]
return call("core_course_update_courses",
courses = courses)
.. 还展示了如何为类(class)定义自定义类。以同样的方式,可以为用户、成绩等创建类。
此外,PyPi 上还有一些包装器模块,例如moodle , 和 moodle-ws-client .
关于python - 通过 Python 的请求库访问 Moodle 服务器的 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53161278/
我正在为 Moodle 开发自定义登录应用程序。 我只想知道Moodle用什么算法来加密密码?这样,我就可以在我的登录应用程序上对 Moodle 用户进行身份验证。 最佳答案 这取决于 Moodle
Moodle的日历可以显示用户自己的所有事件。 我想要这样的功能:我是 Moodle 网站的网络管理员,我想获取所有事件,详细说明用户的所有事件。 如何在 Moodle 的日历上获取用户的所有事件?
我为 guest 打开了测验,获得了查看、预览尝试测验的权限,但 guest 使用仍然无法运行测试。那么为什么在测验级别为 guest 提到了权限。 最佳答案 没有。测验模块明确检查以确保用户已登录。
我想在 Moodle 3.1.7 注册后禁用用户修改他们的电子邮件帐户 我试过没有运气https://moodle.org/mod/forum/discuss.php?d=169041 最佳答案 作为
我想要一个更好的工作流程来调试上传的 SCO。事实上,我必须在事件中编辑一个文件,重新打包、上传和测试。通常,我只需要更改一行代码。如果能够在服务器上编辑那个文件,那行代码,那就太好了。到目前为止,我
来自Moodle doc : A context is a space in Moodle where roles can be assigned. 据我所知,上下文是用于管理 Moodle 对象的逻
我想要一个更好的工作流程来调试上传的 SCO。事实上,我必须在事件中编辑一个文件,重新打包、上传和测试。通常,我只需要更改一行代码。如果能够在服务器上编辑那个文件,那行代码,那就太好了。到目前为止,我
我是 Moodle 新手。我的客户需要一些特殊的注册表格。我想知道如何更改通过 Moodle 仪表板创建的注册表单的代码? 最佳答案 选项 1(针对开发人员)。创建您自己的身份验证插件 https:/
我在使用 Moodle 表单实现 Moodle 上传机制时遇到了一些困难。我的目标是让用户/管理员上传图像、存储它们并稍后在 block 中访问。 目前,我的形式是这样的: $mform->addEl
我已经检查了 mod/quiz/db/services.php ,但找不到相同的 API。 注意:测验数据,如问题、答案详情。 最佳答案 是的,如果您使用的是 moodle 网络服务,则可以使用 mo
我创建了一个自定义页面,其中显示所有可用类(class)。我还上传了类(class)的图像,现在想要显示类(class)的名称和图像。我可以从数据库中获取类(class)名称,但如何获取图像。 最佳答
我想从 moodle 函数或数据库查询中列出我的类(class)部分中的模块(事件)的名称。 我可以从 mdl_course_sections 和 mdl_course_modules 表中获取部分详
我想从 moodle 函数或数据库查询中列出我的类(class)部分中的模块(事件)的名称。 我可以从 mdl_course_sections 和 mdl_course_modules 表中获取部分详
所以我想像 moodleApp 这样用 flutter 构建移动应用程序,这样应用程序就可以从现有的 moodle web 中获取 api,那么,moodle是否提供了可以自由使用的API呢?还是其他
我已经为我的网站构建了 moodle 移动定制应用程序。我成功地在浏览器中运行了该应用程序。 Command cordova serve 但是当我为 android 构建这个应用程序时,它卡在屏幕上“
我希望在每个 Moodle 类(class)中包含指向外部站点的 URL。我想将用户 ID 和类(class) ID 作为 URL 中的 GET 参数传递给其他站点。 moodle 中是否有将替换为
我被要求创建一个引擎,该引擎将从我们的本地数据库中获取类(class)(名称、简称、类别)并将其添加到moodle。 我正在考虑为此使用 Moodle API。 我尝试使用网络服务但没有运气。 我需要
我正在尝试通过 Keycloak 服务改进 Moodle 登录。 我在本地实例上安装了这个插件( https://moodle.org/plugins/auth_oidc ),安装后我开始编译所有字段
如何识别在 Moodle 中完全阅读/查看特定类(class)的所有类(class)的用户? 我创建了一门类(class)并注册了 3 个用户,创建的类(class)有 10 个主题,每个主题都包含一
我正在两个系统之间进行集成,从我的系统 PHP 中,我必须在 Moodle 上添加一个用户,在特定类(class)上添加此用户后,我已经知道 Moodle 上的类(class) ID,我不知道如何做和
我是一名优秀的程序员,十分优秀!