コード例 #1
0
ファイル: snake.py プロジェクト: sabren/workshop
def wraphtml(html, title):
    """
    I wrap the html that textile produces with a nice template.
    """
    import handy
    return ("\n".join([
        handy.trim(
        '''
        <?xml version="1.0"?
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
        <html>
        <head>
        <title>%s</title>
        <link rel="stylesheet" href="/stylesheet.css">
        </head>
        <body>
        ''') % title,

        cleanhtml(html),
        
        handy.trim(
        '''
        </body>
        </html>
        ''')]))
コード例 #2
0
ファイル: wks.py プロジェクト: tangentstorm/workshop
def addToModel(className, tableName=None):
    """
    Adds a class to the model.
    """
    appname = currentAppName()
    if not className[0] in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
        raise SystemExit("class must start with uppercase letter")

    if modelClassExists(className):
        raise SystemExit("class %s.model.%s already exists." %
                         (appname, className))

    tableName = tableName or className.lower()
    addToSQL(
        trim('''
        CREATE TABLE %s (
            ID INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY
        );
        ''') % tableName)

    with outstream("test/%sTest.py" % className) as out:
        out(
            trim("""
            from %s import model
            import unittest
            from strongbox import *
            
            class %sTest(unittest.TestCase):
        
                def setUp(self):
                    pass

                def test_constructor(self):
                    obj = %s()

                def tearDown(self):
                    pass

            if __name__ == '__main__':
                unittest.main()
            """) % (appname, className, className))

    with outstream("model/%s.py" % className) as out:
        out(
            trim("""
            from strongbox import *
            from pytypes import *
            import model
            
            class %s(Strongbox):
                ID = attr(long)
            """) % className)

    with outstream("model/__init__.py", "a") as out:
        out(
            trim("""
            from %s import %s
            """ % (className, className)))

    addToSchema(className, repr(tableName))
コード例 #3
0
def handleError(msg, user=None):
    RES.write(
        handy.trim('''
        <html>
        <title>error</title>
        <style type="text/css">
        body, p, table {
            font-family: verdana, arial, helvetica;
            font-size: 10pt;
        }
        body {
            background: #eeeeee;
        }
        h1 {
           font-size: 10pt;
           background: gold;
           padding-left: 10px;
        }
        p { padding-bottom: 10px;
            padding-left: 10px;
            margin: 0px; }
        </style>
        </head>
        <div style="background: white">
          <h1>error</h1>
          <p>%s</p>
          <p style="color: gray">
           An email has been sent to the administrator.<br/>
           Please try back in a little while.
          </p>
        </div>
        ''') % msg)
    trace = "".join(
        traceback.format_exception(sys.exc_type, sys.exc_value,
                                   sys.exc_traceback))
    trace += "\n"
    trace += "query: %s\n" % str(REQ.query)
    trace += "form: %s\n" % str(REQ.form)
    trace += "session: %s\n" % str(SESS)
    if TEST_MODE:
        RES.write("<pre>")
        RES.write(trace)
        RES.write("</pre>")
    RES.write("</html>")
    try:
        uname = getattr(user, "username", "(unknown)")
        handy.sendmail((handy.trim("""
            To: [email protected]
            From: [email protected]
            Subject: error in control panel

            user: %s
            this error was trapped with message:
            %s
            ------------------------------------
            """) % (msg, uname)) + trace)
    except:
        raise
        pass  # oh well.
    raise Finished
コード例 #4
0
ファイル: .weblib.py プロジェクト: sabren/cornerops-svn
def handleError(msg, user=None):
    RES.write(handy.trim(
        '''
        <html>
        <title>error</title>
        <style type="text/css">
        body, p, table {
            font-family: verdana, arial, helvetica;
            font-size: 10pt;
        }
        body {
            background: #eeeeee;
        }
        h1 {
           font-size: 10pt;
           background: gold;
           padding-left: 10px;
        }
        p { padding-bottom: 10px;
            padding-left: 10px;
            margin: 0px; }
        </style>
        </head>
        <div style="background: white">
          <h1>error</h1>
          <p>%s</p>
          <p style="color: gray">
           An email has been sent to the administrator.<br/>
           Please try back in a little while.
          </p>
        </div>
        ''') % msg)
    trace = "".join(traceback.format_exception(
        sys.exc_type, sys.exc_value, sys.exc_traceback))
    trace += "\n"
    trace += "query: %s\n" % str(REQ.query)
    trace += "form: %s\n" % str(REQ.form)
    trace += "session: %s\n" % str(SESS)
    if TEST_MODE:        
        RES.write("<pre>")
        RES.write(trace)
        RES.write("</pre>")
    RES.write("</html>")
    try:
        uname = getattr(user, "username", "(unknown)")
        handy.sendmail((handy.trim(
            """
            To: [email protected]
            From: [email protected]
            Subject: error in control panel

            user: %s
            this error was trapped with message:
            %s
            ------------------------------------
            """) % (msg, uname)) + trace)
    except:
        raise
        pass # oh well. 
    raise Finished
コード例 #5
0
ファイル: admin.py プロジェクト: sabren/cornerops-svn
    def invoke(self, _clerk, signupID, account, plan, server, cycLen, domains):
            
        p = _clerk.fetch(Signup, ID=long(signupID))
        p.plan = plan # @TODO: capture plan in cornerhost signups
        p.username = account
        p.cycLen = cycLen

        #try:
        pw = self.makeUser(server, p)
        #except xmlrpclib.Fault, f:
        #    print >> self, "XMLRPC fault: %s" % f.faultString
        #    return 

        ## now the account in duckbill:
        u = _clerk.fetch(User, username=account)
        u.account = p.toDuckbill()
        _clerk.store(u)

        p.status="filled"
        _clerk.store(p)

        doms = [item.strip() for item in domains.split() if item.strip()]
        g = NewSiteGrunt(_clerk, u, sabrenOK = True)
        for dname in doms:
            g.newSite(dname)
            
        ## show the password!
        #@TODO: make this do something sensible instead
        assert 0, "password for %s is %s" % (account, pw)
        return Model(message=trim(
            '''
            <p>password for %s is %s<br/>
            <a href="admin.app?action=jump&jumpto=%s">see user</a></p>
            ''' % (account, pw, username)))
コード例 #6
0
ファイル: weblib.py プロジェクト: sabren/appengine-workshop
 def errHeaders(self):
     return trim(
         '''
         Status: 500 Internal Server Error
         Content-Type: text/html; charset=utf-8
         
         ''')
コード例 #7
0
ファイル: narr2html.py プロジェクト: sabren/workshop
def test_getChunks(test):
    chunks = list(
        getChunks(
            trim(
                '''
        """
        <title>abc</title>
        """
        import this
        pass
        # * headline 1
        # ** headline 2
        """
        here\'s some text
        more text
        """
        pass
        assert 1 + 2 == 3
        '''
            )
        )
    )
    # print [(chunk[0].__name__, chunk[1])  for chunk in chunks]
    modes = [chunk[0].__name__ for chunk in chunks]
    test.assertEquals(modes, [x.__name__ for x in [TITLE, CODE, CODE, HEAD, HEAD, TEXT, TEXT, CODE, CODE]])
コード例 #8
0
ファイル: ApplicationTest.py プロジェクト: souca/sixthdev
 def render_list_user(self, model):
     template = zebra.old_parse(handy.trim(
         """
         * for each:
             {:name:}
         """))
     return template.fetch(model)
コード例 #9
0
 def test__main__(self):
     e = Engine(script=trim("""
         if __name__=='__main__':
            print >> RES, 'sup?'
         """))
     e.run()
     assert e.response.buffer == "sup?\n"
コード例 #10
0
    def test_on_exit(self):
        """
        engine.do_on_exit(XXX) should remember XXX and call it at end of page.
        """
        def nothing():
            pass

        eng = Engine(script="")
        assert len(eng._exitstuff)==0, \
               "exitstuff not empty by default"

        eng.do_on_exit(nothing)
        assert len(eng._exitstuff)==1, \
               "do_on_exit doesn't add to exitstuff"

        eng._exitstuff = []

        eng = Engine(script=trim("""
            # underscores on next line are just for emacs.. (trim strips them)
        ___ def cleanup():   
                print >> RES, 'wokka wokka wokka'
            ENG.do_on_exit(cleanup)
            """))
        eng.execute(eng.script)
        assert len(eng._exitstuff) == 1, \
               "didn't register exit function: %s" % str(eng._exitstuff)
        eng._exit()
        assert eng.response.buffer=='wokka wokka wokka\n', \
               "got wrong response: %s" % eng.response.buffer
コード例 #11
0
    def invoke(self, _clerk, signupID, account, plan, server, cycLen, domains):

        p = _clerk.fetch(Signup, ID=long(signupID))
        p.plan = plan  # @TODO: capture plan in cornerhost signups
        p.username = account
        p.cycLen = cycLen

        #try:
        pw = self.makeUser(server, p)
        #except xmlrpclib.Fault, f:
        #    print >> self, "XMLRPC fault: %s" % f.faultString
        #    return

        ## now the account in duckbill:
        u = _clerk.fetch(User, username=account)
        u.account = p.toDuckbill()
        _clerk.store(u)

        p.status = "filled"
        _clerk.store(p)

        doms = [item.strip() for item in domains.split() if item.strip()]
        g = NewSiteGrunt(_clerk, u, sabrenOK=True)
        for dname in doms:
            g.newSite(dname)

        ## show the password!
        #@TODO: make this do something sensible instead
        assert 0, "password for %s is %s" % (account, pw)
        return Model(message=trim('''
            <p>password for %s is %s<br/>
            <a href="admin.app?action=jump&jumpto=%s">see user</a></p>
            ''' % (account, pw, username)))
コード例 #12
0
ファイル: weblib.py プロジェクト: sabren/appengine-workshop
    def test_on_exit(self):
        """
        engine.do_on_exit(XXX) should remember XXX and call it at end of page.
        """
        def nothing():
            pass
        
        eng = Engine(script="")
        assert len(eng._exitstuff)==0, \
               "exitstuff not empty by default"
        
        eng.do_on_exit(nothing)
        assert len(eng._exitstuff)==1, \
               "do_on_exit doesn't add to exitstuff" 

        eng._exitstuff = []
        
        eng = Engine(script=trim(
            """
            # underscores on next line are just for emacs.. (trim strips them)
        ___ def cleanup():   
                print >> RES, 'wokka wokka wokka'
            ENG.do_on_exit(cleanup)
            """))
        eng.execute(eng.script)
        assert len(eng._exitstuff) == 1, \
               "didn't register exit function: %s" % str(eng._exitstuff)
        eng._exit()
        assert eng.response.buffer=='wokka wokka wokka\n', \
               "got wrong response: %s" % eng.response.buffer
コード例 #13
0
ファイル: weblib.py プロジェクト: sabren/appengine-workshop
 def test__main__(self):
     e = Engine(script=trim(
         """
         if __name__=='__main__':
            print >> RES, 'sup?'
         """))
     e.run()
     assert e.response.buffer =="sup?\n"
コード例 #14
0
ファイル: weblib.py プロジェクト: sabren/appengine-workshop
 def test_assert(self):
     out = self.wrap("assert 0, 'the assertion failed'")
     self.assertEquals(out.getHeaders(), trim(
         '''
         Status: 500 Internal Server Error
         Content-Type: text/html; charset=utf-8
         
         '''))
     assert out.getBody().count('the assertion failed'), out.getBody()
コード例 #15
0
ファイル: weblib.py プロジェクト: sabren/appengine-workshop
    def test_except(self):
        out = self.wrap("raise hell")
        self.assertEquals(out.getHeaders(), trim(
            '''
            Status: 500 Internal Server Error
            Content-Type: text/html; charset=utf-8

            ''')) 
        assert out.getBody().count('NameError'), out.getBody()
コード例 #16
0
ファイル: autobill.py プロジェクト: sabren/cornerops-svn
def emailCustomer(acc, result, details, lastfour, amount):
    model = {}
    model["email"] = acc.email
    model["fname"] = acc.fname
    model["brand"] = acc.brand
    model["account"] = acc.account
    model["lastfour"] = lastfour
    model["amount"] = amount
    model["result"] = result
    model["details"] = details
    model["signature"] = open("/home/sei/.signature").read()

    model['fromAddr'] = FROM
    message = handy.trim("""
        From: %(fromAddr)s
        To: %(email)s
        BCC: %(fromAddr)s
        Subject: credit card denied

        Hi %(fname)s,

        Your %(brand)s account (username %(account)s)
        is set up for automatic billing, and my system
        just attempted to post a charge of $%(amount)s
        to your credit card - the one with the number
        ending in %(lastfour)s. The bank responded
        with the following error:

            %(result)s
            %(details)s

        Could you please look into this? If you would like
        to use a different means of payment or enter a
        different card, you can do so here:

            http://%(brand)s.com/payment/

        If the only thing that has changed is the expiration
        date on your card, you can just email me the new
        date.

        Thanks!

        %(signature)s
        """) % model

    action = "e"
    while 1:
        if action == "e":
            message = handy.edit(message)
        elif action == "s":
            handy.sendmail(message)
            break
        elif action == "a":
            break
        action = raw_input("[e]dit, [a]bandon, [s]end? ")
コード例 #17
0
 def errFooter(self):
     return trim('''
         <hr/>
         <a href="https://secure.sabren.com/trac/workshop/">weblib</a>
         (c) copyright 2000-2008
         <a href="http://www.sabren.com/">Sabren Enterprises, Inc</a>. 
         All rights reserved.
         </body>
         </html>
         ''')
コード例 #18
0
 def test_globals(self):
     myscript = trim("""
         import weblib
         assert isinstance(REQ, weblib.Request)
         assert isinstance(RES, weblib.Response)
         assert isinstance(ENG, weblib.Engine)
         """)
     eng = Engine(script=myscript)
     eng.run()
     assert eng.result == Engine.SUCCESS, eng.error
コード例 #19
0
 def test_assert(self):
     out = self.wrap("assert 0, 'the assertion failed'")
     self.assertEquals(
         out.getHeaders(),
         trim('''
         Status: 500 Internal Server Error
         Content-Type: text/html; charset=utf-8
         
         '''))
     assert out.getBody().count('the assertion failed'), out.getBody()
コード例 #20
0
ファイル: OutputDecorator.py プロジェクト: souca/sixthdev
 def errFooter(self):
     return trim('''
         <hr>
         <a href="http://www.tangentcode.com/">weblib</a>
         (c) copyright 2000-2003 
         <a href="http://www.sabren.com/">Sabren Enterprises, Inc</a>. 
         All rights reserved.
         </body>
         </html>
         ''')
コード例 #21
0
    def test_except(self):
        out = self.wrap("raise hell")
        self.assertEquals(
            out.getHeaders(),
            trim('''
            Status: 500 Internal Server Error
            Content-Type: text/html; charset=utf-8

            '''))
        assert out.getBody().count('NameError'), out.getBody()
コード例 #22
0
 def test_globals(self):
     myscript = trim("""
         import weblib
         assert REQ.__class__.__name__ == 'Request', 'req'
         assert RES.__class__.__name__ == 'Response', 'res'
         assert ENG.__class__.__name__ == 'Engine', 'eng'
         """)
     eng = Engine(script=myscript)
     eng.run()
     assert eng.error is None, eng.error
     self.assertEquals(Engine.SUCCESS, eng.result)
コード例 #23
0
ファイル: EngineTest.py プロジェクト: elmore/sixthdev
 def test_globals(self):
     myscript = trim(
         """
         import weblib
         assert isinstance(REQ, weblib.Request)
         assert isinstance(RES, weblib.Response)
         assert isinstance(ENG, weblib.Engine)
         """)
     eng = Engine(script=myscript)
     eng.run()
     assert eng.result == Engine.SUCCESS, eng.error
コード例 #24
0
ファイル: OutputDecorator.py プロジェクト: elmore/sixthdev
 def errFooter(self):
     return trim(
         '''
         <hr>
         <a href="http://www.tangentcode.com/">weblib</a>
         (c) copyright 2000-2003 
         <a href="http://www.sabren.com/">Sabren Enterprises, Inc</a>. 
         All rights reserved.
         </body>
         </html>
         ''')
コード例 #25
0
ファイル: weblib.py プロジェクト: sabren/appengine-workshop
 def errFooter(self):
     return trim(
         '''
         <hr/>
         <a href="https://secure.sabren.com/trac/workshop/">weblib</a>
         (c) copyright 2000-2008
         <a href="http://www.sabren.com/">Sabren Enterprises, Inc</a>. 
         All rights reserved.
         </body>
         </html>
         ''')
コード例 #26
0
ファイル: weblib.py プロジェクト: sabren/appengine-workshop
 def test_globals(self):
     myscript = trim(
         """
         import weblib
         assert REQ.__class__.__name__ == 'Request', 'req'
         assert RES.__class__.__name__ == 'Response', 'res'
         assert ENG.__class__.__name__ == 'Engine', 'eng'
         """)
     eng = Engine(script=myscript)
     eng.run()
     assert eng.error is None, eng.error
     self.assertEquals(Engine.SUCCESS, eng.result)
コード例 #27
0
 def test_form(self):
     weblib.MYFORM = {"a": "bcd"}
     try:
         myscript = trim("""
             import weblib
             assert REQ.form is weblib.MYFORM, \
                 'request uses wrong form'
             """)
         req = self.builder.build(form=weblib.MYFORM)
         eng = weblib.Engine(request=req, script=myscript)
         eng.run()
         assert eng.result == eng.SUCCESS, eng.result
     finally:
         del weblib.MYFORM
コード例 #28
0
def wraphtml(html, title):
    """
    I wrap the html that textile produces with a nice template.
    """
    import handy
    return ("\n".join([
        handy.trim('''
        <?xml version="1.0"?
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
        <html>
        <head>
        <title>%s</title>
        <link rel="stylesheet" href="/stylesheet.css">
        </head>
        <body>
        ''') % title,
        cleanhtml(html),
        handy.trim('''
        </body>
        </html>
        ''')
    ]))
コード例 #29
0
 def test_print(self):
     import sys, StringIO
     eng = Engine(script=trim("""
         import weblib
         print >> RES, 'this should show'
         print 'this should not'
         """))
     tempout, sys.stdout = sys.stdout, StringIO.StringIO()
     eng.run()
     sys.stdout, tempout = tempout, sys.stdout
     assert eng.response.buffer == "this should show\n", \
            "doesn't grab prints after import weblib!"
     assert tempout.getvalue() == "this should not\n", \
            "doesn't print rest to stdout"
コード例 #30
0
ファイル: weblib.py プロジェクト: sabren/appengine-workshop
 def test_form(self):
     weblib.MYFORM = {"a":"bcd"}
     try:
         myscript = trim(
             """
             import weblib
             assert REQ.form is weblib.MYFORM, \
                 'request uses wrong form'
             """)
         req = self.builder.build(form=weblib.MYFORM)
         eng = weblib.Engine(request=req, script=myscript)
         eng.run()
         assert eng.result == eng.SUCCESS, eng.result
     finally:
         del weblib.MYFORM
コード例 #31
0
ファイル: weblib.py プロジェクト: sabren/appengine-workshop
 def test_print(self):
     import sys, StringIO
     eng = Engine(script=trim(
         """
         import weblib
         print >> RES, 'this should show'
         print 'this should not'
         """))
     tempout, sys.stdout = sys.stdout, StringIO.StringIO()
     eng.run()
     sys.stdout, tempout = tempout, sys.stdout
     assert eng.response.buffer == "this should show\n", \
            "doesn't grab prints after import weblib!"
     assert tempout.getvalue() == "this should not\n", \
            "doesn't print rest to stdout"
コード例 #32
0
ファイル: wks.py プロジェクト: tangentstorm/workshop
def main(argv):
    cmds = dict(
        makeArgParser(line) for line in trim("""
        init appname
        addToModel ClassName [tableName]
        addLink  FromClass linkName ToClass
        addLinkset ParentClass linksetName ChildClass [backLinkName]
        fromXMI filename
        """).split('\n') if line)

    usage = "usage: wks [ %s ]" % (' | '.join(sorted(cmds.keys())))
    cmd = expectArg(argv, 1, usage)
    if cmd in cmds:
        cmds[cmd](argv)
    else:
        raise SystemExit(usage)
コード例 #33
0
ファイル: wks.py プロジェクト: sabren/workshop
def main(argv):
    cmds = dict(makeArgParser(line) for line in trim(
        """
        init appname
        addToModel ClassName [tableName]
        addLink  FromClass linkName ToClass
        addLinkset ParentClass linksetName ChildClass [backLinkName]
        fromXMI filename
        """).split('\n') if line)

    usage = "usage: wks [ %s ]" % (' | '.join(sorted(cmds.keys())))
    cmd = expectArg(argv, 1, usage)
    if cmd in cmds:
        cmds[cmd](argv)
    else:
        raise SystemExit(usage)
コード例 #34
0
ファイル: main.py プロジェクト: sabren/webAppWorkshop
 def _exec(self, script):
     if script:
         script(self.request, self.response)
     else:
         self.response.addHeader("status", "404 Not Found")
         self.response.write(handy.trim(
             """
             <!doctype html>
             <html>
             <head>
               <title>404 Not Found</title>
             </head>
             <body>
               <h1>404 Not Found</h1>
               <p>There is no app at <strong>%s</strong>.</p>
             </body>
             <html>
             """) % self.request.host)
コード例 #35
0
 def errStart(self):
     return trim('''
         <html>
         <head>
         <title>weblib.cgi exception</title>
         <style type="text/css">
             body, p {
                background: #cccccc;
                font-family: verdana, arial;
                font-size: 75%;
             }
             pre { font-size: 120%; }
             pre.traceback { color: red; }
             pre.output{ color : green }
         </style>
         </head>
         <body>
         ''')
コード例 #36
0
ファイル: weblib.py プロジェクト: sabren/appengine-workshop
 def errStart(self):
     return trim(
         '''
         <html>
         <head>
         <title>weblib.cgi exception</title>
         <style type="text/css">
             body, p {
                background: #cccccc;
                font-family: verdana, arial;
                font-size: 75%;
             }
             pre { font-size: 120%; }
             pre.traceback { color: red; }
             pre.output{ color : green }
         </style>
         </head>
         <body>
         ''')
コード例 #37
0
ファイル: weblib.py プロジェクト: sabren/appengine-workshop
    def sendError(self):
        SITE_MAIL = self.eng.globals["SITE_MAIL"]
        SITE_NAME = self.eng.globals["SITE_NAME"]
        assert SITE_MAIL is not None, "must define SITE_MAIL first!"
        hr = "-" * 50 + "\n"
        msg = trim(
            """
            To: %s
            From: cgi <%s>
            Subject: uncaught exception in %s

            """ % (SITE_MAIL, SITE_MAIL, SITE_NAME))
        msg += "uncaught exception in %s\n\n" % self.eng.request.pathInfo
        msg += hr
        msg += str(self.eng.error)
        msg += hr
        msg += "FORM: %s\n"  % self.eng.request.form
        msg += "QUERYSTRING: %s\n" % self.eng.request.query.string
        msg += "COOKIE: %s\n" % self.eng.request.cookie

        if hasattr(self, "sess"):
            msg += "SESSION DATA:\n"
            for item in self.eng.sess.keys():
                msg += item + ': '
                try:
                    msg += self.eng.sess[item] + "\n"
                except:
                    msg += "(can't unpickle)\n"
        else:
            msg += "NO SESSION DATA\n"
        msg += hr
        msg += "OUTPUT:\n\n"
        msg += self.eng.response.getHeaders() + "\n"
        msg += self.eng.response.buffer + "\n"
        msg += hr

        msg.encode("utf-8")

        sendmail(msg)
コード例 #38
0
    def sendError(self):
        SITE_MAIL = self.eng.globals["SITE_MAIL"]
        SITE_NAME = self.eng.globals["SITE_NAME"]
        assert SITE_MAIL is not None, "must define SITE_MAIL first!"
        hr = "-" * 50 + "\n"
        msg = trim("""
            To: %s
            From: cgi <%s>
            Subject: uncaught exception in %s

            """ % (SITE_MAIL, SITE_MAIL, SITE_NAME))
        msg += "uncaught exception in %s\n\n" % self.eng.request.pathInfo
        msg += hr
        msg += str(self.eng.error)
        msg += hr
        msg += "FORM: %s\n" % self.eng.request.form
        msg += "QUERYSTRING: %s\n" % self.eng.request.query.string
        msg += "COOKIE: %s\n" % self.eng.request.cookie

        if hasattr(self, "sess"):
            msg = msg + "SESSION DATA:\n"
            for item in self.eng.sess.keys():
                msg += item + ': '
                try:
                    msg += self.eng.sess[item] + "\n"
                except:
                    msg += "(can't unpickle)\n"
        else:
            msg += "NO SESSION DATA\n"
        msg += hr
        msg += "OUTPUT:\n\n"
        msg += self.eng.response.getHeaders() + "\n"
        msg += self.eng.response.buffer + "\n"
        msg += hr

        msg.encode("utf-8")

        sendmail(msg)
コード例 #39
0
ファイル: prototype.py プロジェクト: elmore/sixthdev
def generic_header(title, page):
    return trim(
        '''
        <html>
        <head>
        <title>%(title)s</title>

        <style type="text/css">
        body, table, p {
           font-family: arial, verdana, helvetica;
           font-size: 10pt;
           background: white;
           color: black;
        }

        table {
            border-collapse: collapse;
        }

        th {
            background: silver;
            border: solid black 1px;
            border-left:none;
            border-top: none;
        }

        td {
           border: solid silver 1px;
        }

        </style>
        </head>
        <body>
        <table>
           <tr><td><a href="%(page)s">%(page)s</td></tr>
        </table>
        ''' % locals())
コード例 #40
0
def generic_header(title, page):
    return trim('''
        <html>
        <head>
        <title>%(title)s</title>

        <style type="text/css">
        body, table, p {
           font-family: arial, verdana, helvetica;
           font-size: 10pt;
           background: white;
           color: black;
        }

        table {
            border-collapse: collapse;
        }

        th {
            background: silver;
            border: solid black 1px;
            border-left:none;
            border-top: none;
        }

        td {
           border: solid silver 1px;
        }

        </style>
        </head>
        <body>
        <table>
           <tr><td><a href="%(page)s">%(page)s</td></tr>
        </table>
        ''' % locals())
コード例 #41
0
def test_getChunks(test):
    chunks = list(
        getChunks(
            trim('''
        """
        <title>abc</title>
        """
        import this
        pass
        # * headline 1
        # ** headline 2
        """
        here\'s some text
        more text
        """
        pass
        assert 1 + 2 == 3
        ''')))
    #print [(chunk[0].__name__, chunk[1])  for chunk in chunks]
    modes = [chunk[0].__name__ for chunk in chunks]
    test.assertEquals(modes, [
        x.__name__
        for x in [TITLE, CODE, CODE, HEAD, HEAD, TEXT, TEXT, CODE, CODE]
    ])
コード例 #42
0
ファイル: tstream_main.py プロジェクト: sabren/ceomatic
    app = TsApp(redirect=False)

    if twisted:
        RPC_HOST = None # @TODO
        RPC_PORT = 9050 # set to None to disable the xml-rpc server
        print "starting with xml-rpc on port %s"
        print handy.trim(

            """
            TangentStream in running on port %s

            try this:

            >>> python
                import xmlrpclib

                rpc = xmlrpclib.Server("http://localhost:%s")
                box.echo("hello")
            ---
                ['echo', 'hello']
            <<<

            See tstream/TsXmlRpc.py for available methods.

            """  % (RPC_PORT,  RPC_PORT))

        twist(app, TsXmlRpc())
    else:
        print "couldn't find twisted. xml-rpc server disabled."
        app.MainLoop()
コード例 #43
0
ファイル: formgen.py プロジェクト: elmore/sixthdev
        theModule, theClass = sys.argv[1:3]
    except:
        print "usage:", _USAGE_
        sys.exit()

    exec "from %s import %s" % (theModule, theClass)
    instance = locals()[theClass]()

    print trim(
          '''
          *# remember to update ####### tags in this generated file!
          * exec:
              from zebra import html

          <form action="########index.py" method="POST">
          {:html.hidden("what", "#######%(theClass)s"):}
          * if ID:
              edit %(theClass)s
              {:html.hidden("ID", ID):}
          * el:
              add new %(theClass)s

          <table>
          ''' % locals())

    for field in instance.__attrs__:
        if field != 'ID':
            print trim(
                '''
                <tr><td>%(field)s</td>
                    <td>{:html.text("%(field)s", %(field)s):}</td></tr>
                ''' % locals())
コード例 #44
0
ファイル: autobill.py プロジェクト: sabren/cornerops-svn
def main():
    opts, args = parseCommandLine()

    clerk = duckbill.config.makeClerk()
    dbc = clerk.storage.dbc

    accts = getAccountsToBill(Receivables(dbc, clerk))
    #accts = clerk.match(Account, account="ftempy")
    total = sum([a.balance() for a in accts])
    count = len(accts)

    if count == 0:
        sys.exit()

    if opts.notify:
        detail = "\n".join(
            ["    %s : %s" % (a.account, a.balance()) for a in accts])
        handy.sendmail(
            handy.trim("""
            To: %s
            From: %s
            Subject: time to run cards
            
            you have %s account(s), worth %s ready for autobill

            %s
            """) % (FROM, FROM, count, total, detail))
    else:
        # get passphrase and decrypt the cards:
        while True:
            phrase = getpass.getpass("passphrase: ")
            try:
                for acc in accts:
                    #print acc.account,
                    #print acc.cardinfo.isEncrypted()
                    acc.cardinfo.decrypt(phrase)
                break
            except ValueError, e:
                if str(e).count("I/O operation on closed file"):
                    print "nope"
                else:
                    raise

        ## @TODO: this has to come after gpg stuff because otherwise
        ## duckpag changes os.environ["GNUPG"] -- but WHY?!?!
        import os
        tmp = os.environ.get("GNUPGHOME")
        import duckpay
        if tmp:
            os.environ["GNUPGHOME"] = tmp
        else:
            del os.environ["GNUPGHOME"]

        ## @TODO: clean this mess up!! #########################
        sys.path.insert(0, "/home/sei/lib/ensemble")
        import ensemble
        perl = ensemble.Director("/home/sei/lib/ensemble/ensemble.pl")
        perl.loadModule("CyberSourceAuth", "cybs")
        assert perl.cybs.okay(), "didn't load okay"
        ########################################################

        import reasons

        # now charge them:
        for acc in accts:

            amount = acc.balance()
            if amount == 0: continue
            print "%s ($%s):" % (acc.account, amount),
            sys.stdout.flush()
            if not opts.batch:
                if raw_input("[yes|no]").lower() not in ["y", "yes"]:
                    continue

            # this is basically stolen from process.cgi:
            if " " not in acc.cardinfo.owner:
                print "bad card owner: %s" % acc.cardinfo.owner
                owner = raw_input("enter new name: ")
                if not owner.strip():
                    print "skipping..."
                else:
                    acc.cardinfo.owner = owner.strip()
                    acc.cardinfo.encrypt()
                    #@TODO: touching cardinfo should make acc.isDirty=True
                    acc.private.isDirty = True
                    clerk.store(acc)
                    print "updated...",
                print "will try again next time"
                continue

            fname, lname = acc.cardinfo.owner.split(" ", 1)
            orderid = handy.uid()
            request = {
                "ccAuthService_run": "true",
                "merchantReferenceCode": orderid,
                "billTo_firstName": fname,
                "billTo_lastName": lname,
                "card_expirationMonth": acc.cardinfo.expire.m,
                "card_expirationYear": acc.cardinfo.expire.y,
                "billTo_street1": acc.address1,
                "billTo_city": acc.city,
                "billTo_state": acc.state,
                "billTo_postalCode": acc.postal,
                "billTo_country": acc.countryCD,
                "billTo_email": acc.email,
                "card_accountNumber": acc.cardinfo.number,
                "sei_userid": acc.account,
                "purchaseTotals_currency": "USD",
                "purchaseTotals_grandTotalAmount": str(amount),
            }

            # do it:
            status, reply = perl.cybs.auth(request)

            if status != 0:
                print "SYSTEM ERROR"
                pprint.pprint(reply)

            elif reply["decision"] in ["ERROR", "REJECT"]:
                pprint.pprint(request)
                pprint.pprint(reply)
                reason = str(reasons.code[int(reply["reasonCode"])][0])
                print "###", reason, "#####"
                if opts.batch: continue
                if raw_input("send email? ").lower() in ("y", "yes"):
                    emailCustomer(acc, reply["decision"],
                                  (reason + "\n" + pprint.pformat(reply)),
                                  acc.cardinfo.number[-4:], amount)
            else:
                print reply["decision"], amount, orderid
                duckpay.post("bofa",
                             acc.account,
                             amount,
                             orderid,
                             note="autopayment - thank you!")
コード例 #45
0
ファイル: wks.py プロジェクト: sabren/workshop
def addToModel(className, tableName=None):
    """
    Adds a class to the model.
    """
    appname = currentAppName()
    if not className[0] in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
        raise SystemExit("class must start with uppercase letter")

    if modelClassExists(className):
        raise SystemExit("class %s.model.%s already exists."
                         % (appname, className))

    tableName = tableName or className.lower()
    addToSQL(trim(
        '''
        CREATE TABLE %s (
            ID INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY
        );
        ''') % tableName)

    with outstream("test/%sTest.py" % className) as out:
        out(trim(
            """
            from %s import model
            import unittest
            from strongbox import *
            
            class %sTest(unittest.TestCase):
        
                def setUp(self):
                    pass

                def test_constructor(self):
                    obj = %s()

                def tearDown(self):
                    pass

            if __name__ == '__main__':
                unittest.main()
            """) % (appname, className, className))


    with outstream("model/%s.py" % className) as out:
        out(trim(
            """
            from strongbox import *
            from pytypes import *
            import model
            
            class %s(Strongbox):
                ID = attr(long)
            """) % className)

    with outstream("model/__init__.py", "a") as out:
        out(trim(
            """
            from %s import %s
            """ % (className, className)))


    addToSchema(className, repr(tableName))
コード例 #46
0
ファイル: wks.py プロジェクト: sabren/workshop
def init(appname):
    os.mkdir(appname)
    os.chdir(appname)

    dirs = ['spec','test','model','theme','theme/default']
    for d in dirs:
        os.mkdir(d)

    appClass = appname.capitalize() + "App"

    with outstream("%s.py" % appname) as out:
        out(trim(
            '''
            import model, schema
            from dispatch import urlmap
            from wsgiapp import WebApp, GenshiTheme, fileHandlerFactory
            
            __version__="$version$"

            def app_factory(cfg, dbhost, dbname, dbpass, dbuser, baseURL,**etc):
                """
                entry point for paste
                """
                clerk = schema.makeClerk(dbhost, dbuser, dbpass, dbname)
                return %(appClass)s

            class %(appClass)s(WebApp):
                def __init__(self, baseURL, urlmap, clerk=None):
                    super(%(appClass)s, self).__init__(
                        baseURL,
                        [urlmap, fileHandlerFactory])
                    self.theme = GenshiTheme(baseURL)
                    self.clerk = clerk or schema.mockClerk()
                    
            ''') % dict(appClass=appClass))

    
    with outstream("%s.app.in" % appname) as out:
        out(trim(
            """
            #!/bin/env paster
            # $version$

            [server:main]
            paste.server_factory = cherrypaste:server_factory
            host = localhost
            port = 8080
            baseURL = http://localhost:8080/

            [app:main]
            paste.app_factory = %(app)s:app_factory
            
            dbhost = %(dbhost)s
            dbname = %(dbname)s
            dbuser = %(dbuser)s
            dbpass = %(dbpass)s

            """) % dict(app=appname,
                        dbhost='localhost',
                        dbname=appname,
                        dbuser=appname,
                        dbpass=appname))


    with outstream("model/__init__.py", "a") as out:
        out('')

    with outstream("dispatch.py") as out:
        out(trim(
            """
            import %s as app
            from platonic import REST,URI
            
            urlmap = REST(
                URI("/", GET= lambda: handler)
            )
            """) % (appname))


    with outstream("schema.py") as out:
        out(trim(
            """
            import clerks
            import storage
            import MySQLdb
            from model import *

            schema = clerks.Schema({
            })

            def connect(dbhost, dbuser, dbpass, dbname):
                return MySQLdb.connect(
                    user = dbuser,
                    passwd = dbpass,
                    host = dbhost,
                    db = dbname)

            def makeClerk(dbhost, dbuser, dbpass, dbname):
                dbc = connect(dbhost, dbuser, dbpass, dbname)
                return clerks.Clerk(storage.MySQLStorage(dbc), schema)

            def mockClerk():
                return clerks.MockClerk(schema)

            """))


    with outstream('theme/default/layout.gen') as out:
        out(trim(
            '''
            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
                      "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
            <html xmlns="http://www.w3.org/1999/xhtml">
            <head>
            <meta http-equiv="Content-Type"
                content="text/html; charset=utf-8" />
            <title>${title}</title>
            <link rel="stylesheet" href="style.css"/>
            </head>
            <body>
            
            <h1>${title}</h1>
            
            </body>
            </html>
            '''))


    with outstream('theme/default/style.css') as out:
        out(trim(
            """
            body {
              color: black;
              background: white;
              font-family:Verdana, Arial, Helvetica, sans-serif;
              font-size: 10pt;
            }
            """))
コード例 #47
0
ファイル: wks.py プロジェクト: tangentstorm/workshop
def init(appname):
    os.mkdir(appname)
    os.chdir(appname)

    dirs = ['spec', 'test', 'model', 'theme', 'theme/default']
    for d in dirs:
        os.mkdir(d)

    appClass = appname.capitalize() + "App"

    with outstream("%s.py" % appname) as out:
        out(
            trim('''
            import model, schema
            from dispatch import urlmap
            from wsgiapp import WebApp, GenshiTheme, fileHandlerFactory
            
            __version__="$version$"

            def app_factory(cfg, dbhost, dbname, dbpass, dbuser, baseURL,**etc):
                """
                entry point for paste
                """
                clerk = schema.makeClerk(dbhost, dbuser, dbpass, dbname)
                return %(appClass)s

            class %(appClass)s(WebApp):
                def __init__(self, baseURL, urlmap, clerk=None):
                    super(%(appClass)s, self).__init__(
                        baseURL,
                        [urlmap, fileHandlerFactory])
                    self.theme = GenshiTheme(baseURL)
                    self.clerk = clerk or schema.mockClerk()
                    
            ''') % dict(appClass=appClass))

    with outstream("%s.app.in" % appname) as out:
        out(
            trim("""
            #!/bin/env paster
            # $version$

            [server:main]
            paste.server_factory = cherrypaste:server_factory
            host = localhost
            port = 8080
            baseURL = http://localhost:8080/

            [app:main]
            paste.app_factory = %(app)s:app_factory
            
            dbhost = %(dbhost)s
            dbname = %(dbname)s
            dbuser = %(dbuser)s
            dbpass = %(dbpass)s

            """) % dict(app=appname,
                        dbhost='localhost',
                        dbname=appname,
                        dbuser=appname,
                        dbpass=appname))

    with outstream("model/__init__.py", "a") as out:
        out('')

    with outstream("dispatch.py") as out:
        out(
            trim("""
            import %s as app
            from platonic import REST,URI
            
            urlmap = REST(
                URI("/", GET= lambda: handler)
            )
            """) % (appname))

    with outstream("schema.py") as out:
        out(
            trim("""
            import clerks
            import storage
            import MySQLdb
            from model import *

            schema = clerks.Schema({
            })

            def connect(dbhost, dbuser, dbpass, dbname):
                return MySQLdb.connect(
                    user = dbuser,
                    passwd = dbpass,
                    host = dbhost,
                    db = dbname)

            def makeClerk(dbhost, dbuser, dbpass, dbname):
                dbc = connect(dbhost, dbuser, dbpass, dbname)
                return clerks.Clerk(storage.MySQLStorage(dbc), schema)

            def mockClerk():
                return clerks.MockClerk(schema)

            """))

    with outstream('theme/default/layout.gen') as out:
        out(
            trim('''
            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
                      "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
            <html xmlns="http://www.w3.org/1999/xhtml">
            <head>
            <meta http-equiv="Content-Type"
                content="text/html; charset=utf-8" />
            <title>${title}</title>
            <link rel="stylesheet" href="style.css"/>
            </head>
            <body>
            
            <h1>${title}</h1>
            
            </body>
            </html>
            '''))

    with outstream('theme/default/style.css') as out:
        out(
            trim("""
            body {
              color: black;
              background: white;
              font-family:Verdana, Arial, Helvetica, sans-serif;
              font-size: 10pt;
            }
            """))
コード例 #48
0
ファイル: scrape_test.py プロジェクト: mehulsbhatt/snakeeyes
 def __init__(self, string):
     lines = trim(string).split("\n")
     self.width = max(len(line) for line in lines)
     self.height= len(lines) 
     self.lines = lines
コード例 #49
0
        theModule, theClass = sys.argv[1:3]
    except:
        print "usage:", _USAGE_
        sys.exit()

    exec "from %s import %s" % (theModule, theClass)
    instance = locals()[theClass]()

    print trim('''
          *# remember to update ####### tags in this generated file!
          * exec:
              from zebra import html

          <form action="########index.py" method="POST">
          {:html.hidden("what", "#######%(theClass)s"):}
          * if ID:
              edit %(theClass)s
              {:html.hidden("ID", ID):}
          * el:
              add new %(theClass)s

          <table>
          ''' % locals())

    for field in instance.__attrs__:
        if field != 'ID':
            print trim('''
                <tr><td>%(field)s</td>
                    <td>{:html.text("%(field)s", %(field)s):}</td></tr>
                ''' % locals())
コード例 #50
0
ファイル: catchup.py プロジェクト: sabren/cornerops-svn
def sendStatement(acc):
    fromAddr = FROM
    fname, name, email, stmt, grand = makeStatement(acc)
    #if acc.company:
    #    fname = acc.company
    pastDue = acc.amountPastDue(lastDue)
    brand = acc.brand.title().replace('Dcd', 'DCD')
    if brand == 'DCD hosting': pastDue = None # TODO: fix this!
    header =[trim(
        """
        From: %(fromAddr)s
        To: %(name)s <%(email)s>
        """ % locals())]
    if acc.email2:
        header.append("CC: %s\n" % acc.email2)
    header.append(trim(
        """
        Subject: %(brand)s statement [$%(grand)s]
        """ % locals()))
    header = "".join(header)

    if grand <= 0:
        grand_msg = "You owe nothing at this time.\n"
    else:
        if pastDue:
            grand_msg = trim(
                """
                Amount Due: $%s.

                ** NOTE: YOUR ACCOUNT IS PAST DUE.
                ** PLEASE PAY YOUR BILL IMMEDIATELY.

                """ % (grand))
        elif acc.autobill and acc.lastfour:
            grand_msg = trim(
                """
                Amount Due: $%s.

                This amount will be charged to your credit
                card after 48 hours. The card we have on
                file for you ends with %s.

                """) % (grand, acc.lastfour)
        else:
            grand_msg = trim(
                """
                Amount Due: $%s.

                Please pay this amount by %s.

                """)  % (grand, nextDue)

        ## now cap it off:
        brand = acc.brand
        if brand == 'DCD hosting': brand='cornerhost'
        grand_msg += trim(
            """
            You may pay via credit card, PayPal, check
            or money order. For details, visit:

                http://www.%s.com/payment/

            Remember, you can pay by the month *or* by the
            year. If you would like to change your billing
            cycle, just drop me a note when you pay your bill.
            """ % brand)


    #@TODO: strip out my name. get this whole thing into genshi or something.
    msg = trim(
        """
        =============================================================

        Hello %s,

        This is your statement for %s.

        %s
        Thanks!

        Michal J Wallace
        http://www.%s.com/

        =============================================================
        """) % (fname, acc.brand, grand_msg, acc.brand.replace(' ',''))


    if (grand <= 0) and acc.statementStrategy=="ifBalance":
        print "no statement sent for %s (%s) : no balance due" % (name, acc.account)
    else:
        print "sending statement for %s (%s): $%s" % (name, acc.account, grand)
        sys.stdout.flush()
        #print header + msg + stmt
        sendmail(header + msg + stmt)
コード例 #51
0
 def errHeaders(self):
     return trim('''
         Status: 500 Internal Server Error
         Content-Type: text/html; charset=utf-8
         
         ''')