Export CSV - jordy33/turbogears_tutorial GitHub Wiki

Export data to a coma separated values

In controllers update secure.py with the following code:

# -*- coding: utf-8 -*-
"""Sample controller with all its actions protected."""
from tg import expose, flash
from tg.i18n import ugettext as _, lazy_ugettext as l_
from tg.predicates import has_permission

from myprojectname.lib.base import BaseController
##
from myprojectname.model.auth import User
from myprojectname.lib.utils import ExportCSV
from myprojectname.model import DBSession
from tg import predicates,url
##
__all__ = ['SecureController']

class SecureController(BaseController):
    """Sample controller-wide authorization"""

    # The predicate that must be met for all the actions in this controller:
    allow_only = predicates.not_anonymous()

    @expose('myprojectname.templates.index')
    def index(self):
        """Let the user know that's visiting a protected controller."""
        flash(_("Secure Controller here"))
        return dict(page='index')

    @expose('myprojectname.templates.index')
    def some_where(self):
        """Let the user know that this action is protected too."""
        return dict(page='some_where')

    @expose('myprojectname.templates.csv')
    def csv(self):
        list=[]
        allrecords = DBSession.query(User).all()
        for item in allrecords:
            list.append(str(item.user_id)+","+item.user_name+","+item.email_address+","+item.display_name+'\n')
        # list=array of items, the next parameter is the file name, the last is the current route (for debugging)
        file_name=ExportCSV.create(list,"users","/secc/csv")
        return dict(file_name=file_name)

In lib directory create utils.py and insert the following code:

# -*- coding: utf-8 -*-
"""The base Controller API."""

from myprojectname.lib.helpers import whoami
import os,sys
from tg import abort
__all__ = ['ExportCSV']

from pathlib import Path


class ExportCSV():
    """
     Export CSV
    """
    @classmethod
    def create(cls, list,name,url):
        cwd = os.getcwd()
        np=cwd.rfind("/")+1
        who=whoami()
        if who=="":
            error="CSV Failure"
            reason="User not logged"
            message = "The following {} occured, this is due to {}, please DEBUG the url : {}".format(error, reason,url)
            abort(status_code=500, detail=message)
        file_name=cwd+"/"+cwd[np:]+"/public/"+who+"_"+name+".csv"
        my_file = Path(file_name)
        if my_file.is_file():
            os.remove(file_name)
        outfile = open(file_name, 'w')
        for item in list:
            outfile.write(item)
        outfile.close()
        return "/"+who+"_"+name+".csv"

In the templates folder insert csv.mak and insert the following

<%inherit file="local:templates.master"/>

<%def name="title()">
Learning TurboGears 2.3: Quick guide to the Quickstart pages.
</%def>

    <div class="row">
      <div class="col-md-12">
        <div class="page-header">
          <h2>CSV Example</h2>
        </div>
	  <div class="container" align="left">
          <a href="${tg.url("/manager_users.csv")}" download>
        <img border="0" src="${tg.url('/img/download.png')}" alt="Press here to Download" width="104" height="142">
        </a>
      </form>
	  </div>
      </div>
    </div>

From the images of this repository download the file download.png and insert into public/img

Test the code:

http://localhost:8086/secc/csv
⚠️ **GitHub.com Fallback** ⚠️