Exemplo n.º 1
0
    def PUT_model_row(self):
        data = self.data
        query = self.query
        db = self.db
        urlbits = self.urlbits
        
        if urlbits[-2] != '~' and urlbits[-1] != '~':
            query.setdefault(urlbits[-2], []).insert(0, urlbits[-1])

        where = {}
        for k in query.keys():
            if k and k[0] != '_':
                where[k] = query.pop(k)
        if where:
            where = db._op_expand_where(where, op_mode=self.op_mode)
        if not where:
            raise RestyError('you must give the where')

        if type(data) is list:
            data = data[0]

        if type(data) is not dict:
            raise RestyError('data <%s> must be dict or 1 item list'%json_encode(data))

        _test = False
        if '_test' in query:
            _test = query.pop('_test')[0]

        data = dict([(str(k),v) for k,v in data.items() if str(k)!='id'])
        
        if not data:
            raise RestyError('data is invalid')

        return db.update(self.model, where=where, _test=_test, **data)
Exemplo n.º 2
0
    def POST_model_row(self):
        data = self.data
        query = self.query

        if type(data) is dict:
            data = [data]

        if type(data) is not list:
            raise RestyError('data <%s> must be list or dict'%json_encode(data))

        _test = False
        if '_test' in query:
            _test = query.pop('_test')[0]
        
        data_ = []
        for idx, d in enumerate(data):
            d = dict([(str(k),v) for k,v in d.items()])
            
            if 'id' in d:
                del d['id']
            if d:
                data_.append(d)
        del data
        
        if not data_:
            raise RestyError('data is invalid')

        return self.db.multiple_insert(self.model, data_, seqname='id', _test=_test)
Exemplo n.º 3
0
def suggest(self):
    for_women = (self.GET[u'for'] == u'True')
    data = Exercise.objects.all()

    data = filter(lambda x: self.GET['term'].lower() in x.title.lower(), data)

    for i in data:
        print (repr(i) + ' - ' + repr(i.for_women))
    data = filter(lambda x: x.for_women == for_women, data)
    data = map(lambda x: {'label': x.title, 'id': x.id, 'value': x.title}, data)
    return HttpResponse(content=json_encode(data), mimetype='application/x-javascript')
Exemplo n.º 4
0
 def call(self, api_operation, api_request):
     try:
         API_OPERATIONS.index(api_operation)
     except ValueError:
         raise RuntimeError("Invalid API operation.")
     url = "%s/%s" % (self._endpoint, api_operation)
     req = http_request(url)
     json_request = json_encode(api_request)
     try:
         response = urlopen(req, json_request)
     except URLError:
         raise RuntimeError("API request failed.")
     return json_decode(response.read())
Exemplo n.º 5
0
def task_ss_save(request):
    logging.error(request.POST)
    number = request.POST.get(u'number')
    task_id = request.POST.get(u'task_id')
    logging.error(number)
    logging.error(task_id)

    task = Task.objects.get(id=int(task_id))
    task.super_set_number = number
    task.save()

    sleep(0.5)

    return HttpResponse(content=json_encode({'res': 'OK'}), mimetype='application/x-javascript')
Exemplo n.º 6
0
def init_default_filters():
    from hashlib import md5
    from base64 import b64encode, b64decode
    from simplejson import dumps as json_encode, loads as json_decode
    add_filter('md5', lambda v: md5(v).hexdigest())
    add_filter('md5b', lambda v: md5(v).digest())
    add_filter('b64e', lambda v: b64encode(v))
    add_filter('b64d', lambda v: b64decode(v))
    add_filter('jsone', lambda v: json_encode(v))
    add_filter('jsond', lambda v: json_decode(v))
    add_filter('len', lambda v: len(v))

    _to_num = lambda v: (float(v) if '.' in v else int(v)) if isinstance(v, basestring) else v
    add_filter('add', lambda v, arg: _to_num(v) + _to_num(arg))
Exemplo n.º 7
0
def task_reorder(request):
    logging.error(request.POST)
    order_f = request.POST.get(u'order')
    logging.error(order_f)

    pos = 1
    for i in order_f.split('+'):
        task_id = int(i[len('task_id_'):])
        logging.error(task_id)

        task = Task.objects.get(id=task_id)
        if Task:
            task.order = pos
            task.save()
        pos += 1

    sleep(1)

    return HttpResponse(content=json_encode({'res': 'OK'}), mimetype='application/x-javascript')
Exemplo n.º 8
0
    def _http_resource(self, method, resource, params=None, data=None):
        """Makes an HTTP request."""

        if not is_collection(resource):
            resource = [resource]

        # This is needed because we only send application/json
        data = json_encode(data)

        url = self._url_for(*resource)
        r = self._session.request(method, url, params=params, data=data)

        if r.status_code == 422:
            http_error = HTTPError("%s Client Error: %s" % (r.status_code, r.content))
            http_error.response = r
            raise http_error

        r.raise_for_status()
        return r
Exemplo n.º 9
0
    def _http_resource(self, method, resource, params=None, data=None):
        """Makes an HTTP request."""

        if not is_collection(resource):
            resource = [resource]

        # This is needed because we only send application/json
        data = json_encode(data)

        url = self._url_for(*resource)
        r = self._session.request(method, url, params=params, data=data)

        if r.status_code == 422:
            http_error = HTTPError('%s Client Error: %s' %
                                   (r.status_code, r.content))
            http_error.response = r
            raise http_error

        r.raise_for_status()
        return r
Exemplo n.º 10
0
    def build_payload(self):
        # Just to avoid circular dependencies
        import silota as _s
        payload = {'topics': [], 'selectors': []}
        payload['selectors'] = [x for x in self.selectors]
        payload['selectors'].append('#console  .form-search  .search-box  .search-query')
        for topic in self.topics:
            d = {'id': topic.id, 'name': topic.name}
            d['fields'] = [x for x in topic.schema]
            d['templates'] = {}
            d['templates']['suggest'] = topic.templates.suggest
            payload['topics'].append(d)

        url_args = urllib.quote(json_encode(payload))
        url = '%s/jsc/%d.js?%s' % (_s.config.search_uri,
                                   self.id, url_args)
        r = self._h._session.get(url)

        r.raise_for_status()
        return r.content
Exemplo n.º 11
0
    def build_payload(self):
        # Just to avoid circular dependencies
        import silota as _s
        payload = {'topics': [], 'selectors': []}
        payload['selectors'] = [x for x in self.selectors]
        payload['selectors'].append(
            '#console  .form-search  .search-box  .search-query')
        for topic in self.topics:
            d = {'id': topic.id, 'name': topic.name}
            d['fields'] = [x for x in topic.schema]
            d['templates'] = {}
            d['templates']['suggest'] = topic.templates.suggest
            d['value_key'] = topic.value_key
            payload['topics'].append(d)

        url_args = urllib.quote(json_encode(payload))
        url = '%s/jsc/%d.js?%s' % (_s.config.search_uri, self.id, url_args)
        r = self._h._session.get(url)

        r.raise_for_status()
        return r.content
Exemplo n.º 12
0
    def build_payload(self):
        # Just to avoid circular dependencies
        import silota as _s

        payload = {"topics": [], "selectors": []}
        payload["selectors"] = [x for x in self.selectors]
        payload["selectors"].append("#console  .form-search  .search-box  .search-query")
        for topic in self.topics:
            d = {"id": topic.id, "name": topic.name}
            d["fields"] = [x for x in topic.schema]
            d["templates"] = {}
            d["templates"]["suggest"] = topic.templates.suggest
            d["value_key"] = topic.value_key
            payload["topics"].append(d)

        url_args = urllib.quote(json_encode(payload))
        url = "%s/jsc/%d.js?%s" % (_s.config.search_uri, self.id, url_args)
        r = self._h._session.get(url)

        r.raise_for_status()
        return r.content
Exemplo n.º 13
0
    def run(self):
        upload = {"version": version}
        text = ""

        # Collect hardware information
        if not w.pageHardwareInfoDlg.hardwareInfoBox.isChecked():

            def readProcFile(file, label):
                for i in open(file).readlines():
                    if i.startswith(label):
                        return i.split(":")[1].strip()

            text += i18n("Collecting hardware information...")
            w.pageUploadDlg.labelStatus.setText(text)

            upload["hw"] = {}
            upload["hw"]["memtotal"] = readProcFile("/proc/meminfo", "MemTotal").split()[0]
            upload["hw"]["swaptotal"] = readProcFile("/proc/meminfo", "SwapTotal").split()[0]
            upload["hw"]["cpu_model"] = readProcFile("/proc/cpuinfo", "model name")
            upload["hw"]["cpu_speed"] = readProcFile("/proc/cpuinfo", "cpu MHz")
            upload["hw"]["kernel"] = open("/proc/version").read().split()[2]

            text += i18n("<font color=\"#008800\">Done</font><br>\n")
            w.pageUploadDlg.labelStatus.setText(text)

        # Upload data to dev. center
        text += i18n("Uploading data...")
        w.pageUploadDlg.labelStatus.setText(text)

        # Experience
        upload['experience'] = 0
        if w.pageExperienceDlg.questionOne.isChecked():
            upload['experience'] = 1
        elif w.pageExperienceDlg.questionTwo.isChecked():
            upload['experience'] = 2
        elif w.pageExperienceDlg.questionThree.isChecked():
            upload['experience'] = 3
        elif w.pageExperienceDlg.questionFour.isChecked():
            upload['experience'] = 4

        # Purpose
        upload['purpose'] = 0
        if w.pagePurposeDlg.checkBoxDaily.isChecked():
            upload['purpose'] += 1
        if w.pagePurposeDlg.checkBoxHobby.isChecked():
            upload['purpose'] += 2
        if w.pagePurposeDlg.checkBoxInt.isChecked():
            upload['purpose'] += 4
        if w.pagePurposeDlg.checkBoxBus.isChecked():
            upload['purpose'] += 8
        if w.pagePurposeDlg.checkBoxEnt.isChecked():
            upload['purpose'] += 16
        if w.pagePurposeDlg.checkBoxEdu.isChecked():
            upload['purpose'] += 32

        # Usage
        upload['use_where'] = 0
        if w.pageUsageDlg.usagecheckBoxOne.isChecked():
            upload['use_where'] += 1
        if w.pageUsageDlg.usagecheckBoxTwo.isChecked():
            upload['use_where'] += 2
        if w.pageUsageDlg.usagecheckBoxThree.isChecked():
            upload['use_where'] += 4

        # Question
        upload['question'] = 0
        if w.pageQuestionDlg.questionOne.isChecked():
            upload['question'] = 1
        elif w.pageQuestionDlg.questionTwo.isChecked():
            upload['question'] = 2
        elif w.pageQuestionDlg.questionThree.isChecked():
            upload['question'] = 3

        # Opinion
        upload['opinion'] = str(w.pageOpinionDlg.opinionEdit.text())

        # Personal
        upload['email'] = str(w.pagePersonalInfoDlg.lineEmail.text())
        upload['email_announce'] = w.pagePersonalInfoDlg.CheckBoxAnnounce.isChecked()

        # Encode dictionary
        upload = json_encode(upload)

        # Upload!
        try:
            params = urllib.urlencode({"data": upload})
            f = urllib.urlopen(url_upload, params)
            s = f.read()
        except:
            text += i18n("<font color=\"#ff0000\">Failed</font><br>\n")
            text += i18n("<font color=\"#ff0000\">Unable to connect feedback database.</font><br>\n")
            w.pageUploadDlg.labelStatus.setText(text)
            w.pageUploadDlg.buttonRetry.show()
            return

        if s == "0":
            text += i18n("<font color=\"#008800\">Done</font><br>\n")
            w.pageUploadDlg.labelStatus.setText(text)
            w.setNextEnabled(w.pageUploadDlg, 1)
        else:
            text += i18n("<font color=\"#ff0000\">Failed</font><br>\n")

            if s == "1":
                text += i18n("<font color=\"#ff0000\">Feedback seems to be broken. Data is corrupted.</font><br>\n")
            elif s == "2":
                text += i18n("<font color=\"#ff0000\">Server does not support this version. Please update feedback tool.</font><br>\n")
            elif s == "3":
                text += i18n("<font color=\"#ff0000\">Feedback seems to be broken. Data is missing.</font><br>\n")
            elif s == "4":
                text += i18n("<font color=\"#ff0000\">Feedback database is offline.</font><br>\n")
            elif s == "5":
                text += i18n("<font color=\"#ff0000\">You've already sent feedback.</font><br>\n")
            else:
                text += i18n("<font color=\"#ff0000\">Feedback database has errors.</font><br>\n")

            w.pageUploadDlg.labelStatus.setText(text)
            w.pageUploadDlg.buttonRetry.show()
Exemplo n.º 14
0
Arquivo: doc.py Projeto: lstn/eppy
    cmd = EppCreateDomainCommand()
    cmd.name = 'hello.me'
    cmd.ns = dict(hostObj=['ns1.acme.com', 'ns2.acme.com'])
    cmd.contact = [{'@type': 'admin', '_text': 'wil001a'}]
    cmd.authInfo = dict(pw='fooBAR')

    #print "handcrafted = ", json_encode(cmd)
    xml = cmd.to_xml()
    print xml

    root = ElementTree.parse(StringIO(xml)).getroot()
    cmd2 = xml2dict(root,
                    outerclass=EppCreateDomainCommand,
                    default_prefix="epp")
    print repr(cmd2)
    print json_encode(cmd2)

    print "domain = ", cmd2.name

    print "again back to XML="
    print cmd2.to_xml()

    sys.exit(0)
    cmd = {
        'epp:create': {
            #'{urn:ietf:params:xml:ns:domain-1.0}create': {
            'domain:create': {
                '_order':
                ['name', 'period', 'ns', 'registrant', 'contact', 'authInfo'],
                #'@xmlns:domain': 'urn:ietf:params:xml:ns:domain-1.0',
                'name':
Exemplo n.º 15
0
	def encode(cls, data, charset=None, mimetype=None):
		return json_encode(data)
Exemplo n.º 16
0
def run_app(
    api=None,
    dict=dict,
    sys=sys,
    API_HANDLERS=API_HANDLERS,
    DEVNULL=DEVNULL,
    ERROR=ERROR,
    ERROR_HEADER=ERROR_HEADER,
    NOTFOUND=NOTFOUND,
    ):
    """The core application runner."""

    env = dict(os.environ)
    kwargs = {}

    sys._boot_stdout = sys.stdout
    sys.stdout = DEVNULL
    write = sys._boot_stdout.write

    try:

        http_method = env['REQUEST_METHOD']
        content_type = env.get('CONTENT-TYPE', '')

        args = [arg for arg in env['PATH_INFO'].split('/') if arg]
        if args:
            api = args[0]

        # return a NotFoundError if it doesn't look like a valid api call
        if (http_method != 'POST') or (api not in API_HANDLERS):
            write(ERROR_HEADER)
            write(NOTFOUND)
            return

        # force the request to be over SSL when on a production deployment
        if RUNNING_ON_GOOGLE_SERVERS and env.get('HTTPS') not in SSL_FLAGS:
            write(ERROR_HEADER)
            write(NOTAUTHORISED)
            return

        # we assume that the request is utf-8 encoded, but that the request
        # kwarg "keys" are in ascii and the kwarg values to be in utf-8
        if ';' in content_type:
            content_type = content_type.split(';', 1)[0]

        # parse the POST body if it exists and is of a known content type
        if content_type in VALID_REQUEST_CONTENT_TYPES:

            post_environ = env.copy()
            post_environ['QUERY_STRING'] = ''

            post_data = FieldStorage(
                environ=post_environ, fp=env['wsgi.input']
                ).list

            if post_data:
                for field in post_data:
                    key = field.name
                    if field.filename:
                        continue
                    if key not in API_REQUEST_KEYS:
                        continue
                    value = unicode(field.value, UTF8, 'strict')
                    kwargs[key] = value

        # check that there's a token and it validates
        if 0: # @/@
            signature = kwargs.pop('sig', None)
            if not signature:
                write(ERROR_HEADER)
                write(NOTAUTHORISED)
                return
            if not validate_tamper_proof_string(
                'token', token, key=API_KEY, timestamped=True
                ):
                logging.info("Unauthorised API Access Attempt: %r", token)
                write(UNAUTH)
                return

        handler, store_needed = api_definition

        # check if the datastore and memcache services are available
        if store_needed:
            disabled = None
            if not CapabilitySet('datastore_v3', capabilities=['write']).is_enabled():
                disabled = 'datastore'
            elif not CapabilitySet('memcache', methods=['set']).is_enabled():
                disabled = 'memcache'
            if disabled:
                write(ERROR_HEADER)
                write(DISABLED % disabled)
                return

        try:
            # try and respond with the result of calling the api handler
            args = tuple(args)
            result = handler(*args, **kwargs)
            if result:
                write(OK_HEADER)
                write(json_encode(result))
            else:
                write(ERROR)
        except Exception, error:
            # log the error and return it as json
            logging.error(''.join(format_exception(*sys.exc_info())))
            write(ERROR_HEADER)
            write(json_encode({
                "error": error.__class__.__name__,
                "error_msg": str(error)
                }))

    except:
        # this shouldn't ever happen, but just in case...
        logging.critical(''.join(format_exception(*sys.exc_info())))
        write(ERROR_HEADER)
        write(json_encode({
            "error": error.__class__.__name__,
            "error_msg": str(error)
            }))

    finally:
        sys.stdout = sys._boot_stdout