Esempio n. 1
0
 def download_asset(self, size=None):
     e = HTTPOk()
     data, meta_data = self.assets_manager.load(self.filename, size)
     e.body = data
     e.content_type = str(meta_data["content-type"])
     e.title = meta_data["filename"]
     # e.headers['Cache-Control'] = 'max-age=0, must-revalidate, no-cache, no-store'
     raise e
Esempio n. 2
0
 def download_asset(self, size=None):
     e = HTTPOk()
     data, meta_data = self.assets_manager.load(self.filename, size)
     e.body = data
     e.content_type = str(meta_data['content-type'])
     e.title = meta_data['filename']
     #e.headers['Cache-Control'] = 'max-age=0, must-revalidate, no-cache, no-store'
     raise e
def init_portal_idea(self, url, comp, *args):
    r_feed = comp.render(rss.RssRenderer(), model='published_ideas')
    r_feed = r_feed.write_xmlstring()
    e = HTTPOk(headerlist=[('Content-Type', '')])
    e.body = '<?xml version="1.0" encoding="UTF-8"?>\n' + r_feed

    e.content_type = 'application/xml'

    raise e
Esempio n. 4
0
    def get_qnet_progress(self, request, suffix=''):
        """The user progress checking handler"""
        abs_path = self.qnet_domain + self.qnet_progress
        # check absolute path and used element
        if abs_path != '' and self.qnet_element != '':
            # try to request
            try:
                url = self._format_api_url(abs_path)
                response = self._request_get(url)
            except Exception as e:
                return HTTPServerError(body="GET Qnet progress error: %s" %
                                       str(e))

            # parse progress
            progress = self._convert_progress(response['progress'])
            self.is_done = progress['is_done']
            self.score = progress['score']

            # grade
            if self.is_done:
                self.runtime.publish(self, 'grade', {
                    'value': self.score,
                    'max_value': self.weight
                })

            # return result
            return HTTPOk(headers={'Content-Type': 'application/json'},
                          body=json.dumps({
                              'is_done': self.is_done,
                              'score': self.score,
                              'max_score': self.weight
                          }))

        else:
            return HTTPServerError(body="Bad request to the Qnet platform")
Esempio n. 5
0
 def get_grades_data(self, data, suffix=''):
     assert self._is_staff()
     grades_objects = StudentModule.objects.filter(
         module_state_key=self.location)
     grades = [[
         'id', 'username', 'score', 'max_grade', 'state', 'created',
         'modified'
     ]]
     for grade in grades_objects:
         grades.append([
             grade.id,
             grade.student.username if grade.student is not None else None,
             grade.grade,
             grade.max_grade,
             grade.state,
             grade.created,
             grade.modified,
         ])
     return HTTPOk(body="\n".join([
         "\t".join(["" if j is None else str(j) for j in i]) for i in grades
     ]),
                   headers={
                       'Content-Disposition':
                       'attachment; filename=grades_%s.tsv' %
                       self.scope_ids.usage_id.block_id,
                       'Content-Type':
                       'text/tab-separated-values'
                   })
Esempio n. 6
0
 def get_tasks_data(self, data, suffix=''):
     assert self._is_staff()
     grader_tasks = GraderTask.objects.filter(module_id=self.location)
     tasks = [[
         'id', 'task_id', 'student_input', 'grader_payload',
         'system_payload', 'task_input', 'task_output', 'course_id',
         'module_id', 'user_target.username', 'task_type', 'task_state'
     ]]
     for task in grader_tasks:
         tasks.append([
             task.id,
             task.task_id,
             task.student_input,
             task.grader_payload,
             task.system_payload,
             task.task_input,
             task.task_output,
             task.course_id,
             task.module_id,
             task.user_target.username
             if task.user_target is not None else None,
             task.task_type,
             task.task_state,
         ])
     return HTTPOk(body="\n".join([
         "\t".join(["" if j is None else str(j) for j in i]) for i in tasks
     ]),
                   headers={
                       'Content-Disposition':
                       'attachment; filename=tasks_%s.tsv' %
                       self.scope_ids.usage_id.block_id,
                       'Content-Type':
                       'text/tab-separated-values'
                   })
 def get_grades_data(self, data, suffix=''):
     assert self._is_staff()
     grades_objects = StudentModule.objects.filter(module_state_key=self.location)
     grades = [['id', 'username', 'score', 'max_grade', 'state', 'created', 'modified']]
     for grade in grades_objects:
         try:
             history = json.loads(grade.state).get('history')
             has_history = True
         except Exception:
             history = None
             has_history = False
         grades.append([
             grade.id,
             grade.student.username if grade.student is not None else None,
             self._get_points(history)*self.weight if has_history else None,
             self.weight,
             grade.state,
             grade.created,
             grade.modified,
         ])
     return HTTPOk(
         body="\n".join(["\t".join(["" if j is None else str(j) for j in i]) for i in grades]),
         headers={
             'Content-Disposition': 'attachment; filename=grades_%s.tsv' % self.scope_ids.usage_id.block_id,
             'Content-Type': 'text/tab-separated-values'
         })
def init_portal_xml_published_ideas(self, url, comp, http_method, request):
    root = comp.render(xml.Renderer(), model='xml_published_ideas')
    # Now we need to fix the avatar urls because we can't pass the request object to the component
    # render function (or did I missed something ?)
    for node in root.xpath('//avatar'):
        node.text = request.application_url + node.text
    raise HTTPOk(content_type='application/xml', body=root.write_xmlstring(
        xml_declaration=True, encoding='UTF-8'))
Esempio n. 9
0
    def wrapped( topology_params, function_params, ssh = None, response = None, *args, **kwargs ):

        response                    	= HTTPOk()
        response.information_message    = ''
        response.execution              = { 
                                           HAS_BEEN_EXECUTED 	: False, 
                                           STEPS		: [],
                                          }
        response.next                  	= {}
        response.datas                  = []
        response.accepted_commands      = []
        response.is_ok                  = False

	if len( topology_params.aera ) != 2:

            remote_server_name          	= '%s-%s-%s-%s-%s' % (
                topology_params.appcode,
                topology_params.env,
                topology_params.appcomp,
                topology_params.num_component,
                topology_params.aera
            )

	else:

            remote_server_name          	= '%s-%s-%s-%s%s' % (
                topology_params.appcode,
                topology_params.env,
                topology_params.aera,
                topology_params.appcomp,
                topology_params.num_component
            )

        try:

            f( 
                topology_params, 
                function_params, 
                connect( remote_server_name ),
                response, 
                *args, 
                **kwargs 
            )

        except NetworkError, e:
            # abnormal exit
            app_e = HTTPServiceUnavailable()
            app_e.information_message = e.message
            raise app_e
Esempio n. 10
0
    def get_qnet_status(self, request, suffix=''):
        """The lab status checking handler"""
        abs_path = self.qnet_domain + self.qnet_status
        # check absolute path and used element
        if abs_path != '' and self.qnet_element != '':
            # try to request
            try:
                url = self._format_api_url(abs_path)
                response = self._request_get(url)
            except Exception as e:
                return HTTPServerError(body="GET Qnet status error: %s" %
                                       str(e))

            # return result
            return HTTPOk(headers={'Content-Type': 'application/json'},
                          body=json.dumps(response['wstatus']))

        else:
            return HTTPServerError(body="Bad request to the Qnet platform")
Esempio n. 11
0
from webob.exc import HTTPOk

__docformat__ = 'reStructuredText en'
__all__ = [
    'DeleteMemberView',
]


class DeleteMemberView(ResourceView):
    """
    A View for processing DELETE requests

    The client sends a DELETE request to the URI of a Member Resource. If the
    deletion is successful, the server responds with a status code of 200.

    In a RESTful server DELETE does not always mean "delete a record from the
    database". See RESTful Web Services and REST in Practice books.

    See http://bitworking.org/projects/atom/rfc5023.html#delete-via-DELETE
    """
    def __call__(self):
        self._logger.debug('DELETE Request received on %s' % self.request.url)
        try:
            self.context.__parent__.remove(self.context)
        except Exception, err:  # catch Exception pylint: disable=W0703
            response = self._handle_unknown_exception(err.message,
                                                      get_traceback())
        else:
            response = self.request.get_response(HTTPOk())
        return response
Esempio n. 12
0
 def check_lab_external(self, request, suffix=''):
     return HTTPOk(json=self._check_lab(request.GET))
Esempio n. 13
0
def insure_is_xhr(env):
    if (env.request.method in ('GET', 'HEAD') and \
            not env.request.is_xhr and \
            '__ajax' not in env.request.GET):
        raise HTTPOk(body=env.render_to_string('layout.html', {}))