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

Moving to Python3 #313

Merged
merged 7 commits into from
Feb 10, 2020
Merged
Show file tree
Hide file tree
Changes from 2 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: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
language: python
python:
- 2.7
- 3.7
cache:
directories:
- $HOME/.cache/pip
Expand Down
4 changes: 2 additions & 2 deletions boxoffice/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

from . import extapi, views # NOQA
from boxoffice.models import db, User, Item, Price, DiscountPolicy, DiscountCoupon, ItemCollection, Organization, Category, Invoice # noqa
from siteadmin import OrganizationModelView, DiscountCouponModelView, InvoiceModelView # noqa
from .siteadmin import OrganizationModelView, DiscountCouponModelView, InvoiceModelView # noqa


# Configure the app
Expand All @@ -51,7 +51,7 @@
# This is a temporary solution for an admin interface, only
# to be used until the native admin interface is ready.
try:
admin = Admin(app, name=u"Boxoffice Admin", template_mode='bootstrap3', url='/siteadmin')
admin = Admin(app, name="Boxoffice Admin", template_mode='bootstrap3', url='/siteadmin')
admin.add_view(OrganizationModelView(Organization, db.session))
admin.add_view(DiscountCouponModelView(DiscountCoupon, db.session))
admin.add_view(InvoiceModelView(Invoice, db.session))
Expand Down
2 changes: 1 addition & 1 deletion boxoffice/extapi/razorpay.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def get_settled_transactions(date_range, tz=None):
'receivable_amount', 'settlement_amount', 'buyer_fullname']
# Nested list of dictionaries consisting of transaction details
rows = []
external_transaction_msg = u"Transaction external to Boxoffice. Credited directly to Razorpay?"
external_transaction_msg = "Transaction external to Boxoffice. Credited directly to Razorpay?"

for settled_transaction in settled_transactions:
if settled_transaction['type'] == 'settlement':
Expand Down
4 changes: 2 additions & 2 deletions boxoffice/forms/discount.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class DiscountPolicyForm(forms.Form):
validators=[forms.validators.DataRequired(__("Please specify a discount title")),
forms.validators.Length(max=250)], filters=[forms.filters.strip()])
discount_type = forms.RadioField(__("Discount type"),
choices=DISCOUNT_TYPE.items(), coerce=int, default=DISCOUNT_TYPE.COUPON)
choices=list(DISCOUNT_TYPE.items()), coerce=int, default=DISCOUNT_TYPE.COUPON)
is_price_based = forms.RadioField(__("Price based discount"),
coerce=getbool, default=1, choices=[
(1, __("Special price discount")),
Expand Down Expand Up @@ -79,7 +79,7 @@ class DiscountPriceForm(forms.Form):
validators=[forms.validators.DataRequired(__("Please specify an amount"))])
currency = forms.RadioField(__("Currency"),
validators=[forms.validators.DataRequired(__("Please select the currency"))],
choices=CURRENCY.items(), default=CURRENCY.INR)
choices=list(CURRENCY.items()), default=CURRENCY.INR)
start_at = forms.DateTimeField(__("Price start date"),
validators=[forms.validators.DataRequired(__("Please specify a start date and time"))],
naive=False)
Expand Down
2 changes: 1 addition & 1 deletion boxoffice/forms/order.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def trim(length):
field = forms.StringField(__("Some field"), filters=[trim(25)])
"""
def _inner(data):
return unicode(data[0:length])
return data[0:length]
return _inner


Expand Down
2 changes: 1 addition & 1 deletion boxoffice/forms/price.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ class PriceForm(forms.Form):
end_at = forms.DateTimeField(__("End date & time"),
validators=[
forms.validators.DataRequired(__("Please specify an end date & time")),
forms.validators.GreaterThan('start_at', __(u"The price can’t end before it starts"))
forms.validators.GreaterThan('start_at', __("The price can’t end before it starts"))
],
naive=False)
4 changes: 2 additions & 2 deletions boxoffice/models/invoice.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,9 @@ def __init__(self, *args, **kwargs):
country_code = kwargs.get('country_code')
if not country_code:
# Default to India
country_code = u'IN'
country_code = 'IN'
if not organization:
raise ValueError(u"Invoice MUST be initialized with an organization")
raise ValueError("Invoice MUST be initialized with an organization")
self.invoiced_at = utcnow()
self.fy_start_at, self.fy_end_at = get_fiscal_year(country_code, self.invoiced_at)
self.invoice_no = gen_invoice_no(organization, country_code, self.invoiced_at)
Expand Down
12 changes: 6 additions & 6 deletions boxoffice/models/item.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class Item(BaseScopedNameMixin, db.Model):
__uuid_primary_key__ = True
__table_args__ = (db.UniqueConstraint('item_collection_id', 'name'),)

description = MarkdownColumn('description', default=u'', nullable=False)
description = MarkdownColumn('description', default='', nullable=False)
seq = db.Column(db.Integer, nullable=False)

item_collection_id = db.Column(None, db.ForeignKey('item_collection.id'), nullable=False)
Expand Down Expand Up @@ -154,7 +154,7 @@ def get_availability(cls, item_ids):
item_tups = db.session.query(cls.id, cls.title, cls.quantity_total, db.func.count(cls.id)).join(LineItem).filter(
LineItem.item_id.in_(item_ids), LineItem.status == LINE_ITEM_STATUS.CONFIRMED).group_by(cls.id).all()
for item_tup in item_tups:
items_dict[unicode(item_tup[0])] = item_tup[1:]
items_dict[item_tup[0]] = item_tup[1:]
return items_dict

def demand_curve(self):
Expand Down Expand Up @@ -190,7 +190,7 @@ class Price(BaseScopedNameMixin, db.Model):
end_at = db.Column(db.TIMESTAMP(timezone=True), nullable=False)

amount = db.Column(db.Numeric, default=Decimal(0), nullable=False)
currency = db.Column(db.Unicode(3), nullable=False, default=u'INR')
currency = db.Column(db.Unicode(3), nullable=False, default='INR')

__roles__ = {
'price_owner': {
Expand All @@ -212,8 +212,8 @@ def discount_policy_title(self):
def tense(self):
now = utcnow()
if self.end_at < now:
return u"past"
return "past"
elif self.start_at > now:
return u"upcoming"
return "upcoming"
else:
return u"current"
return "current"
4 changes: 2 additions & 2 deletions boxoffice/models/item_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ class ItemCollection(BaseScopedNameMixin, db.Model):
__uuid_primary_key__ = True
__table_args__ = (db.UniqueConstraint('organization_id', 'name'),)

description = MarkdownColumn('description', default=u'', nullable=False)
description = MarkdownColumn('description', default='', nullable=False)

organization_id = db.Column(db.Integer, db.ForeignKey('organization.id'), nullable=False)
organization = db.relationship(Organization, backref=db.backref('item_collections', cascade='all, delete-orphan'))
parent = db.synonym('organization')
tax_type = db.Column(db.Unicode(80), nullable=True, default=u'GST')
tax_type = db.Column(db.Unicode(80), nullable=True, default='GST')
# ISO 3166-2 code. Eg: KA for Karnataka
place_supply_state_code = db.Column(db.Unicode(3), nullable=True)
# ISO country code
Expand Down
8 changes: 4 additions & 4 deletions boxoffice/models/line_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,9 @@ def calculate(cls, line_items, recalculate=False, coupons=[]):
base_amount = item.current_price().amount if item.is_available else None
line_item_id = None

if not item_line_items.get(unicode(item.id)):
item_line_items[unicode(item.id)] = []
item_line_items[unicode(item.id)].append(make_ntuple(item_id=item.id,
if not item_line_items.get(str(item.id)):
item_line_items[str(item.id)] = []
item_line_items[str(item.id)].append(make_ntuple(item_id=item.id,
base_amount=base_amount, line_item_id=line_item_id))

for item_id in item_line_items.keys():
Expand Down Expand Up @@ -241,7 +241,7 @@ def counts_per_date_per_item(item_collection, user_tz):
"""
date_item_counts = {}
for item in item_collection.items:
item_id = unicode(item.id)
item_id = str(item.id)
item_results = db.session.query('date', 'count').from_statement(
db.text('''SELECT DATE_TRUNC('day', line_item.ordered_at AT TIME ZONE :timezone)::date as date, count(line_item.id) AS count
FROM line_item WHERE item_id = :item_id AND status = :status
Expand Down
14 changes: 7 additions & 7 deletions boxoffice/models/order.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,11 +133,11 @@ class OrderSession(BaseMixin, db.Model):
host = db.Column(db.UnicodeText, nullable=True)

# Google Analytics parameters
utm_source = db.Column(db.Unicode(250), nullable=False, default=u'', index=True)
utm_medium = db.Column(db.Unicode(250), nullable=False, default=u'', index=True)
utm_term = db.Column(db.Unicode(250), nullable=False, default=u'')
utm_content = db.Column(db.Unicode(250), nullable=False, default=u'')
utm_id = db.Column(db.Unicode(250), nullable=False, default=u'', index=True)
utm_campaign = db.Column(db.Unicode(250), nullable=False, default=u'', index=True)
utm_source = db.Column(db.Unicode(250), nullable=False, default='', index=True)
utm_medium = db.Column(db.Unicode(250), nullable=False, default='', index=True)
utm_term = db.Column(db.Unicode(250), nullable=False, default='')
utm_content = db.Column(db.Unicode(250), nullable=False, default='')
utm_id = db.Column(db.Unicode(250), nullable=False, default='', index=True)
utm_campaign = db.Column(db.Unicode(250), nullable=False, default='', index=True)
# Google click id (for AdWords)
gclid = db.Column(db.Unicode(250), nullable=False, default=u'', index=True)
gclid = db.Column(db.Unicode(250), nullable=False, default='', index=True)
4 changes: 2 additions & 2 deletions boxoffice/models/payment.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,11 +139,11 @@ def item_collection_net_sales(self):


class CURRENCY(LabeledEnum):
INR = (u"INR", __("INR"))
INR = ("INR", __("INR"))


class CURRENCY_SYMBOL(LabeledEnum):
INR = (u'INR', u'₹')
INR = ('INR', '₹')


def calculate_weekly_refunds(item_collection_ids, user_tz, year):
Expand Down
4 changes: 2 additions & 2 deletions boxoffice/models/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def get_fiscal_year(jurisdiction, dt):
Example::
get_fiscal_year('IN', utcnow())
"""
if jurisdiction.lower() == u'in':
if jurisdiction.lower() == 'in':
if dt.month < 4:
start_year = dt.year - 1
else:
Expand All @@ -84,6 +84,6 @@ def get_fiscal_year(jurisdiction, dt):
fy_start = datetime(start_year, 4, 1)
# ends on April 1 XXXX + 1
fy_end = datetime(start_year + 1, 4, 1)
timezone = u'Asia/Kolkata'
timezone = 'Asia/Kolkata'
return (naive_to_utc(fy_start, timezone), naive_to_utc(fy_end, timezone))
return (naive_to_utc(datetime(dt.year, 1, 1)), naive_to_utc(datetime(dt.year + 1, 1, 1)))
14 changes: 7 additions & 7 deletions boxoffice/views/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,23 +50,23 @@ def org_revenue(organization):
check_api_access(organization.details.get('access_token'))

if not request.args.get('year'):
return api_error(message=_(u"Missing year"), status_code=400)
return api_error(message=_("Missing year"), status_code=400)

if not request.args.get('timezone'):
return api_error(message=_(u"Missing timezone"), status_code=400)
return api_error(message=_("Missing timezone"), status_code=400)

if request.args.get('timezone') not in pytz.common_timezones:
return api_error(message=_(u"Unknown timezone. Timezone is case-sensitive"), status_code=400)
return api_error(message=_("Unknown timezone. Timezone is case-sensitive"), status_code=400)

item_collection_ids = [item_collection.id for item_collection in organization.item_collections]
year = int(request.args.get('year'))
user_timezone = request.args.get('timezone')

if getbool(request.args.get('refund')):
result = calculate_weekly_refunds(item_collection_ids, user_timezone, year).items()
doc = _(u"Refunds per week for {year}".format(year=year))
result = list(calculate_weekly_refunds(item_collection_ids, user_timezone, year).items())
doc = _("Refunds per week for {year}".format(year=year))
else:
# sales includes confirmed and cancelled line items
result = calculate_weekly_sales(item_collection_ids, user_timezone, year).items()
doc = _(u"Revenue per week for {year}".format(year=year))
result = list(calculate_weekly_sales(item_collection_ids, user_timezone, year).items())
doc = _("Revenue per week for {year}".format(year=year))
return api_success(result=result, doc=doc, status_code=200)
12 changes: 6 additions & 6 deletions boxoffice/views/admin_category.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,16 @@ def jsonify_new_category(data_dict):
item_collection = data_dict['item_collection']
category_form = CategoryForm(parent=item_collection)
if request.method == 'GET':
return jsonify(form_template=render_form(form=category_form, title=u"New item", submit=u"Create", with_chrome=False))
return jsonify(form_template=render_form(form=category_form, title="New item", submit="Create", with_chrome=False))
if category_form.validate_on_submit():
category = Category(item_collection=item_collection)
category_form.populate_obj(category)
if not category.name:
category.make_name()
db.session.add(category)
db.session.commit()
return api_success(result={'category': dict(category.current_access())}, doc=_(u"New category created"), status_code=201)
return api_error(message=_(u"There was a problem with creating the item"), errors=category_form.errors, status_code=400)
return api_success(result={'category': dict(category.current_access())}, doc=_("New category created"), status_code=201)
return api_error(message=_("There was a problem with creating the item"), errors=category_form.errors, status_code=400)


@app.route('/admin/ic/<ic_id>/category/new', methods=['GET', 'POST'])
Expand All @@ -41,12 +41,12 @@ def jsonify_edit_category(data_dict):
category = data_dict['category']
category_form = CategoryForm(obj=category)
if request.method == 'GET':
return jsonify(form_template=render_form(form=category_form, title=u"Edit category", submit=u"Update", with_chrome=False))
return jsonify(form_template=render_form(form=category_form, title="Edit category", submit="Update", with_chrome=False))
if category_form.validate_on_submit():
category_form.populate_obj(category)
db.session.commit()
return api_success(result={'category': dict(category.current_access())}, doc=_(u"Category was updated"), status_code=201)
return api_error(message=_(u"There was a problem with updating the category"), errors=category_form.errors, status_code=400)
return api_success(result={'category': dict(category.current_access())}, doc=_("Category was updated"), status_code=201)
return api_error(message=_("There was a problem with updating the category"), errors=category_form.errors, status_code=400)


@app.route('/admin/ic/<ic_id>/category/<category_id>/edit', methods=['GET', 'POST'])
Expand Down
Loading