Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an example that returns a sum of values. #94

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions examples/pyramid_tut/pyramid_tut/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,11 @@ def main(global_config, **settings):
config.include('pyramid_debugtoolbar')
config.add_route('home', '/')
config.add_route('data', '/data')
config.add_route('data_func', '/data_func')
config.add_route('data_advanced', '/data_advanced')
config.add_route('data_yadcf', '/data_yadcf')
config.add_route('dt_110x', '/dt_110x')
config.add_route('dt_110x_func', '/dt_110x_func')
config.add_route('dt_110x_custom_column', '/dt_110x_custom_column')
config.add_route('dt_110x_basic_column_search',
'/dt_110x_basic_column_search')
Expand Down
26 changes: 22 additions & 4 deletions examples/pyramid_tut/pyramid_tut/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
Basic example: a User has one or many Addresses.
"""
import datetime

from sqlalchemy import Column, Date, ForeignKey, Integer, Unicode, func
from sqlalchemy import (Column, Date, ForeignKey,
Integer, Unicode, func, DateTime)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (backref, column_property, relationship,
scoped_session, sessionmaker)
Expand All @@ -15,7 +15,6 @@


class User(Base):

"""Define a User."""

__tablename__ = 'users'
Expand All @@ -24,6 +23,7 @@ class User(Base):
name = Column(Unicode, unique=True)
birthday = Column(Date)
address = relationship('Address', uselist=False, backref=backref('user'))
incomes = relationship('Income', backref=backref('user'))

# calculating age from date is a bit hacky with sqlite
age = column_property(
Expand All @@ -41,7 +41,6 @@ def __repr__(self):


class Address(Base):

"""Define an Address."""

__tablename__ = 'addresses'
Expand All @@ -57,3 +56,22 @@ def __unicode__(self):
def __repr__(self):
"""Give a unambiguous representation of an instance."""
return '<%s#%s>' % (self.__class__.__name__, self.id)


class Income(Base):
"""Define an Income."""

__tablename__ = 'incomes'

id = Column(Integer, primary_key=True)
amount = Column(Integer, nullable=False)
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
created_at = Column(DateTime, default=datetime.datetime.utcnow)

def __unicode__(self):
"""Give a readable representation of an instance."""
return '%s' % (self.id)

def __repr__(self):
"""Give a unambiguous representation of an instance."""
return '<%s#%s>' % (self.__class__.__name__, self.id)
13 changes: 9 additions & 4 deletions examples/pyramid_tut/pyramid_tut/scripts/initializedb.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
"""Initialize DB with fixtures."""
import os
import sys
import random
from datetime import date

import transaction
from pyramid.paster import get_appsettings, setup_logging
from pyramid.scripts.common import parse_vars
from sqlalchemy import engine_from_config

from ..models import Address, Base, DBSession, User
from ..models import Address, Base, DBSession, User, Income


def usage(argv):
Expand All @@ -33,11 +34,15 @@ def main(argv=sys.argv):

for i in range(30):
with transaction.manager:
address = Address(description='Address#2' + str(i).rjust(2, "0"))
DBSession.add(address)
user = User(name='User#1' + str(i).rjust(2, "0"),
birthday=date(1980 + i % 8,
i % 12 + 1,
i % 10 + 1))
user.address = address
user.address = Address(
description='Address#2' + str(i).rjust(2, "0"))
user.incomes = [
Income(amount=random.randint(0, 4000)),
Income(amount=random.randint(0, 4000)),
Income(amount=random.randint(0, 4000)),
]
DBSession.add(user)
1 change: 1 addition & 0 deletions examples/pyramid_tut/pyramid_tut/templates/base.jinja2
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="/dt_110x">basic</a></li>
<li><a href="/dt_110x_func">func (sum...)</a></li>
<li><a href="/dt_110x_custom_column">basic custom column</a></li>
<li><a href="/dt_110x_basic_column_search">basic column search</a></li>
<li><a href="/dt_110x_advanced_column_search">advanced column search</a></li>
Expand Down
35 changes: 35 additions & 0 deletions examples/pyramid_tut/pyramid_tut/templates/dt_110x_func.jinja2
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{% include 'base.jinja2' %}

{% block extra_stylesheets %}
<link href="https://cdn.datatables.net/1.10.10/css/jquery.dataTables.css" rel="stylesheet">
{% endblock %}

{% block content %}
<div class="row-fluid">
<div class="col-lg-12">
<h2>DataTables 1.10.x example: Users and their incomes.</h2>
<table id="dt_110x" class="table table-striped" cellspacing="0" width="100%">
<thead>
<tr>
<th>User name</th>
<th>Total incomes</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
{% endblock %}

{% block extra_javascripts %}
<script src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
var table = $('#dt_110x').DataTable({
"processing": false,
"serverSide": true,
"ajax": "{{ request.route_path('data_func') }}"
});
});
</script>
{% endblock %}
42 changes: 37 additions & 5 deletions examples/pyramid_tut/pyramid_tut/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from sqlalchemy import func
from datatables import ColumnDT, DataTables

from .models import Address, DBSession, User
from .models import Address, DBSession, User, Income


@view_config(route_name='home', renderer='templates/home.jinja2')
Expand All @@ -25,31 +25,38 @@ def dt_110x(request):
return {'project': 'dt_110x'}


@view_config(route_name='dt_110x_func',
renderer='templates/dt_110x_func.jinja2')
def dt_110x_func(request):
"""List users with DataTables >= 1.10.x."""
return {'project': 'dt_110x_func'}


@view_config(route_name='dt_110x_custom_column',
renderer='templates/dt_110x_custom_column.jinja2')
def dt_110x_custom_column(request):
"""Show a CRUD custom column"""
"""Show a CRUD custom column."""
return {'project': 'dt_110x_custom_column'}


@view_config(route_name='dt_110x_basic_column_search',
renderer='templates/dt_110x_basic_column_search.jinja2')
def dt_110x_basic_column_search(request):
"""Text based per column search"""
"""Text based per column search."""
return {'project': 'dt_110x_basic_column_search'}


@view_config(route_name='dt_110x_advanced_column_search',
renderer='templates/dt_110x_advanced_column_search.jinja2')
def dt_110x_advanced_column_search(request):
"""Advanced per column search"""
"""Advanced per column search."""
return {'project': 'dt_110x_advanced_column_search'}


@view_config(route_name='dt_110x_yadcf',
renderer='templates/dt_110x_yadcf.jinja2')
def dt_110x_yadcf(request):
"""Search with yadcf"""
"""Search with yadcf."""
return {'project': 'dt_110x_yadcf'}


Expand Down Expand Up @@ -133,6 +140,31 @@ def data_yadcf(request):
return rowTable.output_result()


@view_config(route_name='data_func', renderer='json')
def data_func(request):
"""Return server side data."""
# defining columns
columns = [
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Think we should add something on aggregated columns and searchability here

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, I re-reran the pypy case on travis (it failed before), now it passed.

ColumnDT(User.name),
ColumnDT(func.sum(Income.amount).label(
'Total incomes'), global_search=False),
]

# defining the initial query depending on your purpose
# - don't include any columns
# - if you need a join, also include a 'select_from'
query = DBSession.query().\
select_from(User).\
join(Income).\
group_by(User.name)

# instantiating a DataTable for the query and table needed
rowTable = DataTables(request.GET, query, columns)

# returns what is needed by DataTable
return rowTable.output_result()


conn_err_msg = """\
Pyramid is having a problem using your SQL database. The problem
might be caused by one of the following things:
Expand Down