Esempio n. 1
0
 def _process(self, response):
     """Given a response object, process it for JSON.
     """
     if not isinstance(response.body, basestring):
         response.body = json.dumps(response.body)
     response.headers['Content-Type'] = self.website.media_type_json
     return response
Esempio n. 2
0
 def _process(self, response):
     """Given a response object, process it for JSON.
     """
     if not isinstance(response.body, basestring):
         response.body = json.dumps(response.body)
     response.headers.set('Content-Type', self.website.json_content_type)
     return response
Esempio n. 3
0
def authorize(participant_id, pmt):
    """Given two unicodes, return a dict.

    This function attempts to authorize the credit card details referenced by
    pmt. If the attempt succeeds we cancel the transaction. If it fails we log
    the failure. Even for failure we keep the payment_method_token, we don't
    reset it to None/NULL. It's useful for loading the previous (bad) credit
    card info from Samurai in order to prepopulate the form.

    """
    typecheck(pmt, unicode, participant_id, unicode)
    transaction = Processor.authorize(pmt, '1.00', custom=participant_id)
    if transaction.errors:
        last_bill_result = json.dumps(transaction.errors)
        out = dict(transaction.errors)
    else:
        transaction.reverse()
        last_bill_result = ''
        out = {}
        
    STANDING = """\

    UPDATE participants
       SET payment_method_token=%s
         , last_bill_result=%s 
     WHERE id=%s

    """
    db.execute(STANDING, (pmt, last_bill_result, participant_id))
    return out
Esempio n. 4
0
 def create_github_review_issue(self):
     """POST to GitHub, and return the URL of the new issue.
     """
     api_url = "https://api.github.com/repos/{}/issues".format(self.review_repo)
     data = json.dumps(
         {
             "title": self.name,
             "body": "https://gratipay.com/{}/\n\n".format(self.slug)
             + "(This application will remain open for at least a week.)",
         }
     )
     out = ""
     try:
         r = requests.post(api_url, auth=self.review_auth, data=data)
         if r.status_code == 201:
             out = r.json()["html_url"]
         else:
             log(r.status_code)
             log(r.text)
         err = str(r.status_code)
     except:
         err = "eep"
     if not out:
         out = "https://github.com/gratipay/team-review/issues#error-{}".format(err)
     return out
Esempio n. 5
0
 def create_github_review_issue(self):
     """POST to GitHub, and return the URL of the new issue.
     """
     api_url = "https://api.github.com/repos/{}/issues".format(
         self.review_repo)
     data = json.dumps({
         "title":
         self.name,
         "body":
         "https://gratipay.com/{}/\n\n".format(self.slug) +
         "(This application will remain open for at least a week.)"
     })
     out = ''
     try:
         r = requests.post(api_url, auth=self.review_auth, data=data)
         if r.status_code == 201:
             out = r.json()['html_url']
         else:
             log(r.status_code)
             log(r.text)
         err = str(r.status_code)
     except:
         err = "eep"
     if not out:
         out = "https://github.com/gratipay/team-review/issues#error-{}".format(
             err)
     return out
Esempio n. 6
0
def authorize(participant_id, pmt):
    """Given two unicodes, return a dict.

    This function attempts to authorize the credit card details referenced by
    pmt. If the attempt succeeds we cancel the transaction. If it fails we log
    the failure. Even for failure we keep the payment_method_token, we don't
    reset it to None/NULL. It's useful for loading the previous (bad) credit
    card info from Samurai in order to prepopulate the form.

    """
    typecheck(pmt, unicode, participant_id, unicode)
    transaction = Processor.authorize(pmt, '1.00', custom=participant_id)
    if transaction.errors:
        last_bill_result = json.dumps(transaction.errors)
        out = dict(transaction.errors)
    else:
        transaction.reverse()
        last_bill_result = ''
        out = {}

    STANDING = """\

    UPDATE participants
       SET payment_method_token=%s
         , last_bill_result=%s 
     WHERE id=%s

    """
    db.execute(STANDING, (pmt, last_bill_result, participant_id))
    return out
def test_aspen_json_dumps_dumps():
    actual = json.dumps({"cheese": "puffs"})
    assert (
        actual
        == """{
    "cheese": "puffs"
}"""
    )
Esempio n. 8
0
 def __str__(self):
     data = self.data
     if self.type in (4, 5):
         data = json.dumps(data)
     return ":".join([ str(self.type)
                     , self.id
                     , self.endpoint
                     , data
                      ])
Esempio n. 9
0
 def __str__(self):
     data = self.data
     if self.type in (4, 5):
         data = json.dumps(data)
     return ":".join([ str(self.type)
                     , self.id
                     , self.endpoint
                     , data
                      ])
Esempio n. 10
0
def associate(participant_id, stripe_customer_id, tok):
    """Given three unicodes, return a dict.

    This function attempts to associate the credit card details referenced by
    tok with a Stripe Customer. If the attempt succeeds we cancel the
    transaction. If it fails we log the failure. Even for failure we keep the
    payment_method_token, we don't reset it to None/NULL. It's useful for
    loading the previous (bad) credit card info from Stripe in order to
    prepopulate the form.

    """
    typecheck( participant_id, unicode
             , stripe_customer_id, (unicode, None)
             , tok, unicode
              )


    # Load or create a Stripe Customer.
    # =================================

    if stripe_customer_id is None:
        customer = stripe.Customer.create()
        CUSTOMER = """\
                
                UPDATE participants 
                   SET stripe_customer_id=%s 
                 WHERE id=%s
                
        """
        db.execute(CUSTOMER, (customer.id, participant_id))
        customer.description = participant_id
        customer.save()  # HTTP call under here
    else:
        customer = stripe.Customer.retrieve(stripe_customer_id)



    # Associate the card with the customer.
    # =====================================
    # Handle errors. Return a unicode, a simple error message. If empty it
    # means there was no error. Yay! Store any raw error message from the
    # Stripe API in JSON format as last_bill_result. That may be helpful for
    # debugging at some point.

    customer.card = tok
    try:
        customer.save()
    except stripe.StripeError, err:
        last_bill_result = json.dumps(err.json_body)
        typecheck(last_bill_result, str)
        out = err.message
Esempio n. 11
0
def track(user_id, event, properties=None):
    if MIXPANEL_TOKEN is None:
        return

    typecheck(user_id, unicode, event, unicode, properties, (None, dict))
    if properties is None:
        properties = {}
    properties['token'] = MIXPANEL_TOKEN
    properties['distinct_id'] = user_id
    data = {"event": event, "properties": properties}
    data = json.dumps(data).encode("base64")
    response = session.get("http://api.mixpanel.com/track?data=" + data)

    # Read response.content to take advantage of keep-alive. See:
    # http://docs.python-requests.org/en/latest/user/advanced/#keep-alive
    response.content
Esempio n. 12
0
 def send_json(self, data):
     """Buffer a JSON message to be sent to the client.
     """
     if not isinstance(data, basestring):
         data = json.dumps(data)
     self.__send(4, data)
Esempio n. 13
0
 def render_content(self, context):
     if 'Content-type' not in context['response'].headers:
         response = context['response']
         website = context['website']
         response.headers['Content-type'] = website.media_type_json
     return json.dumps(eval(self.compiled, globals(), context))
Esempio n. 14
0
def test_aspen_json_dumps_dumps():
    actual = json.dumps({'cheese': 'puffs'})
    assert actual == '''{
Esempio n. 15
0
 def send_event(self, data):
     """Buffer an event message to be sent to the client.
     """
     if not isinstance(data, basestring):
         data = json.dumps(data)
     self.__send(5, data)
Esempio n. 16
0
def to_javascript(obj):
    """For when you want to inject an object into a <script> tag.
    """
    return json.dumps(obj).replace('</', '<\\/')
Esempio n. 17
0
def to_javascript(obj):
    """For when you want to inject an object into a <script> tag.
    """
    return json.dumps(obj).replace('</', '<\\/')
Esempio n. 18
0
 def send_event(self, data):
     """Buffer an event message to be sent to the client.
     """
     if not isinstance(data, basestring):
         data = json.dumps(data)
     self.__send(5, data)
Esempio n. 19
0
 def render_content(self, context):
     d = dict((k, v) for k, v in self.__dict__.items() if k[0] != '_')
     return json.dumps(d)
Esempio n. 20
0
def test_aspen_json_dumps_dumps():
    actual = json.dumps({'cheese': 'puffs'})
    assert actual == '''{
Esempio n. 21
0
 def send_json(self, data):
     """Buffer a JSON message to be sent to the client.
     """
     if not isinstance(data, basestring):
         data = json.dumps(data)
     self.__send(4, data)
def test_aspen_json_dumps_dumps():
    actual = json.dumps({'cheese': 'puffs'})
    assert actual == '{"cheese": "puffs"}', actual
Esempio n. 23
0
def charge(participant_id, pmt, amount):
    """Given two unicodes and a Decimal, return a boolean indicating success.

    This is the only place where we actually charge credit cards. Amount should
    be the nominal amount. We compute Gittip's fee in this function and add
    it to amount.

    """
    typecheck(pmt, (unicode, None), participant_id, unicode, amount,
              decimal.Decimal)

    if pmt is None:
        STATS = """\

            UPDATE paydays 
               SET npmt_missing = npmt_missing + 1
             WHERE ts_end='1970-01-01T00:00:00+00'::timestamptz
         RETURNING id
        
        """
        assert_one_payday(db.fetchone(STATS))
        return False

    # We have a purported payment method token. Try to use it.
    # ========================================================

    charge_amount = (amount + FEE[0]) * FEE[1]
    charge_amount = charge_amount.quantize(FEE[0], rounding=decimal.ROUND_UP)
    fee = charge_amount - amount
    log("Charging %s $%s + $%s fee = $%s." %
        (participant_id, amount, fee, charge_amount))
    transaction = Processor.purchase(pmt, charge_amount, custom=participant_id)

    # XXX If the power goes out at this point then Postgres will be out of sync
    # with Samurai. We'll have to resolve that manually be reviewing the
    # Samurai transaction log and modifying Postgres accordingly.

    with db.get_connection() as conn:
        cur = conn.cursor()

        if transaction.errors:
            last_bill_result = json.dumps(transaction.errors)
            amount = decimal.Decimal('0.00')

            STATS = """\

                UPDATE paydays 
                   SET npmt_failing = npmt_failing + 1
                 WHERE ts_end='1970-01-01T00:00:00+00'::timestamptz
             RETURNING id
            
            """
            cur.execute(STATS)
            assert_one_payday(cur.fetchone())

        else:
            last_bill_result = ''

            EXCHANGE = """\

            INSERT INTO exchanges
                   (amount, fee, participant_id)
            VALUES (%s, %s, %s)

            """
            cur.execute(EXCHANGE, (amount, fee, participant_id))

            STATS = """\

                UPDATE paydays 
                   SET nexchanges = nexchanges + 1
                     , exchange_volume = exchange_volume + %s
                     , exchange_fees_volume = exchange_fees_volume + %s
                 WHERE ts_end='1970-01-01T00:00:00+00'::timestamptz
             RETURNING id
            
            """
            cur.execute(STATS, (charge_amount, fee))
            assert_one_payday(cur.fetchone())

        # Update the participant's balance.
        # =================================
        # Credit card charges go immediately to balance, not to pending.

        RESULT = """\

        UPDATE participants
           SET last_bill_result=%s 
             , balance=(balance + %s)
         WHERE id=%s

        """
        cur.execute(RESULT, (last_bill_result, amount, participant_id))

        conn.commit()

    return not bool(last_bill_result)  # True indicates success
Esempio n. 24
0
                            , currency="USD"
                             )
        err = False
        log(msg + "succeeded.")
    except stripe.StripeError, err:
        log(msg + "failed: %s" % err.message)

    # XXX If the power goes out at this point then Postgres will be out of sync
    # with Stripe. We'll have to resolve that manually be reviewing the Stripe
    # transaction log and modifying Postgres accordingly.

    with db.get_connection() as conn:
        cur = conn.cursor()

        if err:
            last_bill_result = json.dumps(err.json_body)
            amount = decimal.Decimal('0.00')

            STATS = """\

                UPDATE paydays 
                   SET ncc_failing = ncc_failing + 1
                 WHERE ts_end='1970-01-01T00:00:00+00'::timestamptz
             RETURNING id
            
            """
            cur.execute(STATS)
            assert_one_payday(cur.fetchone())

        else:
            last_bill_result = ''
Esempio n. 25
0
def charge(participant_id, pmt, amount):
    """Given two unicodes and a Decimal, return a boolean indicating success.

    This is the only place where we actually charge credit cards. Amount should
    be the nominal amount. We compute Gittip's fee in this function and add
    it to amount.

    """
    typecheck( pmt, (unicode, None)
             , participant_id, unicode
             , amount, decimal.Decimal
              )

    if pmt is None:
        STATS = """\

            UPDATE paydays 
               SET npmt_missing = npmt_missing + 1
             WHERE ts_end='1970-01-01T00:00:00+00'::timestamptz
         RETURNING id
        
        """
        assert_one_payday(db.fetchone(STATS))
        return False 


    # We have a purported payment method token. Try to use it.
    # ========================================================

    charge_amount = (amount + FEE[0]) * FEE[1]
    charge_amount = charge_amount.quantize(FEE[0], rounding=decimal.ROUND_UP)
    fee = charge_amount - amount
    log("Charging %s $%s + $%s fee = $%s." 
       % (participant_id, amount, fee, charge_amount))
    transaction = Processor.purchase(pmt, charge_amount, custom=participant_id)

    # XXX If the power goes out at this point then Postgres will be out of sync
    # with Samurai. We'll have to resolve that manually be reviewing the
    # Samurai transaction log and modifying Postgres accordingly.

    with db.get_connection() as conn:
        cur = conn.cursor()

        if transaction.errors:
            last_bill_result = json.dumps(transaction.errors)
            amount = decimal.Decimal('0.00')

            STATS = """\

                UPDATE paydays 
                   SET npmt_failing = npmt_failing + 1
                 WHERE ts_end='1970-01-01T00:00:00+00'::timestamptz
             RETURNING id
            
            """
            cur.execute(STATS)
            assert_one_payday(cur.fetchone())

        else:
            last_bill_result = ''

            EXCHANGE = """\

            INSERT INTO exchanges
                   (amount, fee, participant_id)
            VALUES (%s, %s, %s)

            """
            cur.execute(EXCHANGE, (amount, fee, participant_id))

            STATS = """\

                UPDATE paydays 
                   SET nexchanges = nexchanges + 1
                     , exchange_volume = exchange_volume + %s
                     , exchange_fees_volume = exchange_fees_volume + %s
                 WHERE ts_end='1970-01-01T00:00:00+00'::timestamptz
             RETURNING id
            
            """
            cur.execute(STATS, (charge_amount, fee))
            assert_one_payday(cur.fetchone())


        # Update the participant's balance.
        # =================================
        # Credit card charges go immediately to balance, not to pending.

        RESULT = """\

        UPDATE participants
           SET last_bill_result=%s 
             , balance=(balance + %s)
         WHERE id=%s

        """
        cur.execute(RESULT, (last_bill_result, amount, participant_id))

        conn.commit()

    return not bool(last_bill_result)  # True indicates success
Esempio n. 26
0
def test_aspen_json_dumps_dumps():
    actual = json.dumps({'cheese': 'puffs'})
    assert actual == '{"cheese": "puffs"}', actual