Guest User

Untitled

a guest
Aug 24th, 2016
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.14 KB | None | 0 0
  1. class PlustronWebsite(Website):
  2.     # ------------------------------------------------------
  3.     # View
  4.     # ------------------------------------------------------
  5.     #
  6.     @http.route([
  7.         '/web/binary/company_logo',
  8.         '/logo',
  9.         '/logo.png',
  10.     ], type='http', auth="public", cors="*")
  11.     def company_logo(self, dbname=None, **kw):
  12.         imgname = 'logo.png'
  13.         placeholder = functools.partial(get_module_resource, 'web', 'static', 'src', 'img')
  14.         uid = None
  15.         wid = None
  16.         if request.session.db:
  17.             dbname = request.session.db
  18.             uid = request.session.uid
  19.             wid = request.registry['website'].get_current_website(request.cr, request.uid, context=request.context).id
  20.         elif dbname is None:
  21.             dbname = db_monodb()
  22.         if not uid and not wid:
  23.             uid = SUPERUSER_ID
  24.         if not dbname:
  25.             response = http.send_file(placeholder(imgname))
  26.         else:
  27.             try:
  28.                 # create an empty registry
  29.                 registry = openerp.modules.registry.Registry(dbname)
  30.                 with registry.cursor() as cr:
  31.                     if wid:
  32.                         cr.execute("""SELECT c.logo_web, c.write_date
  33.                                        FROM website u
  34.                                   LEFT JOIN res_company c
  35.                                          ON c.id = u.company_id
  36.                                       WHERE u.id = %s
  37.                                   """, (wid,))
  38.                     else:
  39.                         cr.execute("""SELECT c.logo_web, c.write_date
  40.                                        FROM res_users u
  41.                                   LEFT JOIN res_company c
  42.                                          ON c.id = u.company_id
  43.                                       WHERE u.id = %s
  44.                                   """, (uid,))
  45.                     row = cr.fetchone()
  46.                     if row and row[0]:
  47.                         image_data = StringIO(str(row[0]).decode('base64'))
  48.                         response = http.send_file(image_data, filename=imgname, mtime=row[1])
  49.                     else:
  50.                         response = http.send_file(placeholder('nologo.png'))
  51.             except Exception:
  52.                 response = http.send_file(placeholder(imgname))
  53.  
  54.         return response
  55.  
  56.     @http.route(['/robots.txt'], type='http', auth="public")
  57.     def robots(self):
  58.         return request.render('website.robots', {'url_root': request.httprequest.url_root}, mimetype='text/plain')
  59.  
  60.     @http.route('/sitemap.xml', type='http', auth="public", website=True)
  61.     def sitemap_xml_index(self):
  62.         cr, uid, context = request.cr, openerp.SUPERUSER_ID, request.context
  63.         ira = request.registry['ir.attachment']
  64.         iuv = request.registry['ir.ui.view']
  65.         mimetype = 'application/xml;charset=utf-8'
  66.         content = None
  67.  
  68.         def create_sitemap(url, content):
  69.             ira.create(cr, uid, dict(
  70.                 datas=content.encode('base64'),
  71.                 mimetype=mimetype,
  72.                 type='binary',
  73.                 name=url,
  74.                 url=url,
  75.             ), context=context)
  76.  
  77.         sitemap = ira.search_read(cr, uid, [('url', '=', '/sitemap.xml'), ('type', '=', 'binary')],
  78.                                   ('datas', 'create_date'), context=context)
  79.         if sitemap:
  80.             # Check if stored version is still valid
  81.             server_format = openerp.tools.misc.DEFAULT_SERVER_DATETIME_FORMAT
  82.             create_date = datetime.datetime.strptime(sitemap[0]['create_date'], server_format)
  83.             delta = datetime.datetime.now() - create_date
  84.             if delta < SITEMAP_CACHE_TIME:
  85.                 content = sitemap[0]['datas'].decode('base64')
  86.  
  87.         if not content:
  88.             # Remove all sitemaps in ir.attachments as we're going to regenerated them
  89.             sitemap_ids = ira.search(cr, uid, [('url', '=like', '/sitemap%.xml'), ('type', '=', 'binary')],
  90.                                      context=context)
  91.             if sitemap_ids:
  92.                 ira.unlink(cr, uid, sitemap_ids, context=context)
  93.  
  94.             pages = 0
  95.             first_page = None
  96.             locs = request.website.sudo(user=request.website.user_id.id).enumerate_pages()
  97.             while True:
  98.                 start = pages * LOC_PER_SITEMAP
  99.                 values = {
  100.                     'locs': islice(locs, start, start + LOC_PER_SITEMAP),
  101.                     'url_root': request.httprequest.url_root[:-1],
  102.                 }
  103.                 urls = iuv.render(cr, uid, 'website.sitemap_locs', values, context=context)
  104.                 if urls.strip():
  105.                     page = iuv.render(cr, uid, 'website.sitemap_xml', dict(content=urls), context=context)
  106.                     if not first_page:
  107.                         first_page = page
  108.                     pages += 1
  109.                     create_sitemap('/sitemap-%d.xml' % pages, page)
  110.                 else:
  111.                     break
  112.             if not pages:
  113.                 return request.not_found()
  114.             elif pages == 1:
  115.                 content = first_page
  116.             else:
  117.                 # Sitemaps must be split in several smaller files with a sitemap index
  118.                 content = iuv.render(cr, uid, 'website.sitemap_index_xml', dict(
  119.                     pages=range(1, pages + 1),
  120.                     url_root=request.httprequest.url_root,
  121.                 ), context=context)
  122.             create_sitemap('/sitemap.xml', content)
  123.  
  124.         return request.make_response(content, [('Content-Type', mimetype)])
  125.  
  126.     # ------------------------------------------------------
  127.     # Misc. route utils
  128.     # ------------------------------------------------------
  129.     @http.route(['/report/barcode', '/report/barcode/<type>/<path:value>'], type='http', auth="user")
  130.     def report_barcode(self, type, value, width=300, height=300, humanreadable=0):
  131.         """Contoller able to render barcode images thanks to reportlab.
  132.        Samples:
  133.            <img t-att-src="'/report/barcode/QR/%s' % o.name"/>
  134.            <img t-att-src="'/report/barcode/?type=%s&amp;value=%s&amp;width=%s&amp;height=%s' %
  135.                ('QR', o.name, 200, 200)"/>
  136.        :param type: Accepted types: 'Codabar', 'Code11', 'Code128', 'EAN13', 'EAN8', 'Extended39',
  137.        'Extended93', 'FIM', 'I2of5', 'MSI', 'POSTNET', 'QR', 'Standard39', 'Standard93',
  138.        'UPCA', 'USPS_4State'
  139.        :param humanreadable: Accepted values: 0 (default) or 1. 1 will insert the readable value
  140.        at the bottom of the output image
  141.        """
  142.         try:
  143.             width, height, humanreadable = int(width), int(height), bool(int(humanreadable))
  144.             barcode = createBarcodeDrawing(
  145.                 type, value=value, format='png', width=width, height=height,
  146.                 humanReadable=humanreadable
  147.             )
  148.             barcode = barcode.asString('png')
  149.         except (ValueError, AttributeError):
  150.             raise exceptions.HTTPException(description='Cannot convert into barcode.')
  151.  
  152.         return request.make_response(barcode, headers=[('Content-Type', 'image/png')])
Add Comment
Please, Sign In to add comment