sample-post.py 2.43 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
# A simple script demonstrating how to have an external program post problem
# responses to an edx server.
#
# ***** NOTE *****
# This is not intended as a stable public API.  In fact, it is almost certainly
# going to change.  If you use this for some reason, be prepared to change your
# code.
#
# We will be working to define a stable public API for external programs.  We
# don't have have one yet (Feb 2013).

12 13 14

import requests
import sys
15
import getpass
16

17
def prompt(msg, default=None, safe=False):
18
    d = ' [{0}]'.format(default) if default is not None else ''
19 20 21 22 23 24
    prompt = 'Enter {msg}{default}: '.format(msg=msg, default=d)
    if not safe:
        print prompt
        x = sys.stdin.readline().strip()
    else:
        x = getpass.getpass(prompt=prompt)
25 26 27 28
    if x == '' and default is not None:
        return default
    return x

29 30 31
server = 'https://www.edx.org'
course_id = 'HarvardX/PH207x/2012_Fall'
location = 'i4x://HarvardX/PH207x/problem/ex_practice_2'
32

33 34 35
#server = prompt('Server (no trailing slash)',  'http://127.0.0.1:8000')
#course_id = prompt('Course id', 'MITx/7012x/2013_Spring')
#location = prompt('problem location', 'i4x://MITx/7012x/problem/example_upload_answer')
36 37
value = prompt('value to upload')

38 39 40 41
username = prompt('username on server', 'victor@edx.org')
password = prompt('password', 'abc123', safe=True)

print "get csrf cookie"
42
session = requests.Session()
43 44
r = session.get(server + '/')
r.raise_for_status()
45 46

# print session.cookies
47 48 49 50

# for some reason, the server expects a header containing the csrf cookie, not just the
# cookie itself.
session.headers['X-CSRFToken'] = session.cookies['csrftoken']
51 52
# for https, need a referer header
session.headers['Referer'] = server + '/'
53 54
login_url = '/'.join([server, 'login'])

55 56 57 58
print "log in"
r = session.post(login_url, {'email': 'victor@edx.org', 'password': 'Secret!', 'remember': 'false'})
#print "request headers: ", r.request.headers
#print "response headers: ", r.headers
59 60 61 62 63 64 65 66 67 68
r.raise_for_status()

url = '/'.join([server, 'courses', course_id, 'modx', location, 'problem_check'])
data = {'input_{0}_2_1'.format(location.replace('/','-').replace(':','').replace('--','-')): value}
#data = {'input_i4x-MITx-7012x-problem-example_upload_answer_2_1': value}

print "Posting to '{0}': {1}".format(url, data)

r = session.post(url, data)
r.raise_for_status()
69 70 71

print ("To see the uploaded answer, go to {server}/courses/{course_id}/jump_to/{location}"
       .format(server=server, course_id=course_id, location=location))