Ir al contenido
Odoo Menú
  • Identificarse
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • TPV para tiendas
    • TPV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en directo
    • e-learning
    Cadena de suministro
    • Inventario
    • Fabricación
    • PLM
    • Compra
    • Mantenimiento
    • Calidad
    Recursos Humanos
    • Empleados
    • Reclutamiento
    • Ausencias
    • Evaluación
    • Referencias
    • Flota
    Marketing
    • Marketing social
    • Marketing por correo electrónico
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyecto
    • Partes de horas
    • Servicio de campo
    • Servicio de asistencia
    • Planificación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Conocimientos
    • WhatsApp
    Aplicaciones de terceros Studio de Odoo Plataforma de Odoo Cloud
  • Industrias
    Comercio al por menor
    • Librería
    • Tienda de ropa
    • Tienda de muebles
    • Tienda de ultramarinos
    • Ferretería
    • Juguetería
    Alimentación y hostelería
    • Bar y taberna
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidor de bebidas
    • Hotel
    Inmueble
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión inmobiliaria
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Empresa contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Fabricación
    • Textil
    • Metal
    • Muebles
    • Alimentos
    • Brewery
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Oficios
    • Handyman
    • Hardware y asistencia informática
    • Sistemas de energía solar
    • Zapatero
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin ánimo de lucro
    • Agencia de protección del medio ambiente
    • Alquiler de paneles publicitarios
    • Estudio fotográfico
    • Alquiler de bicicletas
    • Distribuidor de software
    Explorar todos los sectores
  • Comunidad
    Aprender
    • Tutoriales
    • Documentación
    • Certificaciones
    • Formación
    • Blog
    • Podcast
    Potenciar la educación
    • Programa de formación
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtener el software
    • Descargar
    • Comparar ediciones
    • Versiones
    Colaborar
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Convertirse en partner
    • Servicios para partners
    • Registrar tu empresa contable
    Obtener servicios
    • Encontrar un partner
    • Encontrar un asesor fiscal
    • Contacta con un experto
    • Servicios de implementación
    • Referencias de clientes
    • Ayuda
    • Actualizaciones
    GitHub YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicitar una demostración
  • Precios
  • Ayuda

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyecto
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

Non-ASCII/Unicode/Cyrillic URL on Website

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
werkzeugurlcyrillicunicodewebsite
1 Responder
8967 Vistas
Avatar
Anton Chepurov

My goal is to turn the standard website URL of a Product:

/shop/product/ipad-retina-display-5

into a different format:

/shop/product/5/ipad/ipad-с-дисплеем-retina/a2323

where ID is moved to right after the `/shop/product/`, brand follows ID, Internal Reference is added to the end of the URL, and most importantly the product name is translated to the language currently selected (in this example - Russian).

I use the following code to achieve all but translations:

class my_module_website_sale(website_sale):
    @http.route(['/shop/product/<product_model:product>'])
    def product(self, product, category='', search='', **kwargs):
        return super(my_module_website_sale, self).product(product, category=category, search=search, **kwargs)

and this:

from openerp.addons.website.models import website
from openerp.addons.website.models.ir_http import RequestUID
from openerp.addons.website.models.website import slugify

old_slug = website.slug

def slug_product(value):
    if isinstance(value, tuple):
        id, brand, name, default_code = value
    else:
        id, brand, name, default_code = value.id, value.product_variant_ids[0].brand_id.name, value.name, value.default_code
    return '%s/%s/%s/%s' % (id, brand, slugify(name), default_code)

def slug(value):
    if isinstance(value, browse_record) and value._name == 'product.template':
        return slug_product(value)
    return old_slug(value)

website.slug = slug

class ProductModelConverter(werkzeug.routing.PathConverter):
    def __init__(self, url_map):
        super(ProductModelConverter, self).__init__(url_map)
        self.regex = '([0-9]+)/.*'

    def to_python(self, value):
        m = re.match(self.regex, value)
        _uid = RequestUID(value=value, match=m, converter=self)
        return request.registry['product.template'].browse(
            request.cr, _uid, int(m.group(1)), context=request.context)

    def to_url(self, value):
        return slug_product(value)

    def generate(self, cr, uid, query=None, args=None, context=None):
        brands = {b['id']: b['name'] for b in fetchdictall(cr, 'SELECT id, name FROM my_module_brand')}
        products = [(tmpl, brands.get(brand, ''), name, code)
                            for (tmpl, brand, name, code) in
                            fetchall(cr, 'SELECT product_tmpl_id, brand_id, name_template, default_code FROM product_product '
                                                'LEFT JOIN product_template t ON product_tmpl_id = t.id WHERE t.website_published = true ORDER BY product_tmpl_id')]
        templates_done = set()
        for product in products:
            if product[0] not in templates_done:
                templates_done.add(product[0])
                yield {'loc': product}

class ir_http(models.AbstractModel):
    _inherit = 'ir.http'

    def _get_converters(self):
        return dict(super(ir_http, self)._get_converters(), product_model=ProductModelConverter)

 This code works perfectly well for the ASCII URLs, e.g. this URL brings me to the required website shop page:

/shop/product/5/ipad/ipad-retina-display/a2323

However, once translated to Russian, this URL raises an error on the werkzeug level (i.e. not even reaching my code, AFAIU):

/shop/product/5/ipad/ipad-с-дисплеем-retina/a2323

The error:

2016-08-09 05:15:26,210 3902 INFO mgr werkzeug: 127.0.0.1 - - [09/Aug/2016 05:15:26] "GET /ru_RU/shop/product/5/ipad/%D0%B2%D0%BE%D0%B4%D1%8F%D0%BD%D0%BE%D0%B9-%D1%88%D0%BB%D0%B0%D0%BD%D0%B3/a2323 HTTP/1.0" 500 -
2016-08-09 05:15:26,217 3902 ERROR mgr werkzeug: Error on request:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/werkzeug/serving.py", line 177, in run_wsgi
execute(self.server.app)
File "/usr/lib/python2.7/dist-packages/werkzeug/serving.py", line 165, in execute
application_iter = app(environ, start_response)
File "/home/a0c/programs/openerp/odoo/openerp/service/server.py", line 291, in app
return self.app(e, s)
File "/home/a0c/programs/openerp/odoo/openerp/service/wsgi_server.py", line 224, in application
return application_unproxied(environ, start_response)
File "/home/a0c/programs/openerp/odoo/openerp/service/wsgi_server.py", line 210, in application_unproxied
result = handler(environ, start_response)
File "/home/a0c/programs/openerp/odoo/openerp/http.py", line 1292, in __call__
return self.dispatch(environ, start_response)
File "/home/a0c/programs/openerp/odoo/openerp/http.py", line 1266, in __call__
return self.app(environ, start_wrapped)
File "/usr/lib/python2.7/dist-packages/werkzeug/wsgi.py", line 579, in __call__
return self.app(environ, start_response)
File "/home/a0c/programs/openerp/odoo/openerp/http.py", line 1266, in __call__
return self.app(environ, start_wrapped)
File "/usr/lib/python2.7/dist-packages/werkzeug/wsgi.py", line 579, in __call__
return self.app(environ, start_response)
File "/home/a0c/programs/openerp/odoo/openerp/http.py", line 1439, in dispatch
result = ir_http._dispatch()
File "/home/a0c/programs/openerp/odoo/addons/crm/ir_http.py", line 13, in _dispatch
response = super(ir_http, self)._dispatch()
File "/home/a0c/programs/openerp/odoo/addons/website/models/ir_http.py", line 145, in _dispatch
return self.reroute('/'.join(path) or '/')
File "/home/a0c/programs/openerp/odoo/addons/website/models/ir_http.py", line 166, in reroute
return self._dispatch()
File "/home/a0c/programs/openerp/odoo/addons/crm/ir_http.py", line 13, in _dispatch
response = super(ir_http, self)._dispatch()
File "/home/a0c/programs/openerp/odoo/addons/website/models/ir_http.py", line 72, in _dispatch
func, arguments = self._find_handler()
File "/home/a0c/programs/openerp/odoo/openerp/addons/base/ir/ir_http.py", line 65, in _find_handler
return self.routing_map().bind_to_environ(request.httprequest.environ).match(return_rule=return_rule)
File "/usr/lib/python2.7/dist-packages/werkzeug/routing.py", line 1202, in bind_to_environ
path_info = _get_wsgi_string('PATH_INFO')
File "/usr/lib/python2.7/dist-packages/werkzeug/routing.py", line 1199, in _get_wsgi_string
return wsgi_decoding_dance(val, self.charset)
File "/usr/lib/python2.7/dist-packages/werkzeug/_compat.py", line 92, in wsgi_decoding_dance
return s.decode(charset, errors)
File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 21-27: ordinal not in range(128)


Does anybody have an idea how to properly configure werkzeug's PathConverters (or I dunno what else) to make them accept non-ASCII URLs?

Many thanks!

2
Avatar
Descartar
Avatar
Anton Chepurov
Autor Mejor respuesta

Solved this by patching werkzeug and by making slugify() and url_for() support unicode URLs.

Change wsgi_decoding_dance() in werkzeug/_compat.py to:

 def wsgi_decoding_dance(s, charset='utf-8', errors='replace'):
    if isinstance(s, unicode):
        return s
    return s.decode(charset, errors)

This is similar to wsgi_encoding_dance():

 def wsgi_encoding_dance(s, charset='utf-8', errors='replace'):
    if isinstance(s, bytes):
        return s
    return s.encode(charset, errors)

And in the code snippet above, instead of importing slugify() from odoo

from openerp.addons.website.models.website import slugify

define your own slugify() to be used in slug_product():

import unicodedata
from openerp.tools import ustr

def slugify(s, max_length=None):
    s = ustr(s)
    uni = unicodedata.normalize('NFKC', s)
    slug = re.sub('[\W_]', ' ', uni, flags=re.UNICODE).strip().lower()
    slug = re.sub('[-\s]+', '-', slug)
    return slug[:max_length]

Finally, override url_for():

import urlparse
from openerp.addons.web.http import request
from openerp.addons.website.models.website import is_multilang_url

def url_for(path_or_uri, lang=None):
    if isinstance(path_or_uri, unicode):
        path_or_uri = path_or_uri.encode('utf-8')
    current_path = request.httprequest.path
    if isinstance(current_path, unicode):
        current_path = current_path.encode('utf-8')
    location = path_or_uri.strip()
    force_lang = lang is not None
    url = urlparse.urlparse(location)

    if request and not url.netloc and not url.scheme and (url.path or force_lang):
        location = urlparse.urljoin(current_path, location)

        lang = lang or request.context.get('lang')
        langs = [lg[0] for lg in request.website.get_languages()]

        if (len(langs) > 1 or force_lang) and is_multilang_url(location, langs):
            ps = location.decode('utf-8').split('/')
            if ps[1] in langs:
                # Replace the language only if we explicitly provide a language to url_for
                if force_lang:
                    ps[1] = lang
                # Remove the default language unless it's explicitly provided
                elif ps[1] == request.website.default_lang_code:
                    ps.pop(1)
            # Insert the context language or the provided language
            elif lang != request.website.default_lang_code or force_lang:
                ps.insert(1, lang)
            location = '/'.join(ps)
    return location if isinstance(location, unicode) else location.decode('utf-8')

import openerp
openerp.addons.website.models.website.url_for = url_for



3
Avatar
Descartar
Sehrish

awsome

¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Inscribirse
Publicaciones relacionadas Respuestas Vistas Actividad
Multi website with a different xxx.odoo.com address
url website
Avatar
0
ene 21
6639
How do I change my Odoo Website URL? Resuelto
url website
Avatar
Avatar
1
abr 17
8439
How redirect from Website Front end to Odoo Web Back end ? Resuelto
url redirect website
Avatar
Avatar
Avatar
Avatar
Avatar
5
jul 25
17601
How to include the product variant in website URL
url variants website
Avatar
0
ene 24
2297
Redirection error
url website odoo12
Avatar
0
oct 23
2292
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento Odoo.sh
  • Ayuda
  • Actualizar
  • Desarrollos personalizados
  • Educación
  • Encontrar un asesor fiscal
  • Encontrar un partner
  • Convertirse en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contacta con nosotros
  • Puestos de trabajo
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Información legal • Privacidad
  • Seguridad
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y totalmente integrado.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now