Exemple #1
0
def get_extended_fb_token(access_token):
    # print access_token
    payload = {'client_id': FB_CLIENT_ID, 'client_secret': FB_CLIENT_SECRET, 'grant_type': 'fb_exchange_token', 'fb_exchange_token': access_token}
    r = requests.get("https://graph.facebook.com/oauth/access_token", params=payload)
    try:
        access_token = url_decode(r.text).get('access_token')
    except Exception as e:
        print '(WARNING) Failed to parse retrieve long-lived access token', r.text
    print 'EXPIRES: ' + url_decode(r.text).get('expires')
    return access_token
Exemple #2
0
def test_url_decoding():
    """Test the URL decoding"""
    x = url_decode('foo=42&bar=23&uni=H%C3%A4nsel')
    assert x['foo'] == '42'
    assert x['bar'] == '23'
    assert x['uni'] == u'Hänsel'

    x = url_decode('foo=42;bar=23;uni=H%C3%A4nsel', separator=';')
    assert x['foo'] == '42'
    assert x['bar'] == '23'
    assert x['uni'] == u'Hänsel'

    x = url_decode('%C3%9Ch=H%C3%A4nsel', decode_keys=True)
    assert x[u'Üh'] == u'Hänsel'
Exemple #3
0
def test_url_decoding():
    """Test the URL decoding"""
    x = url_decode('foo=42&bar=23&uni=H%C3%A4nsel')
    assert x['foo'] == '42'
    assert x['bar'] == '23'
    assert x['uni'] == u'Hänsel'

    x = url_decode('foo=42;bar=23;uni=H%C3%A4nsel', separator=';')
    assert x['foo'] == '42'
    assert x['bar'] == '23'
    assert x['uni'] == u'Hänsel'

    x = url_decode('%C3%9Ch=H%C3%A4nsel', decode_keys=True)
    assert x[u'Üh'] == u'Hänsel'
Exemple #4
0
def url_add(url=None, **kwargs):
    scheme, netloc, path, query, fragments = urlsplit(url or request.url)
    params = url_decode(query)
    for key, value in kwargs.items():
        if value not in params.getlist(key):
            params.add(key, value)
    return Markup(urlunsplit((scheme, netloc, path, url_encode(params), fragments)))
Exemple #5
0
    def __call__(self, rev, contenttype=None, arguments=None):
        item_name = rev.item.name
        query_keys = {'do': 'get', 'rev': rev.revid}
        attrib = {}
        if arguments:
            query = arguments.keyword.get(xinclude.href)
            if query and query.query:
                # query.query value is similar to  "w=75" given a transclusion "{{jpeg||&w=75 class="top"}}"
                query_keys.update(url_decode(query.query))
            attrib = arguments.keyword

        query = url_encode(query_keys, charset=CHARSET, encode_keys=True)

        attrib.update({
            moin_page.type_:
            str(self.input_type),
            xlink.href:
            Iri(scheme='wiki',
                authority='',
                path='/' + rev.item.fqname.fullname,
                query=query),
        })

        obj = moin_page.object_(attrib=attrib, children=[
            item_name,
        ])
        body = moin_page.body(children=(obj, ))
        return moin_page.page(children=(body, ))
Exemple #6
0
def cse_demande():
    def mk_float(s):
        s = s.strip()
        return float(s) if s else 0

    data = url_decode(request.data)

    data['logement_gracieux'] = data['logement_gracieux'] == 'Oui'
    data['logement_montant'] = mk_float(data['logement_montant'])

    data['financement_famille'] = data['financement_famille'] == 'Oui'
    data['financement_famille_montant'] = mk_float(data['financement_famille_montant'])

    data['financement_autre'] = data['financement_autre'] == 'Oui'
    data['financement_autre_montant'] = mk_float(data['financement_autre_montant'])

    data['apl'] = data['apl'] == 'Oui'
    data['apl_montant'] = mk_float(data['apl_montant'])

    # data['boursier'] = data['boursier'] == 'Oui'
    data['boursier_montant'] = mk_float(data['boursier_montant'])

    print data.to_dict()
    demande = DossierCSE(**data.to_dict())
    demande.save()

    return jsonify(result='saved')
Exemple #7
0
def parse_response(resp, content, strict=False, content_type=None):
    """
    Parse the response returned by :meth:`OAuthRemoteApp.http_request`.
    """
    ct = resp.headers.get('content-type')
    if not ct and content.lower().strip().startswith('callback('):
        ct = 'application/json'
    if not ct:
        ct = content_type
    if not ct:
        ct = 'application/json'
    ct, options = parse_options_header(ct)

    if ct in ('application/json', 'text/javascript'):
        if content.lower().strip().startswith('callback('):
            content = content.strip().replace('callback(', '', 1).strip("); ")
        return json.loads(content)

    if ct in ('application/xml', 'text/xml'):
        return get_etree().fromstring(content)

    if ct != 'application/x-www-form-urlencoded' and strict:
        return content
    charset = options.get('charset', 'utf-8')
    return url_decode(content, charset=charset).to_dict()
Exemple #8
0
def url_add(url=None, **kwargs):
    scheme, netloc, path, query, fragments = urlsplit(url or request.url)
    params = url_decode(query)
    for key, value in kwargs.items():
        if not value in params.getlist(key):
            params.add(key, value)
    return Markup(urlunsplit((scheme, netloc, path, url_encode(params), fragments)))
Exemple #9
0
 def url_code(self, content):
     '''
     parse string, such as access_token=E8BF2BCAF63B7CE749796519F5C5D5EB&expires_in=7776000&refresh_token=30AF0BD336324575029492BD2D1E134B.
     return data, such as {'access_token': 'E8BF2BCAF63B7CE749796519F5C5D5EB', 'expires_in': '7776000', 'refresh_token': '30AF0BD336324575029492BD2D1E134B'}
     '''
     return url_decode(
         content, charset=self._encoding).to_dict() if content else None
 def report_download(self, data, token):
     response = super(OpenedunavDownloadController,
                      self).report_download(data, token)
     # if we got another content disposition before, ditch the one added
     # by super()
     requestcontent = json.loads(data)
     url, type = requestcontent[0], requestcontent[1]
     try:
         if type == 'qweb-pdf':
             reportname = url.split('/report/pdf/')[1].split('?')[0]
             docids = None
             if '/' in reportname:
                 reportname, docids = reportname.split('/')
             if not docids:
                 cr, uid = request.cr, request.uid
                 report = request.registry['report']._get_report_from_name(
                     cr, uid, reportname)
                 data = dict(url_decode(url.split('?')[1]).items())
                 data = json.loads(data.pop('options'))
                 response.headers[
                     'Content-Disposition'] = content_disposition(
                         data['download_name'])
                 return response
     except Exception as e:
         exc_info = sys.exc_info()
         se = traceback.format_exception(*exc_info)
         error = {'code': 200, 'message': "Odoo Server Error", 'data': se}
         return request.make_response(html_escape(json.dumps(error)))
     return response
Exemple #11
0
 def __call__(self, environ, start_response):
     if 'METHOD_OVERRIDE' in environ.get('QUERY_STRING', ''):
         args = url_decode(environ['QUERY_STRING'])
         method = args.get('__METHOD_OVERRIDE__')
         if method:
             environ['REQUEST_METHOD'] = method
     return self.app(environ, start_response)
Exemple #12
0
    def __call__(self, environ, start_response):
        if '_method' in environ.get('QUERY_STRING', ''):
            args = url_decode(environ['QUERY_STRING'])
            method = args.get('_method')
            if method:
                method = method.encode('ascii', 'replace')
                environ['REQUEST_METHOD'] = method
        return self.app(environ, start_response)

# class MethodRewriteMiddleware(object):
#     """Legacy Browser and HTTP REST Methods Support
#     For HTML form use:
#     <input type="hidden" name="_method" value="OPTIONS" />
#     """
#     HTTP_METHODS = ['GET', 'POST', 'PUT', 'DELETE',
#                     'HEAD', 'OPTIONS',
#                     'TRACE', 'CONNECT']

#     def __init__(self, app, input_name='_method'):
#         self.app = app
#         self.input_name = input_name

#     def __call__(self, environ, start_response):
#         request = Request(environ)

        if self.input_name in request.form:
            method = request.form[self.input_name].upper()

            if method in self.HTTP_METHODS:
                environ['REQUEST_METHOD'] = method

        return self.app(environ, start_response)
Exemple #13
0
    def report_download(self, data, token):
        """This function is used by 'qwebactionmanager.js' in order to trigger the download of
        a pdf/controller report.

        :param data: a javascript array JSON.stringified containg report internal url ([0]) and
        type [1]
        :returns: Response with a filetoken cookie and an attachment header
        """
        requestcontent = simplejson.loads(data)
        url, type = requestcontent[0], requestcontent[1]
        try:
            if type == 'qweb-pdf':
                reportname = url.split('/report/pdf/')[1].split('?')[0]

                docids = None
                if '/' in reportname:
                    reportname, docids = reportname.split('/')

                attach_name = reportname
                if docids:
                    so_ids = [int(i) for i in docids.split(',')]
                    if reportname.find(
                            'cebis_sale_order_report.report_sale_order') != -1:
                        cr, uid, context = request.cr, request.uid, request.context
                        so = request.registry['sale.order'].browse(
                            cr, uid, so_ids, context=context)[0]
                        attach_name = so.name
                    # Generic report:
                    response = self.report_routes(reportname,
                                                  docids=docids,
                                                  converter='pdf')
                else:
                    # Particular report:
                    data = url_decode(
                        url.split('?')
                        [1]).items()  # decoding the args represented in JSON
                    response = self.report_routes(reportname,
                                                  converter='pdf',
                                                  **dict(data))

                response.headers.add(
                    'Content-Disposition',
                    'attachment; filename=%s.pdf;' % attach_name)
                response.set_cookie('fileToken', token)
                return response
            elif type == 'controller':
                reqheaders = Headers(request.httprequest.headers)
                response = Client(request.httprequest.app,
                                  BaseResponse).get(url,
                                                    headers=reqheaders,
                                                    follow_redirects=True)
                response.set_cookie('fileToken', token)
                return response
            else:
                return
        except Exception, e:
            se = _serialize_exception(e)
            error = {'code': 200, 'message': "Odoo Server Error", 'data': se}
            return request.make_response(html_escape(simplejson.dumps(error)))
Exemple #14
0
 def __call__(self, environ, start_response):
     if '__METHOD__' in environ.get('QUERY_STRING', ''):
         args = url_decode(environ['QUERY_STRING'])
         method = args.get('__METHOD__').upper()
         if method in ['GET', 'POST', 'PUT', 'DELETE']:
             method = method.encode('ascii', 'replace')
             environ['REQUEST_METHOD'] = method
     return self.app(environ, start_response)
Exemple #15
0
def in_url(*args, **kwargs):
    scheme, netloc, path, query, fragments = urlsplit(request.url)
    params = url_decode(query)
    return (
        all(arg in params for arg in args)
        and
        all(key in params and params[key] == value for key, value in kwargs.items())
    )
Exemple #16
0
Fichier : wsgi.py Projet : jkur/mmm
 def __call__(self, environ, start_response):
     if 'METHOD_OVERRIDE' in environ.get('QUERY_STRING', ''):
         args = url_decode(environ['QUERY_STRING'])
         method = args.get('__METHOD_OVERRIDE__')
         if method:
             method = method.encode('ascii', 'replace')
             environ['REQUEST_METHOD'] = method
     return self.app(environ, start_response)
Exemple #17
0
def in_url(*args, **kwargs):
    scheme, netloc, path, query, fragments = urlsplit(request.url)
    params = url_decode(query)
    return (
        all(arg in params for arg in args) and
        all(key in params and params[key] == value
            for key, value in kwargs.items())
    )
Exemple #18
0
def url_rewrite(url=None, **kwargs):
    scheme, netloc, path, query, fragments = urlsplit(url or request.url)
    params = url_decode(query)
    for key, value in kwargs.items():
        params.setlist(key,
                       value if isinstance(value, (list, tuple)) else [value])
    return Markup(urlunsplit((scheme, netloc, path, url_encode(params),
                  fragments)))
Exemple #19
0
 def __call__(self, environ, start_response):
     if 'METHOD_OVERRIDE' in environ.get('QUERY_STRING', ''):
         args = url_decode(environ['QUERY_STRING'])
         method = args.get('__METHOD_OVERRIDE__')
         if method in ['GET', 'POST', 'PUT', 'DELETE']:
             method = method.encode('ascii', 'replace')
             environ['REQUEST_METHOD'] = method
     return self.app(environ, start_response)
Exemple #20
0
 def __call__(self, environ, start_response):
     if "METHOD_OVERRIDE" in environ.get("QUERY_STRING", ""):
         args = url_decode(environ["QUERY_STRING"])
         method = args.get("__METHOD_OVERRIDE__")
         if method:
             method = method.encode("ascii", "replace")
             environ["REQUEST_METHOD"] = method.decode("ascii")
     return self.app(environ, start_response)
Exemple #21
0
 def url_equals(to_check):
     if to_check[:4] != check_parts[:4]:
         return False
     args = url_decode(to_check[4])
     for key, value in args.iteritems():
         if check_query.get(key) != value:
             return False
     return True
Exemple #22
0
 def url_equals(to_check):
     if to_check[:4] != check_parts[:4]:
         return False
     args = url_decode(to_check[4])
     for key, value in args.iteritems():
         if check_query.get(key) != value:
             return False
     return True
Exemple #23
0
 def __call__(self, environ, start_response):
     if self.input_name in environ.get('QUERY_STRING', ''):
         args = url_decode(environ['QUERY_STRING'])
         method = args.get(self.input_name).upper()
         if method and method in ['GET', 'POST', 'PUT', 'DELETE']:
             method = method.encode('ascii', 'replace')
             environ['REQUEST_METHOD'] = method
     return self.app(environ, start_response)
Exemple #24
0
 def __call__(self, environ, start_response):
     if 'method' in environ.get('QUERY_STRING', ''):
         args = url_decode(environ['QUERY_STRING'])
         method = args.get('method')
         if method:
             method = method.encode('ascii', 'replace')
             environ['REQUEST_METHOD'] = method
     return self.app(environ, start_response)
Exemple #25
0
def url_rewrite(url=None, **kwargs):
    scheme, netloc, path, query, fragments = urlsplit(url or request.url)
    params = url_decode(query)
    for key, value in kwargs.items():
        params.setlist(key, value if isinstance(value,
                                                (list, tuple)) else [value])
    return Markup(
        urlunsplit((scheme, netloc, path, url_encode(params), fragments)))
Exemple #26
0
 def __call__(self, environ, start_response):
     if "METHOD_OVERRIDE" in environ.get("QUERY_STRING", ""):
         args = url_decode(environ["QUERY_STRING"])
         method = args.get("__METHOD_OVERRIDE__")
         if method:
             method = method.encode("ascii", "replace")
             environ["REQUEST_METHOD"] = method
     return self.app(environ, start_response)
Exemple #27
0
    def report_download(self, data, token):
        """This function is used by 'qwebactionmanager.js' in order to trigger the download of
        a pdf/controller report.

        :param data: a javascript array JSON.stringified containg report internal url ([0]) and
        type [1]
        :returns: Response with a filetoken cookie and an attachment header
        """
        requestcontent = json.loads(data)
        url, type = requestcontent[0], requestcontent[1]
        try:
            if type == 'qweb-pdf':
                reportname = url.split('/report/pdf/')[1].split('?')[0]

                docids = None
                if '/' in reportname:
                    reportname, docids = reportname.split('/')

                if docids:
                    # Generic report:
                    response = self.report_routes(reportname,
                                                  docids=docids,
                                                  converter='pdf')
                else:
                    # Particular report:
                    data = url_decode(
                        url.split('?')
                        [1]).items()  # decoding the args represented in JSON
                    response = self.report_routes(reportname,
                                                  converter='pdf',
                                                  **dict(data))

                cr, uid = request.cr, request.uid
                report = request.registry['report']._get_report_from_name(
                    cr, uid, reportname)
                filename = "%s.%s" % (report.name, "pdf")
                response.headers.add('Content-Disposition',
                                     content_disposition(filename))
                response.set_cookie('fileToken', token)
                return response
            elif type == 'controller':
                reqheaders = Headers(request.httprequest.headers)
                response = Client(request.httprequest.app,
                                  BaseResponse).get(url,
                                                    headers=reqheaders,
                                                    follow_redirects=True)
                response.set_cookie('fileToken', token)
                return response
            else:
                return
        except Exception, e:
            se = _serialize_exception(e)
            error = {
                'code': 200,
                'message': "YuanCloud Server Error",
                'data': se
            }
            return request.make_response(html_escape(json.dumps(error)))
Exemple #28
0
    def get_redirect_target(self, invalid_targets=()):
        """Check the request and get the redirect target if possible.
        If not this function returns just `None`.  The return value of this
        function is suitable to be passed to `redirect`.
        """
        check_target = self.values.get('_redirect_target') or \
                       self.values.get('next') or \
                       self.referrer

        # if there is no information in either the form data
        # or the wsgi environment about a jump target we have
        # to use the target url
        if not check_target:
            return

        # otherwise drop the leading slash
        check_target = check_target.lstrip('/')

        root_url = self.url_root
        root_parts = urlparse(root_url)

        check_parts = urlparse(urljoin(root_url, check_target))
        check_query = url_decode(check_parts[4])

        def url_equals(to_check):
            if to_check[:4] != check_parts[:4]:
                return False
            args = url_decode(to_check[4])
            for key, value in args.iteritems():
                if check_query.get(key) != value:
                    return False
            return True

        # if the jump target is on a different server we probably have
        # a security problem and better try to use the target url.
        # except the host is whitelisted in the config
        if root_parts[:2] != check_parts[:2]:
            host = check_parts[1].split(':', 1)[0]
            for rule in settings.ALLOWED_REDIRECTS:
                if fnmatch(host, rule):
                    break
            else:
                return

        # if the jump url is the same url as the current url we've had
        # a bad redirect before and use the target url to not create a
        # infinite redirect.
        if url_equals(urlparse(self.url)):
            return

        # if the `check_target` is one of the invalid targets we also
        # fall back.
        for invalid in invalid_targets:
            if url_equals(urlparse(urljoin(root_url, invalid))):
                return

        return check_target
Exemple #29
0
    def get_redirect_target(self, invalid_targets=()):
        """Check the request and get the redirect target if possible.
        If not this function returns just `None`.  The return value of this
        function is suitable to be passed to `redirect`.
        """
        check_target = self.values.get('_redirect_target') or \
                       self.values.get('next') or \
                       self.referrer

        # if there is no information in either the form data
        # or the wsgi environment about a jump target we have
        # to use the target url
        if not check_target:
            return

        # otherwise drop the leading slash
        check_target = check_target.lstrip('/')

        root_url = self.url_root
        root_parts = urlparse(root_url)

        check_parts = urlparse(urljoin(root_url, check_target))
        check_query = url_decode(check_parts[4])

        def url_equals(to_check):
            if to_check[:4] != check_parts[:4]:
                return False
            args = url_decode(to_check[4])
            for key, value in args.iteritems():
                if check_query.get(key) != value:
                    return False
            return True

        # if the jump target is on a different server we probably have
        # a security problem and better try to use the target url.
        # except the host is whitelisted in the config
        if root_parts[:2] != check_parts[:2]:
            host = check_parts[1].split(':', 1)[0]
            for rule in settings.ALLOWED_REDIRECTS:
                if fnmatch(host, rule):
                    break
            else:
                return

        # if the jump url is the same url as the current url we've had
        # a bad redirect before and use the target url to not create a
        # infinite redirect.
        if url_equals(urlparse(self.url)):
            return

        # if the `check_target` is one of the invalid targets we also
        # fall back.
        for invalid in invalid_targets:
            if url_equals(urlparse(urljoin(root_url, invalid))):
                return

        return check_target
Exemple #30
0
def create_engine(uri, relative_to=None, debug=False):
    """Create a new engine.  This works a bit like SQLAlchemy's
    `create_engine` with the difference that it automaticaly set's MySQL
    engines to 'utf-8', and paths for SQLite are relative to the path
    provided as `relative_to`. Also hooks in LookLively to catch MySQL's
    weird way of connection termination without termination.

    Furthermore the engine is created with `convert_unicode` by default.
    """

    # This is a good idea in any case
    options = {'convert_unicode': True}

    # special case sqlite.  We want nicer urls for that one.
    if uri.startswith('sqlite:'):
        match = _sqlite_re.match(uri)
        if match is None:
            raise ArgumentError('Could not parse rfc1738 URL')
        database, query = match.groups()
        if database is None:
            database = ':memory:'
        elif relative_to is not None:
            database = path.join(relative_to, database)
        if query:
            query = url_decode(query).to_dict()
        else:
            query = {}
        info = URL('sqlite', database=database, query=query)

    else:
        info = make_url(uri)

        # if mysql is the database engine and no connection encoding is
        # provided we set it to utf-8
        if info.drivername == 'mysql':
            info.query.setdefault('charset', 'utf8')
            options['listeners'] = [LookLively()]


    # alternative pool sizes / recycle settings and more.  These are
    # interpreter wide and not from the config for the following reasons:
    #
    # - system administrators can set it independently from the webserver
    #   configuration via SetEnv and friends.
    # - this setting is deployment dependent should not affect a development
    #   server for the same instance or a development shell
    for key in 'pool_size', 'pool_recycle', 'pool_timeout':
        value = os.environ.get("PYCLANSPHERE_" + key.upper())
        if value is not None:
            options[key] = int(value)

    # if debugging is enabled, hook the ConnectionDebugProxy in
    if debug:
        options['proxy'] = ConnectionDebugProxy()

    return sqlalchemy.create_engine(info, **options)
Exemple #31
0
def insert_param_url_query_str(url_query_string, param_name, param_val):
    """
    Given an url query string this function:
    appends a new instance of param_name containing param_val (it doesn't remove existing ones)
    """
    if not param_name or not param_val:
        return url_query_string
    query_params = url_decode(url_query_string)
    query_params.update({param_name:param_val})
    return url_encode(query_params)
Exemple #32
0
def keep_query(*args, **kw):
    if not args and not kw:
        args = ('*',)
    params = kw.copy()
    query_params = frozenset(werkzeug.url_decode(request.httprequest.query_string).keys())
    for keep_param in args:
        for param in fnmatch.filter(query_params, keep_param):
            if param not in params and param in request.params:
                params[param] = request.params[param]
    return werkzeug.urls.url_encode(params)
Exemple #33
0
    def __call__(self, environ, start_response):
        if self.query_param in environ.get('QUERY_STRING', ''):
            args = url_decode(environ['QUERY_STRING'])
            method = args.get(self.query_param)

            if method and method in self.VALID_METHODS:
                method = method.encode('ascii', 'replace')
                environ['REQUEST_METHOD'] = method

        return self.app(environ, start_response)
Exemple #34
0
def keep_query(*args, **kw):
    if not args and not kw:
        args = ('*',)
    params = kw.copy()
    query_params = frozenset(werkzeug.url_decode(request.httprequest.query_string).keys())
    for keep_param in args:
        for param in fnmatch.filter(query_params, keep_param):
            if param not in params and param in request.params:
                params[param] = request.params[param]
    return werkzeug.urls.url_encode(params)
    def report_download(self, data, token):
        """This function is used by 'qwebactionmanager.js' in order to trigger the download of
        a pdf/controller report.

        :param data: a javascript array JSON.stringified containg report internal url ([0]) and
        type [1]
        :returns: Response with a filetoken cookie and an attachment header
        """
        requestcontent = simplejson.loads(data)
        url, type = requestcontent[0], requestcontent[1]
        try:
            if type == 'qweb-pdf':
                reportname = url.split('/report/pdf/')[1].split('?')[0]

                docids = None
                if '/' in reportname:
                    reportname, docids = reportname.split('/')

                if docids:
                    # Generic report:
                    response = super(Extension, self).report_routes(reportname, docids=docids, converter='pdf')
                    # response = self.report_routes(reportname, docids=docids, converter='pdf')
                    ##### FIX START: switch reportname with the evaluated attachment attribute of the action if available
                    docids = [int(i) for i in docids.split(',')]
                    report_obj = request.registry['report']
                    cr, uid, context = request.cr, request.uid, request.context
                    report = report_obj._get_report_from_name(cr, uid, reportname)
                    obj = report_obj.pool[report.model].browse(cr, uid, docids[0])
                    if hasattr(obj, 'name') and obj.name:
                        reportname = obj.name
                    ##### FIX END
                else:
                    # Particular report:
                    data = url_decode(url.split('?')[1]).items()  # decoding the args represented in JSON
                    response = super(Extension, self).report_routes(reportname, converter='pdf', **dict(data))
                    # response = self.report_routes(reportname, converter='pdf', **dict(data))

                response.headers.add('Content-Disposition', 'attachment; filename=%s.pdf;' % reportname)
                response.set_cookie('fileToken', token)
                return response
            elif type =='controller':
                reqheaders = Headers(request.httprequest.headers)
                response = Client(request.httprequest.app, BaseResponse).get(url, headers=reqheaders, follow_redirects=True)
                response.set_cookie('fileToken', token)
                return response
            else:
                return
        except Exception, e:
            se = _serialize_exception(e)
            error = {
                'code': 200,
                'message': "Odoo Server Error",
                'data': se
            }
            return request.make_response(html_escape(simplejson.dumps(error)))
Exemple #36
0
def url_del(url=None, *args, **kwargs):
    scheme, netloc, path, query, fragments = urlsplit(url or request.url)
    params = url_decode(query)
    for key in args:
        params.poplist(key)
    for key, value in kwargs.items():
        lst = params.poplist(key)
        if unicode(value) in lst:
            lst.remove(unicode(value))
        params.setlist(key, lst)
    return Markup(urlunsplit((scheme, netloc, path, url_encode(params), fragments)))
Exemple #37
0
def url_del(url=None, *args, **kwargs):
    scheme, netloc, path, query, fragments = urlsplit(url or request.url)
    params = url_decode(query)
    for key in args:
        params.poplist(key)
    for key, value in kwargs.items():
        lst = params.poplist(key)
        if value in lst:
            lst.remove(value)
        params.setlist(key, lst)
    return Markup(urlunsplit((scheme, netloc, path, url_encode(params), fragments)))
Exemple #38
0
def parse_response(resp, content, strict=False):
    ct, options = parse_options_header(resp['content-type'])
    if ct in ('application/json', 'text/javascript'):
        return json.loads(content)
    elif ct in ('application/xml', 'text/xml'):
        return get_etree().fromstring(content)
    elif ct != 'application/x-www-form-urlencoded':
        if strict:
            return content
    charset = options.get('charset', 'utf-8')
    return url_decode(content, charset=charset).to_dict()
Exemple #39
0
    def report_download(self, data, token):
        """This function is used by 'qwebactionmanager.js' in order to trigger the download of
        a pdf/controller report.

        :param data: a javascript array JSON.stringified containg report internal url ([0]) and
        type [1]
        :returns: Response with a filetoken cookie and an attachment header
        """
        requestcontent = simplejson.loads(data)
        url, type = requestcontent[0], requestcontent[1]
        try:
            if type == 'qweb-pdf':
                reportname = url.split('/report/pdf/')[1].split('?')[0]

                docids = None
                if '/' in reportname:
                    reportname, docids = reportname.split('/')

                if docids:
                    # Generic report:
                    response = self.report_routes(reportname, docids=docids, converter='pdf')
                else:
                    # Particular report:
                    data = url_decode(url.split('?')[1]).items()  # decoding the args represented in JSON
                    response = self.report_routes(reportname, converter='pdf', **dict(data))
                    
                cr, uid, context = request.cr, openerp.SUPERUSER_ID, request.context
                report_obj = request.registry['ir.actions.report.xml']
                idreport = report_obj.search(cr, uid, [('report_name', '=', reportname)], context=context)
                try:
                    report = report_obj.browse(cr, uid, idreport[0], context=context)
                    reportname = report.report_file  + '_' + time.strftime('%Y%m%d', time.gmtime())
                except IndexError:
                    _logger.error("Can not lookup report %s" % reportname)
                
                response.headers.add('Content-Disposition', 'attachment; filename=%s.pdf;' % reportname)
                response.set_cookie('fileToken', token)
                return response
            elif type =='controller':
                reqheaders = Headers(request.httprequest.headers)
                response = Client(request.httprequest.app, BaseResponse).get(url, headers=reqheaders, follow_redirects=True)
                response.set_cookie('fileToken', token)
                return response
            else:
                return
        except Exception, e:
            se = _serialize_exception(e)
            error = {
                'code': 200,
                'message': "Odoo Server Error",
                'data': se
            }
            return request.make_response(html_escape(simplejson.dumps(error)))
Exemple #40
0
    def report_download(self, data,token):
        """This function is used by 'qwebactionmanager.js' in order to trigger the download of
        a pdf/controller report.

        :param data: a javascript array JSON.stringified containg report internal url ([0]) and
        type [1]
        :returns: Response with a filetoken cookie and an attachment header
        """
        requestcontent = simplejson.loads(data)
        url, type = requestcontent[0], requestcontent[1]
        try:
            if type == 'qweb-pdf':
                reportname = url.split('/report/pdf/')[1].split('?')[0]

                docids = None
                if '/' in reportname:
                    reportname, docids = reportname.split('/')

                if docids:
                    # Generic report:
                    response = self.report_routes(reportname, docids=docids, converter='pdf')
                else:
                    # Particular report:
                    data = url_decode(url.split('?')[1]).items()  # decoding the args represented in JSON
                    response = self.report_routes(reportname, converter='pdf', **dict(data))
                if reportname == 'jjuice_fedex.report_print_label':
                    cr, context = request.cr, request.context
                    info = request.registry('create.shipment.fedex').read(cr,SUPERUSER_ID,int(docids),['to_person_name','tracking_number'])
                    str_list = []
                    str_list.append(time.strftime("%Y-%m-%d"))
                    str_list.append(info.get('to_person_name','unavailable') or 'unavailable')
                    str_list.append(info.get('tracking_number','unavailable') or 'unavailable')
                    label_name = '_'.join(str_list)
                    response.headers.add('Content-Disposition', 'attachment; filename=%s.pdf;' % label_name)
                else:
                    response.headers.add('Content-Disposition', 'attachment; filename=%s.pdf;' % reportname)
                response.set_cookie('fileToken', token)
                return response
            elif type =='controller':
                reqheaders = Headers(request.httprequest.headers)
                response = Client(request.httprequest.app, BaseResponse).get(url, headers=reqheaders, follow_redirects=True)
                response.set_cookie('fileToken', token)
                return response
            else:
                return
        except Exception, e:
            se = _serialize_exception(e)
            error = {
                'code': 200,
                'message': "Odoo Server Error",
                'data': se
            }
            return request.make_response(html_escape(simplejson.dumps(error)))
Exemple #41
0
    def report_download(self, data, token):
        """This function is used by 'qwebactionmanager.js' in order to trigger the download of
        a pdf/controller report.

        :param data: a javascript array JSON.stringified containg report internal url ([0]) and
        type [1]
        :returns: Response with a filetoken cookie and an attachment header
        """
        requestcontent = json.loads(data)
        url, type = requestcontent[0], requestcontent[1]
        try:
            if type == 'qweb-pdf':
                reportname = url.split('/report/pdf/')[1].split('?')[0]

                docids = None
                if '/' in reportname:
                    reportname, docids = reportname.split('/')

                if docids:
                    # Generic report:
                    response = self.report_routes(reportname, docids=docids, converter='pdf')
                else:
                    # Particular report:
                    data = url_decode(url.split('?')[1]).items()  # decoding the args represented in JSON
                    response = self.report_routes(reportname, converter='pdf', **dict(data))

                cr, uid = request.cr, request.uid
                report = request.registry['report']._get_report_from_name(cr, uid, reportname)
                filename = "%s.%s" % (report.name, "pdf")
                if docids:
                    ids = [int(x) for x in docids.split(",")]
                    obj = request.env[report.model].browse(ids)
                    if report.print_report_name and not len(obj) > 1:
                        filename = eval(report.print_report_name, {'object': obj, 'time': time})
                response.headers.add('Content-Disposition', content_disposition(filename))
                response.set_cookie('fileToken', token)
                return response
            elif type =='controller':
                reqheaders = Headers(request.httprequest.headers)
                response = Client(request.httprequest.app, BaseResponse).get(url, headers=reqheaders, follow_redirects=True)
                response.set_cookie('fileToken', token)
                return response
            else:
                return
        except Exception, e:
            se = _serialize_exception(e)
            error = {
                'code': 200,
                'message': "Odoo Server Error",
                'data': se
            }
            return request.make_response(html_escape(json.dumps(error)))
Exemple #42
0
	def report_download(self, data, token):
		"""This function is used by 'qwebactionmanager.js' in order to trigger the download of
		 a pdf/controller report.

		:param data: a javascript array JSON.stringified containg report internal url ([0]) and
		type [1]
		:returns: Response with a filetoken cookie and an attachment header
		"""
		requestcontent = simplejson.loads(data)
		url, type = requestcontent[0], requestcontent[1]
		try:
			if type == 'qweb-pdf':
				reportname = url.split('/report/pdf/')[1].split('?')[0]

				docids = None
				if '/' in reportname:
					reportname, docids = reportname.split('/')
				print docids,reportname
				if docids:
				    # Generic report:				    
					response = self.report_routes(reportname, docids=docids, converter='pdf')
				else:
				    # Particular report:
					data = url_decode(url.split('?')[1]).items()  # decoding the args represented in JSON
					response = self.report_routes(reportname, converter='pdf', **dict(data))

				#Rename the pdf's name make it looks kindly.
				report_ids = request.registry.get('ir.actions.report.xml').search(request.cr,openerp.SUPERUSER_ID,[('report_name','=',reportname)])
				if len(report_ids):
					report_obj = request.registry.get('ir.actions.report.xml').browse(request.cr,openerp.SUPERUSER_ID,report_ids[0])
					docids = [int(x) for x in docids.split(',')]
					reports = request.registry.get(report_obj.model).browse(request.cr,openerp.SUPERUSER_ID,docids)
					filename = reports[0].name
				
				response.headers.add('Content-Disposition', 'attachment; filename=%s.pdf;' % filename)
				response.set_cookie('fileToken', token)
				return response
			elif type =='controller':
				reqheaders = Headers(request.httprequest.headers)
				response = Client(request.httprequest.app, BaseResponse).get(url, headers=reqheaders, follow_redirects=True)
				response.set_cookie('fileToken', token)
				return response
			else:
				return
		except Exception, e:
			se = _serialize_exception(e)
			error = {
			    'code': 200,
			    'message': "Odoo Server Error",
			    'data': se
			}
			return request.make_response(html_escape(simplejson.dumps(error)))
Exemple #43
0
def create_engine(uri, relative_to=None, debug=False):
    """Create a new engine.  This works a bit like SQLAlchemy's
    `create_engine` with the difference that it automaticaly set's MySQL
    engines to 'utf-8', and paths for SQLite are relative to the path
    provided as `relative_to`.

    Furthermore the engine is created with `convert_unicode` by default.
    """
    # special case sqlite.  We want nicer urls for that one.
    if uri.startswith('sqlite:'):
        match = _sqlite_re.match(uri)
        if match is None:
            raise ArgumentError('Could not parse rfc1738 URL')
        database, query = match.groups()
        if database is None:
            database = ':memory:'
        elif relative_to is not None:
            database = path.join(relative_to, database)
        if query:
            query = url_decode(query).to_dict()
        else:
            query = {}
        info = URL('sqlite', database=database, query=query)

    else:
        info = make_url(uri)

        # if mysql is the database engine and no connection encoding is
        # provided we set it to utf-8
        if info.drivername == 'mysql':
            info.query.setdefault('charset', 'utf8')

    options = {'convert_unicode': True}

    # alternative pool sizes / recycle settings and more.  These are
    # interpreter wide and not from the config for the following reasons:
    #
    # - system administrators can set it independently from the webserver
    #   configuration via SetEnv and friends.
    # - this setting is deployment dependent should not affect a development
    #   server for the same instance or a development shell
    for key in 'pool_size', 'pool_recycle', 'pool_timeout':
        value = os.environ.get('ZINE_DATABASE_' + key.upper())
        if value is not None:
            options[key] = int(value)

    # if debugging is enabled, hook the ConnectionDebugProxy in
    if debug:
        options['proxy'] = ConnectionDebugProxy()

    return sqlalchemy.create_engine(info, **options)
Exemple #44
0
def announce():
    args = url_decode(request.query_string, None)
    ip = request.remote_addr
    info_hash = args[b'info_hash']
    peer_id = args[b'peer_id']
    try:
        port = int(args[b'port'])
        numwant = int(args.get(b'numwant', b'50'))
    except ValueError:
        abort(400)

    if len(info_hash) != 20 or len(peer_id) != 20:
        abort(400)

    if info_hash not in peer_map:
        peer_map[info_hash] = {
            'complete': set(),
            'incomplete': set(),
            'peers': {},
        }

    peers = []
    for pid in peer_map[info_hash]['peers']:
        if peer != peer_id:
            peer_ip, peer_port = peer_map[info_hash]['peers'][pid]
            peers.append({
                'peer_id': pid,
                'ip': peer_ip.encode('utf-8'),
                'port': peer_port,
            })
        if len(peers) >= numwant:
            break

    if peer_id not in peer_map[info_hash]:
        peer_map[info_hash]['peers'][peer_id] = (ip, port)
        if args[b'left'] == b'0':
            peer_map[info_hash]['complete'].add(peer_id)
            peer_map[info_hash]['incomplete'].discard(peer_id)
        else:
            peer_map[info_hash]['complete'].discard(peer_id)
            peer_map[info_hash]['incomplete'].add(peer_id)

    print('Peers:', peers)

    data = {
        'interval': 1800,
        'peers': peers,
    }

    return Response(bencode.dumps(data), mimetype='text/plain')
Exemple #45
0
def open_url(url,
             data=None,
             timeout=None,
             allow_internal_requests=True,
             **kwargs):
    """This function parses the URL and opens the connection.  The
    following protocols are supported:

    -   `http`
    -   `https`

    Per default requests to Rezine itself trigger an internal request.  This
    can be disabled by setting `allow_internal_requests` to False.
    """
    app = get_application()
    if timeout is None:
        timeout = app.cfg['default_network_timeout']
    parts = urlparse.urlsplit(url)
    if app is not None:
        blog_url = urlparse.urlsplit(app.cfg['blog_url'])
        if allow_internal_requests and \
           parts.scheme in ('http', 'https') and \
           blog_url.netloc == parts.netloc and \
           parts.path.startswith(blog_url.path):
            path = parts.path[len(blog_url.path):].lstrip('/')
            method = kwargs.pop('method', None)
            if method is None:
                method = data is not None and 'POST' or 'GET'
            make_response = lambda *a: URLResponse(url, *a)
            return app.perform_subrequest(path.decode('utf-8'),
                                          url_decode(parts.query),
                                          method,
                                          data,
                                          timeout=timeout,
                                          response_wrapper=make_response,
                                          **kwargs)
    handler = _url_handlers.get(parts.scheme)
    if handler is None:
        raise URLError('unsupported URL schema %r' % parts.scheme)
    if isinstance(data, basestring):
        data = StringIO(data)
    try:
        obj = handler(parts, timeout, **kwargs)
        return obj.open(data)
    except Exception, e:
        if not isinstance(e, NetException):
            e = NetException('%s: %s' % (e.__class__.__name__, str(e)))
        raise e
Exemple #46
0
def open_url(url, data=None, timeout=None, allow_internal_requests=True, **kwargs):
    """This function parses the URL and opens the connection.  The
    following protocols are supported:

    -   `http`
    -   `https`

    Per default requests to pyClanSphere itself trigger an internal request.  This
    can be disabled by setting `allow_internal_requests` to False.
    """
    app = get_application()
    if timeout is None:
        timeout = app.cfg["default_network_timeout"]
    parts = urlparse.urlsplit(url)
    if app is not None:
        site_url = urlparse.urlsplit(app.cfg["site_url"])
        if (
            allow_internal_requests
            and parts.scheme in ("http", "https")
            and site_url.netloc == parts.netloc
            and parts.path.startswith(site_url.path)
        ):
            path = parts.path[len(site_url.path) :].lstrip("/")
            method = kwargs.pop("method", None)
            if method is None:
                method = data is not None and "POST" or "GET"
            make_response = lambda *a: URLResponse(url, *a)
            return app.perform_subrequest(
                path.decode("utf-8"),
                url_decode(parts.query),
                method,
                data,
                timeout=timeout,
                response_wrapper=make_response,
                **kwargs
            )
    handler = _url_handlers.get(parts.scheme)
    if handler is None:
        raise URLError("unsupported URL schema %r" % parts.scheme)
    if isinstance(data, basestring):
        data = StringIO(data)
    try:
        obj = handler(parts, timeout, **kwargs)
        return obj.open(data)
    except Exception, e:
        if not isinstance(e, NetException):
            e = NetException("%s: %s" % (e.__class__.__name__, str(e)))
        raise e
Exemple #47
0
	def __call__(self, env, start_response):
		"""
			snippet based in:
			https://github.com/indabamusic/rack-escaped-fragment/blob/master/lib/rack/escaped_fragment.rb
		"""
		from werkzeug import url_decode
		from re import search
		
		if search('_escaped_fragment_', env.get('QUERY_STRING', '')):
			query_string = url_decode(env['QUERY_STRING'])
			env['QUERY_STRING']=query_string.get('_escaped_fragment_')
			##DEFINE INFORMATION ABOUT PATH_INFO::
			if search('/\w', query_string.get('_escaped_fragment_')):
				env['PATH_INFO'] = query_string.get('_escaped_fragment_')
			app.logger.info(env['PATH_INFO'])
		return self.app(env, start_response)	
Exemple #48
0
def parse_response(resp, content, strict=False):
    ct, options = parse_options_header(resp['content-type'])
    if ct == 'application/json':
        return json.loads(content)
    elif ct in ('application/xml', 'text/xml'):
        # technically, text/xml is ascii based but because many
        # implementations get that wrong and utf-8 is a superst
        # of utf-8 anyways, there is not much harm in assuming
        # utf-8 here
        charset = options.get('charset', 'utf-8')
        return get_etree().fromstring(content.decode(charset))
    elif ct != 'application/x-www-form-urlencoded':
        if strict:
            return content
    charset = options.get('charset', 'utf-8')
    return url_decode(content, charset=charset).to_dict()
Exemple #49
0
def parse_response(resp, content, strict=False):
    ct, options = parse_options_header(resp['content-type'])
    if ct == 'application/json':
        return json.loads(content)
    elif ct in ('application/xml', 'text/xml'):
        # technically, text/xml is ascii based but because many
        # implementations get that wrong and utf-8 is a superst
        # of utf-8 anyways, there is not much harm in assuming
        # utf-8 here
        charset = options.get('charset', 'utf-8')
        return get_etree().fromstring(content.decode(charset))
    elif ct != 'application/x-www-form-urlencoded':
        if strict:
            return content
    charset = options.get('charset', 'utf-8')
    return url_decode(content, charset=charset).to_dict()
Exemple #50
0
    def report_download(self, data, token):
        """This function is used by 'qwebactionmanager.js' in order to trigger the download of
        a pdf/controller report.

        :param data: a javascript array JSON.stringified containg report internal url ([0]) and
        type [1]
        :returns: Response with a filetoken cookie and an attachment header
        """
        requestcontent = simplejson.loads(data)
        url, type = requestcontent[0], requestcontent[1]

        if type == 'qweb-pdf':
            reportname = url.split('/report/pdf/')[1].split('?')[0]

            docids = None
            if '/' in reportname:
                reportname, docids = reportname.split('/')

            if docids:
                # Generic report:
                response = self.report_routes(reportname,
                                              docids=docids,
                                              converter='pdf')
            else:
                # Particular report:
                data = url_decode(url.split(
                    '?')[1]).items()  # decoding the args represented in JSON
                response = self.report_routes(reportname,
                                              converter='pdf',
                                              **dict(data))

            response.headers.add('Content-Disposition',
                                 'attachment; filename=%s.pdf;' % reportname)
            response.set_cookie('fileToken', token)
            return response
        elif type == 'controller':
            reqheaders = Headers(request.httprequest.headers)
            response = Client(request.httprequest.app,
                              BaseResponse).get(url,
                                                headers=reqheaders,
                                                follow_redirects=True)
            response.set_cookie('fileToken', token)
            return response
        else:
            return
Exemple #51
0
    def report_download(self, data, token):
        """This function is used by 'qwebactionmanager.js' in order to trigger the download of
        a pdf/controller report.

        :param data: a javascript array JSON.stringified containg report internal url ([0]) and
        type [1]
        :returns: Response with a filetoken cookie and an attachment header
        """
        requestcontent = json.loads(data)
        url, type = requestcontent[0], requestcontent[1]
        try:
            if type == "qweb-pdf":
                reportname = url.split("/report/pdf/")[1].split("?")[0]

                docids = None
                if "/" in reportname:
                    reportname, docids = reportname.split("/")

                if docids:
                    # Generic report:
                    response = self.report_routes(reportname, docids=docids, converter="pdf")
                else:
                    # Particular report:
                    data = url_decode(url.split("?")[1]).items()  # decoding the args represented in JSON
                    response = self.report_routes(reportname, converter="pdf", **dict(data))

                cr, uid = request.cr, request.uid
                report = request.registry["report"]._get_report_from_name(cr, uid, reportname)
                filename = "%s.%s" % (report.name, "pdf")
                response.headers.add("Content-Disposition", content_disposition(filename))
                response.set_cookie("fileToken", token)
                return response
            elif type == "controller":
                reqheaders = Headers(request.httprequest.headers)
                response = Client(request.httprequest.app, BaseResponse).get(
                    url, headers=reqheaders, follow_redirects=True
                )
                response.set_cookie("fileToken", token)
                return response
            else:
                return
        except Exception, e:
            se = _serialize_exception(e)
            error = {"code": 200, "message": "Odoo Server Error", "data": se}
            return request.make_response(html_escape(json.dumps(error)))
Exemple #52
0
	def handle_unknown_response(self):
		if request.args.get('authorize') == 0:
			return None

		print "lkjalskdjflkjasdf"
		consumer = oldOauth.Consumer(key=self.consumer_key, secret=self.consumer_secret)
		client = oldOauth.Client(consumer, oldOauth.Token(*session['%s_oauthtok' % self.name]))
		response, content = client.request(self.access_token_url, 'POST')

		print response

		if response['status'] not in ('200', '201'):
			raise OAuthException(
				'Invalid response from %s' % self.name,
				type='invalid_response', data=response)

		decoded = url_decode(content).to_dict()
		return decoded
Exemple #53
0
def parse_response(resp, content, strict=False, content_type=None):
    """
    Parse the response returned by :meth:`make_request`.
    """
    if not content_type:
        content_type = resp.headers.get('content-type', 'application/json')
    ct, options = parse_options_header(content_type)

    if ct in ('application/json', 'text/javascript'):
        return json.loads(content)

    if ct in ('application/xml', 'text/xml'):
        return get_etree().fromstring(content)

    if ct != 'application/x-www-form-urlencoded' and strict:
        return content
    charset = options.get('charset', 'utf-8')
    return url_decode(content, charset=charset).to_dict()
Exemple #54
0
    def report_download(self, data, token):
        """This function is used by 'qwebactionmanager.js' in order to trigger the download of
        a pdf/controller report.

        :param data: a javascript array JSON.stringified containg report internal url ([0]) and
        type [1]
        :returns: Response with a filetoken cookie and an attachment header
        """
        requestcontent = simplejson.loads(data)
        url, type = requestcontent[0], requestcontent[1]
        try:
            if type == 'qweb-pdf':
                reportname = url.split('/report/pdf/')[1].split('?')[0]

                docids = None
                if '/' in reportname:
                    reportname, docids = reportname.split('/')

                if docids:
                    # Generic report:
                    response = self.report_routes(reportname, docids=docids, converter='pdf')
                else:
                    # Particular report:
                    data = url_decode(url.split('?')[1]).items()  # decoding the args represented in JSON
                    response = self.report_routes(reportname, converter='pdf', **dict(data))

                response.headers.add('Content-Disposition', 'attachment; filename=%s.pdf;' % reportname)
                response.set_cookie('fileToken', token)
                return response
            elif type =='controller':
                reqheaders = Headers(request.httprequest.headers)
                response = Client(request.httprequest.app, BaseResponse).get(url, headers=reqheaders, follow_redirects=True)
                response.set_cookie('fileToken', token)
                return response
            else:
                return
        except osv.except_osv, e:
            se = _serialize_exception(e)
            error = {
                'code': 200,
                'message': "Odoo Server Error",
                'data': se
            }
            return request.make_response(simplejson.dumps(error))
Exemple #55
0
def parse_response(resp, content, strict=False, content_type=None):
    """
    Parse the response returned by :meth:`make_request`.
    """
    if not content_type:
        content_type = resp.headers.get('content-type', 'application/json')
    ct, options = parse_options_header(content_type)

    if ct in ('application/json', 'text/javascript'):
        return json.loads(content)

    if ct in ('application/xml', 'text/xml'):
        charset = options.get('charset', 'utf-8')
        return get_etree().fromstring(content.decode(charset))

    if ct != 'application/x-www-form-urlencoded' and strict:
        return content
    charset = options.get('charset', 'utf-8')
    return url_decode(content, charset=charset).to_dict()
Exemple #56
0
    def __call__(self, rev, contenttype=None, arguments=None):
        item_name = rev.item.name
        query_keys = {'do': 'get', 'rev': rev.revid}
        attrib = {}
        if arguments:
            query = arguments.keyword.get(xinclude.href).query
            if query:
                query_keys.update(url_decode(query))
            attrib = arguments.keyword

        query = url_encode(query_keys, charset=CHARSET, encode_keys=True)

        attrib.update({
            moin_page.type_: unicode(self.input_type),
            xlink.href: Iri(scheme='wiki', authority='', path='/' + item_name,
                            query=query),
        })

        obj = moin_page.object_(attrib=attrib, children=[item_name, ])
        body = moin_page.body(children=(obj, ))
        return moin_page.page(children=(body, ))
Exemple #57
0
    def report_download(self, data, token):
        """This function is used by 'qwebactionmanager.js' in order to trigger
        the download of a py3o/controller report.

        :param data: a javascript array JSON.stringified containg report
        internal url ([0]) and type [1]
        :returns: Response with a filetoken cookie and an attachment header
        """
        requestcontent = json.loads(data)
        url, type = requestcontent[0], requestcontent[1]
        if type != 'aeroo':
            return super(ReportController, self).report_download(data, token)
        try:
            reportname = url.split('/report/aeroo/')[1].split('?')[0]
            docids = None
            if '/' in reportname:
                reportname, docids = reportname.split('/')

            # on aeroo we support docids + data
            data = url_decode(url.split('?')[1]).items()
            response = self.report_routes(reportname,
                                          docids=docids,
                                          converter='aeroo',
                                          **dict(data))
            # if docids:
            #     # Generic report:
            #     response = self.report_routes(
            #         reportname, docids=docids, converter='aeroo')
            # else:
            #     # Particular report:
            #     # decoding the args represented in JSON
            #     data = url_decode(url.split('?')[1]).items()
            #     response = self.report_routes(
            #         reportname, converter='aeroo', **dict(data))
            response.set_cookie('fileToken', token)
            return response
        except Exception as e:
            se = _serialize_exception(e)
            error = {'code': 200, 'message': "Odoo Server Error", 'data': se}
            return request.make_response(html_escape(json.dumps(error)))
Exemple #58
0
    def report_download(self, data, token):
        """
        This is an override of original method in ReportController class in
        report module
        What is intended here is to properly assign to the extension to XLS
        """
        response = super(ReportController, self).report_download(data, token)
        context = request.context
        if response is None:
            return response

        requestcontent = simplejson.loads(data)
        url = requestcontent[0]

        # decoding the args represented in JSON
        url_split = url.split('?')
        index = len(url_split) > 1 and 1 or 0
        new_data = url_decode(url_split[index]).items()

        new_data = dict(new_data)
        if new_data.get('context'):
            context = simplejson.loads(new_data['context']) or {}

        if not context.get('xls_report'):
            return response

        reportname = url.split('/report/pdf/')[1].split('?')[0]
        # As headers have been implement as as list there are no unique headers
        # adding them just result into duplicated headers that are not
        # unique will convert them into dict update the required header and
        # then will be assigned back into headers
        headers = dict(response.headers.items())
        headers.update({
            'Content-Disposition':
            'attachment; filename=%s.xls;' % reportname
        })
        response.headers.clear()
        for key, value in headers.iteritems():
            response.headers.add(key, value)
        return response
Exemple #59
0
    def __call__(self, environ, response):
        """ Extract the new method from the Query String """

        method = None
        
        # Can get from HTTP header
        if self.header_key in environ:
            method = environ[self.header_key]

        # Or from query string
        elif self.qs_key in environ.get('QUERY_STRING', ''):
            args = url_decode(environ['QUERY_STRING'])
            method = args.get(self.qs_key, '')
            
        if method:
            method = method.upper()            
            if method in self.allowed_methods:
                environ['REQUEST_METHOD'] = method
            if method in self.bodyless_methods:
                environ['CONTENT_LENGTH'] = '0'

        return self.app(environ, response)
Exemple #60
0
def parse_response(resp, content, strict=False, content_type=None):
    """Parse the response returned by :meth:`OAuthRemoteApp.http_request`.

    :param resp: response of http_request
    :param content: content of the response
    :param strict: strict mode for form urlencoded content
    :param content_type: assign a content type manually
    """
    if not content_type:
        content_type = resp.headers.get('content-type', 'application/json')
    ct, options = parse_options_header(content_type)

    if ct in ('application/json', 'text/javascript'):
        return json.loads(content)

    if ct in ('application/xml', 'text/xml'):
        return get_etree().fromstring(content)

    if ct != 'application/x-www-form-urlencoded' and strict:
        return content
    charset = options.get('charset', 'utf-8')
    return url_decode(content, charset=charset).to_dict()