示例#1
0
 def getItem(self, item_id, viewName=None):
     """ Return all list items without further filtering """
     query0 = Element('ns1:query')
     query = Element('Query')
     query0.append(query)
     where = Element('Where')
     query.append(where)
     eq = Element('Eq')
     where.append(eq)
     fieldref = Element('FieldRef').append(
         Attribute('Name', self.primary_key))
     value = Element('Value').append(Attribute('Type',
                                               'Number')).setText(item_id)
     eq.append(fieldref)
     eq.append(value)
     viewfields = Element('ViewFields')
     viewfields.append(
         Element('FieldRef').append(Attribute('Name', self.primary_key)))
     queryOptions = Element('queryOptions')
     result = self.service.GetListItems(self.list_id,
                                        viewName=viewName or self.viewName,
                                        query=query0,
                                        viewFields=viewfields,
                                        queryOptions=queryOptions,
                                        rowLimit=1)
     if int(result.listitems.data._ItemCount) > 0:
         return self._serializeListItem(result.listitems.data.row)
     return []
示例#2
0
 def marshalled(self, context):
     # Fix wrong prefixes
     context.envelope.getChild('Body').setPrefix(
         context.envelope.prefix)  # Fix 'Body' node prefix
     sign_request_ns = context.envelope.findPrefix(
         'urn:oasis:names:tc:dss:1.0:core:schema')
     sapiws_ns = context.envelope.findPrefix(
         'http://arx.com/SAPIWS/DSS/1.0')
     context.envelope.getChild(
         'Body').getChild('DssSign').getChild('SignRequest').setPrefix(
             sign_request_ns)  # Fix 'SignRequest' node prefix
     context.envelope.getChild('Body').getChild('DssSign').getChild(
         'SignRequest').getChild('OptionalInputs').getChild(
             'SAPISigFieldSettings').setPrefix(
                 sapiws_ns)  # Fix 'SAPISigFieldSettings' node prefix
     context.envelope.getChild('Body').getChild('DssSign').getChild(
         'SignRequest').getChild(
             'OptionalInputs').getChild('ReturnPDFTailOnly').setPrefix(
                 sapiws_ns)  # Fix 'ReturnPDFTailOnly' node prefix
     # Add 'NameQualifier' attribute to the 'Name' node (e.g. <Name NameQualifier={domain}>...</Name>)
     name_node = context.envelope.getChild('Body').getChild(
         'DssSign').getChild('SignRequest').getChild(
             'OptionalInputs').getChild('ClaimedIdentity').getChild(
                 'Name')
     name_node.attributes.append(Attribute('NameQualifier', domain))
     # Add 'MimeType' attribute to the 'Base64Data' node (e.g. <Base64Data MimeType="application/pdf">...</Base64Data>)
     base64_data_node = context.envelope.getChild('Body').getChild(
         'DssSign').getChild('SignRequest').getChild(
             'InputDocuments').getChild('Document').getChild(
                 'Base64Data')
     base64_data_node.attributes.append(
         Attribute('MimeType', file_mime_type))
示例#3
0
    def create_headers(self):
        wssens = (
            'wsse',
            'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'
        )
        mustAttribute = Attribute('SOAP-ENV:mustUnderstand', '1')

        security = Element('Security', ns=wssens)
        security.append(mustAttribute)
        security.append(
            Attribute(
                'xmlns:wsse',
                'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'
            ))

        usernametoken = Element('UsernameToken', ns=wssens)

        username = Element('Username', ns=wssens).setText(self.merchantid)

        passwordType = Attribute(
            'Type',
            'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wssusername-token-profile-1.0#PasswordText'
        )
        password = Element('Password', ns=wssens).setText(self.password)
        password.append(passwordType)

        usernametoken.append(username)
        usernametoken.append(password)

        security.append(usernametoken)

        self.client.set_options(soapheaders=security)
示例#4
0
    def payuMeaGetTransactionApiCall(self, args):

        #urlToQuery = 'https://secure.payu.co.za/service/PayUAPI?wsdl'
        if (args['store']['environment'] == 'staging'):
            urlToQuery = 'https://staging.payu.co.za/service/PayUAPI?wsdl'
        else:
            urlToQuery = 'https://secure.payu.co.za/service/PayUAPI?wsdl'
        plugin = MyPlugin()
        client = Client(urlToQuery, plugins=[plugin])
        #client = Client(urlToQuery, faults=False)
        #------------------------------------- CREATING CUSTOM HEADER--------------------------------------
        wsse = (
            'wsse',
            'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'
        )

        mustAttributeSecurity = Attribute('SOAP-ENV:mustUnderstand', '1')
        addressAttributeSecurity = Attribute(
            'xmlns:wsse',
            'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'
        )
        AttributeUsernameToken1 = Attribute('wsu:Id', 'UsernameToken-9')
        addressAttributeUsernameToken = Attribute(
            'xmlns:wsu',
            'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd'
        )
        addressAttributePassword = Attribute(
            'Type',
            'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText'
        )

        msgUsername = Element('Username',
                              ns=wsse).setText(args['store']['soapUsername'])
        msgPassword = Element('Password', ns=wsse).setText(
            args['store']['soapPassword']).append(addressAttributePassword)

        msgUsernameToken = Element('UsernameToken', ns=wsse)
        msgUsernameToken.append(AttributeUsernameToken1)
        msgUsernameToken.append(addressAttributeUsernameToken)
        msgUsernameToken.insert(msgPassword).insert(msgUsername)

        msgSecurity = Element('Security', ns=wsse).addPrefix(
            p='SOAP-ENC', u='http://www.w3.org/2003/05/soap-encoding')
        msgSecurity.append(mustAttributeSecurity)
        msgSecurity.append(addressAttributeSecurity)
        msgSecurity.insert(msgUsernameToken)

        client.set_options(soapheaders=[msgSecurity])

        #------------------------------------- CREATING SOAP CALL DETAILS HERE--------------------------------------
        transaction = {}
        transaction['Api'] = 'ONE_ZERO'
        transaction['Safekey'] = args['store']['safekey']
        transaction['AdditionalInformation'] = args['additionalInformation']
        #------------------------------------- DOING SOAP CALL HERE--------------------------------------
        try:
            setTransaction = client.service.getTransaction(**transaction)
        except Exception, e:
            print_exc()
示例#5
0
def login():
    """Defines the security header required by the SOAP server.

    Before making any call to an OSCAR service, you must run set_options(soapheaders=[login()])
        on that service object. This authenticates us using a username and password.

    Returns:
        a SOAP element object representing a wsse:Security header element

    Raises:
        ConnectionRefusedError: When the connection is refused (usually a firewall problem)
        Exception: All other uncaught errors

    """
    try:
        loginService = Client("%s/%s/ws/LoginService?wsdl" % (HOST, INSTANCE))
        result = loginService.service.login(USER, PASS)

        security = Element('wsse:Security')
        security.attributes.append(
            Attribute(
                'xmlns:wsse',
                'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'
            ))
        auth = Element('wsse:UsernameToken')
        auth.attributes.append(
            Attribute(
                'xmlns:wsu',
                'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd'
            ))
        auth.attributes.append(Attribute('wsu:Id', 'UsernameToken-1'))
        auth.append(Element('wsse:Username').setText(result["securityId"]))
        pw = Element('wsse:Password').setText(result["securityTokenKey"])
        pw.attributes.append(
            Attribute(
                'Type',
                'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText'
            ))
        auth.append(pw)
        security.append(auth)

        return security

    except WebFault as we:
        raise ConnectionRefusedError(
            "There was a problem connecting to OSCAR when logging in. Server status: "
            + test_alive())
    except Exception as e:
        log.exception(e)
        raise
示例#6
0
文件: element.py 项目: USGM/suds
 def set(self, name, value):
     """
     Set an attribute's value.
     @param name: The name of the attribute.
     @type name: basestring
     @param value: The attribute value.
     @type value: basestring
     @see: __setitem__()
     """
     attr = self.getAttribute(name)
     if attr is None:
         attr = Attribute(name, value)
         self.append(attr)
     else:
         attr.setValue(value)
示例#7
0
 def set(self, name, value):
     """
     Set an attribute's value.
     @param name: The name of the attribute.
     @type name: basestring
     @param value: The attribute value.
     @type value: basestring
     @see: __setitem__()
     """
     attr = self.getAttribute(name)
     if attr is None:
         attr = Attribute(name, value)
         self.append(attr)
     else:
         attr.setValue(value)
示例#8
0
def singin(request):
    if request.session.get('email', False):
        return HttpResponseRedirect('/profile_')

    if request.method == 'POST':
        email = request.POST.get('email')
        password = request.POST.get('password')
        client = Client('http://www.universus-webservice.ru/WebService1.asmx?WSDL')
        auth = Element("AuthHeader").append((
            Element('Email').setText(email),
            Element('Password').setText(password),
            Attribute('xmlns', 'http://universus-webservice.ru/'))
        )
        client.set_options(soapheaders=auth)
        id = client.service.getId()
        if (id > 0):
            account = client.service.getAccount()
            request.session['id'] = id
            request.session['email'] = email
            request.session['password'] = password
            request.session['role_id'] = account.RoleId
            return HttpResponseRedirect('/profile_')
        else:
            return render(request, 'singin/singin.html', {'result': False})
    return render(request, 'singin/singin.html', {'result': True})
示例#9
0
def my_groups(request):
    client = Client('http://www.universus-webservice.ru/WebService1.asmx?WSDL')
    auth = Element("AuthHeader").append(
        (Element('Email').setText(request.session.get('email', '')),
         Element('Password').setText(request.session.get('password', '')),
         Attribute('xmlns', 'http://universus-webservice.ru/')))
    client.set_options(soapheaders=auth)
    account = client.service.getAccount()
    groups = []
    if account.RoleId == 1:  # if student
        groups = client.service.getAllGroupsByStudentId(account.Id)
    if account.RoleId == 2:  # if teacher
        groups = client.service.getAllGroupsByTeacherId(account.Id)
    data = []
    dept = []
    uni = []
    if groups:
        if len(groups.StudentGroup) == 1:
            return HttpResponseRedirect('/studentgroup_body/show/' +
                                        str(groups.StudentGroup[0].Id) + '/')
        for group in groups.StudentGroup:
            d = client.service.getDepartmentByIdLite(group.DepartmentID)
            dept.append(d)
            uni.append(client.service.getUniversityByIdLite(d.UniversityId))
        data = zip(groups.StudentGroup, dept, uni)
    return render(request, 'student_group/group_list.html', {'data': data})
示例#10
0
    def __init__(self, **kwargs):
        '''
        Constructor
        '''
        self.kwargs = kwargs
        if 'client' in kwargs:
            self.client = kwargs['client']
        else:
            options = kwargs.get('client_options', {})
            try:
                self.client = suds.client.Client(**options)

                if 'integrationcode' in kwargs:
                    headerURL = AUTOTASK_API_SOAP_HEADER_URL
                    if 'apiversion' in kwargs and kwargs['apiversion'] == 1.6:
                        headerURL = AUTOTASK_API_V1_6_SOAP_HEADER_URL
                    integrationCode = Element("AutotaskIntegrations") \
                        .append(Attribute('xmlns', headerURL)) \
                        .append(Element('IntegrationCode').setText( kwargs['integrationcode']))
                    self.client.set_options(soapheaders=integrationCode)
            except SAXParseException as err:
                # ATWS does not report welformed SOAP responses on authentication failures,
                # so a parseexception at this point is most likely an auth failure
                raise ATWSAuthException(
                    "AutoTask webservice call failed due to authentication or privilege settings"
                )
示例#11
0
def show_profile(request):
    if request.session.get('id', False):
        client = Client(
            'http://www.universus-webservice.ru/WebService1.asmx?WSDL')
        auth = Element("AuthHeader").append(
            (Element('Email').setText(request.session.get('email', '')),
             Element('Password').setText(request.session.get('password', '')),
             Attribute('xmlns', 'http://universus-webservice.ru/')))
        client.set_options(soapheaders=auth)

        account = client.service.getAccount()

        if request.method == 'POST':
            data = request.body.decode('utf-8')
            acc = json.loads(data)
            account.Name = acc['name']
            account.Surname = acc['surname']
            account.Patronymic = acc['patronymic']
            account.Address = acc['address']
            account.Phone = acc['phone']
            account.BirthDay = acc['birth_day']
            res = client.service.updateAccount(account)
            print(res)
        department = client.service.getDepartmentByIdLite(account.DepartmentId)
        university = client.service.getUniversityByIdLite(
            department.UniversityId)
        role = getRoleById(account.RoleId)
    return render(
        request, 'user_profile/user_profile.html', {
            'account': account,
            'role': role,
            'university': university,
            'department': department
        })
示例#12
0
def university(request, university_id):
    client = Client('http://www.universus-webservice.ru/WebService1.asmx?WSDL')
    auth = Element("AuthHeader").append((
        Element('Email').setText(request.session.get('email', '')),
        Element('Password').setText(request.session.get('password', '')),
        Attribute('xmlns', 'http://universus-webservice.ru/'))
    )
    client.set_options(soapheaders=auth)
    if request.method == 'POST':
        data = request.body.decode('utf-8')
        uni = json.loads(data)
        univer = client.service.getUniversityByIdLite(university_id)
        univer.FullName = uni['FullName']
        univer.ShortName = uni['ShortName']
        univer.Description = uni['Description']
        univer.Address = uni['Address']
        univer.WebSite = uni['WebSite']
        result = client.service.updateUniversity(univer)
    university = client.service.getUniversityById(int(university_id))
    departments = client.service.getAllDepartmentsByUniversityIdLite(int(university_id))
    role_id = request.session.get('role_id', 0)
    return render(request, 'university/university.html', {
        'university': university,
        'departments': departments.Department if departments else None,
        'role_id': role_id})
示例#13
0
def university_add(request):
    if request.method == 'POST':
        cloudinary.config(
            cloud_name="universusimages",
            api_key="421689719673152",
            api_secret="E3pIIQne8HbWnxnJiyNm9NFGCxY"
        )
        client = Client('http://www.universus-webservice.ru/WebService1.asmx?WSDL')
        University = client.factory.create('University')
        auth = Element("AuthHeader").append((
            Element('Email').setText(request.session.get('email', '')),
        Element('Password').setText(request.session.get('password', '')),
        Attribute('xmlns', 'http://universus-webservice.ru/'))
        )
        client.set_options(soapheaders=auth)
        University['Id'] = 0;
        University['FullName'] = request.POST.get('full_name')
        University['ShortName'] = request.POST.get('short_name')
        University['Address'] = request.POST.get('address')
        University['WebSite'] = request.POST.get('web_site')
        University['Description'] = request.POST.get('description', '')
        logo_url = cloudinary.uploader.upload(
              request.FILES['logo'].read(),
              crop = 'fit',
              width = 500,
              height = 500
        )['url']
        University['LogoURL'] = logo_url
        client.service.addUniversity(University)
        return render(request, 'university/university_add.html', {'added' : True})
    return render(request, 'university/university_add.html', locals())


# ,eager=[{"width": 400, "height": 300, "crop": "fit"}]
示例#14
0
    def sign(self):
        # Create the random nonce every time
        m = hashlib.md5()
        m.update(str(random.random()))
        self._nonce=m.hexdigest()
        # define the time
        self._created=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime(time.time()))
        # Hash the password
        digest=hashlib.new("sha1",self._nonce+self._created+self._passwordRaw).digest()
        self._password=binascii.b2a_base64(digest)[:-1]


        # create Security element
        securityElem = Element("Security",ns=("wsse", self.SEC_NS))
        securityElem.append(Attribute("SOAP-ENV:mustunderstand", "true"))

        # create UsernameToken elements
        usernameTokenElem = Element("UsernameToken",ns=("wsse", self.SEC_NS))
 
        #create Children of UsernameToken
        createdElem = Element("Created",ns=("wsu",self.UTIL_NS)).setText(self._created)
        usernameElem = Element("Username",ns=("wsse",self.SEC_NS)).setText(self._user)
        #password has already been fully processed
        passwordElem = Element("Password",ns=("wsse",self.SEC_NS)).setText(self._password).append(Attribute("Type",self.PASSWORD_DIGEST_TYPE))
        #base64 the nonce
        nonceElem = Element("Nonce",ns=("wsse",self.SEC_NS)).setText(binascii.b2a_base64(self._nonce)[:-1]).append(Attribute("EncodingType",self.NONCE_DIGEST_TYPE))
 
        # put it all together
        usernameTokenElem.append(usernameElem)
        usernameTokenElem.append(passwordElem)
        usernameTokenElem.append(nonceElem)
        usernameTokenElem.append(createdElem)
        securityElem.append(usernameTokenElem)
        return securityElem
示例#15
0
def set_test(request, group_id, exam_id):
    client = Client('http://www.universus-webservice.ru/WebService1.asmx?WSDL')
    auth = Element("AuthHeader").append(
        (Element('Email').setText(request.session.get('email', '')),
         Element('Password').setText(request.session.get('password', '')),
         Attribute('xmlns', 'http://universus-webservice.ru/')))
    client.set_options(soapheaders=auth)
    group = client.service.getStudentGroupByIdLite(int(group_id))
    exam = client.service.getExamById(int(exam_id))
    if request.method == 'POST':
        exam_history = client.factory.create('ExamHistory')
        exam_history.Id = 0
        exam_history.ExamId = int(exam_id)
        exam_history.Exam = None
        exam_history.TeacherId = request.session.get('id', 0)
        exam_history.StatusId = 1
        exam_history.Result = 0
        exam_history.DateOfTest = '1970-01-01'
        exam_history.PassingScore = int(request.POST['passing_score']) / 100
        deadline = datetime.strptime(request.POST['deadline_date'], "%Y-%m-%d")
        time = datetime.strptime(request.POST['deadline_time'], "%H:%M")
        # deadline.replace(hour=time.hour, minute=time.minute)
        exam_history.Deadline = deadline.strftime("%Y-%m-%d")
        students = client.service.getAllStudentsByGroupId(int(group_id))
        res = 0
        if students:
            for student in students.Account:
                exam_history.StudentId = student.Id
                res += client.service.addExamHistory(exam_history)
    return render(request, 'exam_builder/set_test.html', {
        'exam': exam,
        'group': group
    })
示例#16
0
def exam_buider(request):
    if request.method == 'POST':
        data = request.body.decode('utf-8')
        exam = json.loads(data)
        client = Client(
            'http://www.universus-webservice.ru/WebService1.asmx?WSDL')
        auth = Element("AuthHeader").append(
            (Element('Email').setText(request.session.get('email', '')),
             Element('Password').setText(request.session.get('password', '')),
             Attribute('xmlns', 'http://universus-webservice.ru/')))
        client.set_options(soapheaders=auth)

        exm = client.factory.create('Exam')
        exm.Id = 0
        exm.Title = exam['title']
        exm.Description = exam['description']
        exm.AuthorId = client.service.getId()
        exm.CountOfQuestion = len(exam['tests'])
        exm.Content = json.dumps(exam['tests'])
        res = client.service.addExam(exm)
        response = {
            'status': res,
            'message':
            'Сохранено ' + datetime.strftime(datetime.now(), '%H:%M:%S')
        }
        return HttpResponse(json.dumps(response),
                            content_type='application/json')
    return render(request, 'exam_builder/exam_builder.html', locals())
示例#17
0
def department(request, department_id):
    client = Client('http://www.universus-webservice.ru/WebService1.asmx?WSDL')
    auth = Element("AuthHeader").append(
        (Element('Email').setText(request.session.get('email', '')),
         Element('Password').setText(request.session.get('password', '')),
         Attribute('xmlns', 'http://universus-webservice.ru/')))
    client.set_options(soapheaders=auth)
    if request.method == 'POST':
        data = request.body.decode('utf-8')
        dept = json.loads(data)
        depart = client.service.getDepartmentById(department_id)
        depart.Name = dept['name']
        depart.Description = dept['description']
        depart.DeanName = dept['dean_name']
        result = client.service.updateDepartment(depart)
    depart = client.service.getDepartmentById(int(department_id))
    groups = client.service.getAllStudentGroupByDepartmentIdLite(
        int(department_id))
    role_id = request.session.get('role_id', 0)
    return render(
        request, "department/department.html", {
            'department': depart,
            'groups': groups.StudentGroup if groups else None,
            'role_id': role_id
        })
示例#18
0
 def deleteItems(self, *item_ids):
     """ Remove list items given by value of their primary key """
     batch = Element('Batch')
     batch.append(Attribute('OnError',
                            'Return')).append(Attribute('ListVersion', '1'))
     for i, item_id in enumerate(item_ids):
         method = Element('Method')
         method.append(Attribute('ID', str(i + 1))).append(
             Attribute('Cmd', 'Delete'))
         method.append(
             Element('Field').append(Attribute(
                 'Name', self.primary_key)).setText(item_id))
         batch.append(method)
     updates = Element('ns0:updates')
     updates.append(batch)
     result = self.service.UpdateListItems(self.list_id, updates)
     return ParsedSoapResult(result)
示例#19
0
 def fix_any_type_string(self, element):
     """Used as a filter function with walk in order to fix errors.
     If the element has a certain name, give it a xsi:type=xsd:int. Note that the nsprefix xsd
     must also be added in to make this work."""
     # Fix elements which have these names
     fix_names = ['DataItemValue']
     if element.name in fix_names:
         type_and_value = element.text.split('_')
         element.attributes.append(Attribute('xsi:type', type_and_value[0]))
         element.setText(type_and_value[1])
示例#20
0
文件: utils.py 项目: vashc/Schematron
 def marshalled(self, context):
     context.envelope.nsprefixes = {
         's': 'http://www.w3.org/2003/05/soap-envelope',
         'a': 'http://www.w3.org/2005/08/addressing'
     }
     context.envelope[1].setPrefix('s')
     context.envelope[1][0].setPrefix(None)
     context.envelope[1][0].append(Attribute('xmlns', self.xmlns))
     context.envelope[1][0][0].setPrefix(None)
     context.envelope[1][0][1].setPrefix(None)
示例#21
0
 def updateItems(self, *update_items):
     """ Update list items as given through a list of update_item dicts
         holding the data to be updated. The list items are identified
         through the value of the primary key inside the update dict.
     """
     batch = Element('Batch')
     batch.append(Attribute('OnError',
                            'Return')).append(Attribute('ListVersion', '1'))
     for i, d in enumerate(update_items):
         self._preflight(d)
         method = Element('Method')
         method.append(Attribute('ID', str(i + 1))).append(
             Attribute('Cmd', 'Update'))
         for k, v in d.items():
             method.append(
                 Element('Field').append(Attribute('Name', k)).setText(v))
         batch.append(method)
     updates = Element('ns0:updates')
     updates.append(batch)
     result = self.service.UpdateListItems(self.list_id, updates)
     return ParsedSoapResult(result)
示例#22
0
 def startElement(self, name, attrs):
     top = self.top()
     node = Element(unicode(name), parent=top)
     for a in attrs.getNames():
         n = unicode(a)
         v = unicode(attrs.getValue(a))
         attribute = Attribute(n, v)
         if self.mapPrefix(node, attribute):
             continue
         node.append(attribute)
     top.append(node)
     self.push(node)
示例#23
0
def leave_group(request, group_id):
    client = Client('http://www.universus-webservice.ru/WebService1.asmx?WSDL')
    auth = Element("AuthHeader").append(
        (Element('Email').setText(request.session.get('email', '')),
         Element('Password').setText(request.session.get('password', '')),
         Attribute('xmlns', 'http://universus-webservice.ru/')))
    client.set_options(soapheaders=auth)
    res = client.service.leaveStudentGroupById(int(group_id))
    if res > 0:
        return HttpResponseRedirect('/studentgroup_body/mygroups/')
    else:
        return HttpResponseRedirect('/studentgroup_body/show/' + group_id)
示例#24
0
 def addItems(self, *addable_items):
     """ Add a sequence of items to the list. All items must be passed as dict.
         The list of assigned primary key values should from the 'row' values of 
         the result object.
     """
     batch = Element('Batch')
     batch.append(Attribute('OnError',
                            'Return')).append(Attribute('ListVersion', '1'))
     for i, d in enumerate(addable_items):
         self._preflight(d, primary_key_check=False)
         method = Element('Method')
         method.append(Attribute('ID', str(i + 1))).append(
             Attribute('Cmd', 'New'))
         for k, v in d.items():
             method.append(
                 Element('Field').append(Attribute('Name', k)).setText(v))
         batch.append(method)
     updates = Element('ns0:updates')
     updates.append(batch)
     result = self.service.UpdateListItems(self.list_id, updates)
     return ParsedSoapResult(result)
示例#25
0
def delete_user_profile(request, account_id):
    client = Client('http://www.universus-webservice.ru/WebService1.asmx?WSDL')
    auth = Element("AuthHeader").append(
        (Element('Email').setText(request.session.get('email', '')),
         Element('Password').setText(request.session.get('password', '')),
         Attribute('xmlns', 'http://universus-webservice.ru/')))
    client.set_options(soapheaders=auth)
    acc = client.service.getAccountById(int(account_id))
    result = client.service.deleteAccountById(int(account_id))
    return render(request, 'user_profile/user_profile_delete.html', {
        'result': result,
        'profile': acc
    })
示例#26
0
def exam_show(request, exam_id):
    client = Client('http://www.universus-webservice.ru/WebService1.asmx?WSDL')
    auth = Element("AuthHeader").append(
        (Element('Email').setText(request.session.get('email', '')),
         Element('Password').setText(request.session.get('password', '')),
         Attribute('xmlns', 'http://universus-webservice.ru/')))
    client.set_options(soapheaders=auth)
    exam = client.service.getExamById(int(exam_id))
    tests = json.loads(exam.Content)
    return render(request, 'exam_builder/exam_show.html', {
        'exam': exam,
        'tests': tests
    })
示例#27
0
def university_delete(request, university_id):
    client = Client('http://www.universus-webservice.ru/WebService1.asmx?WSDL')
    auth = Element("AuthHeader").append((
        Element('Email').setText(request.session.get('email', '')),
        Element('Password').setText(request.session.get('password', '')),
        Attribute('xmlns', 'http://universus-webservice.ru/'))
    )
    client.set_options(soapheaders=auth)
    uni = client.service.getUniversityByIdLite(university_id)
    result = client.service.deleteUniversityById(university_id)
    return render(request, 'university/university_delete.html',
                  {'result': result,
                   'university': uni})
示例#28
0
 def startElement(self, name, attrs):
     top = self.top()
     node = Element(str(name))
     for a in attrs.getNames():
         n = str(a)
         v = str(attrs.getValue(a))
         attribute = Attribute(n, v)
         if self.mapPrefix(node, attribute):
             continue
         node.append(attribute)
     node.charbuffer = []
     top.append(node)
     self.push(node)
示例#29
0
def add_user_profile(request):
    client = Client('http://www.universus-webservice.ru/WebService1.asmx?WSDL')
    auth = Element("AuthHeader").append(
        (Element('Email').setText(request.session.get('email', '')),
         Element('Password').setText(request.session.get('password', '')),
         Attribute('xmlns', 'http://universus-webservice.ru/')))
    client.set_options(soapheaders=auth)

    if request.method == 'POST':
        account = client.factory.create('Account')
        account.Id = 0
        account.Name = request.POST['name']
        account.Surname = request.POST['surname']
        account.Patronymic = request.POST['patronymic'] if request.POST[
            'patronymic'] else ' '
        account.Address = request.POST['address'] if request.POST[
            'address'] else 'не задан'
        account.Email = request.POST['email']
        account.Phone = request.POST['phone'] if request.POST[
            'phone'] else 'не задан'
        account.PasswordMD5 = request.POST['password']
        account.DepartmentId = request.POST['department']
        account.BirthDay = request.POST['birth_day']
        account.RoleId = int(request.POST['role'])

        if request.FILES and request.FILES['photo']:
            cloudinary.config(cloud_name="universusimages",
                              api_key="421689719673152",
                              api_secret="E3pIIQne8HbWnxnJiyNm9NFGCxY")
            account.PhotoURL = cloudinary.uploader.upload(
                request.FILES['photo'].read(),
                crop='fit',
                width=700,
                height=700)['url']
        else:
            account.PhotoURL = 'http://res.cloudinary.com/universusimages/image/upload/v1523119802/default.png'

        id = 0
        if account.RoleId == 1:
            id = client.service.addStudent(account)
        elif account.RoleId == 2:
            id = client.service.addTeacher(account)
        if id > 0:
            return HttpResponseRedirect('/profile_body/show/' + str(id))

    uni = client.service.getAllUniversitiesLite()
    role_id = request.session.get('role_id', 0)
    return render(request, 'user_profile/add_profile.html', {
        'universities': uni.University if uni else [],
        'role_id': role_id
    })
示例#30
0
def added_teacher_to_group(request, group_id, teacher_id):
    client = Client('http://www.universus-webservice.ru/WebService1.asmx?WSDL')
    auth = Element("AuthHeader").append(
        (Element('Email').setText(request.session.get('email', '')),
         Element('Password').setText(request.session.get('password', '')),
         Attribute('xmlns', 'http://universus-webservice.ru/')))
    client.set_options(soapheaders=auth)
    group = client.service.getStudentGroupById(int(group_id))
    account = client.service.getAccountById(int(teacher_id))
    result = client.service.addTeacherToGroup(int(teacher_id), int(group_id))
    return render(request, 'student_group/added_teacher.html', {
        'group': group,
        'account': account,
        'result': result
    })
示例#31
0
def my_dialogs(request):
    client = Client('http://www.universus-webservice.ru/WebService1.asmx?WSDL')
    auth = Element("AuthHeader").append(
        (Element('Email').setText(request.session.get('email', '')),
         Element('Password').setText(request.session.get('password', '')),
         Attribute('xmlns', 'http://universus-webservice.ru/')))
    client.set_options(soapheaders=auth)
    dialogs = client.service.getDialogs()
    countMsgs = []
    lastMsgs = []
    data = []
    if dialogs:
        for account in dialogs.Account:
            countMsgs.append(client.service.getCountNewMessages(account.Id))
            lastMsgs.append(client.service.getLastMessage(account.Id))
        data = zip(dialogs.Account, countMsgs, lastMsgs)
    return render(request, 'chat/my_dialogs.html', {'dialogs': data})