示例#1
0
    def get_content(self):
        """Open content as a stream for reading.

        See DAVResource.get_content()
        """
        filestream = compat.StringIO()

        tableName, primKey = self.provider._split_path(self.path)
        if primKey is not None:
            conn = self.provider._init_connection()
            listFields = self.provider._get_field_list(conn, tableName)
            csvwriter = csv.DictWriter(filestream, listFields, extrasaction="ignore")
            dictFields = {}
            for field_name in listFields:
                dictFields[field_name] = field_name
            csvwriter.writerow(dictFields)

            if primKey == "_ENTIRE_CONTENTS":
                cursor = conn.cursor(MySQLdb.cursors.DictCursor)
                cursor.execute("SELECT * from " + self.provider._db + "." + tableName)
                result_set = cursor.fetchall()
                for row in result_set:
                    csvwriter.writerow(row)
                cursor.close()
            else:
                row = self.provider._get_record_by_primary_key(conn, tableName, primKey)
                if row is not None:
                    csvwriter.writerow(row)
            conn.close()

        # this suffices for small dbs, but
        # for a production big database, I imagine you would have a FileMixin that
        # does the retrieving and population even as the file object is being read
        filestream.seek(0)
        return filestream
    def getContent(self):
        """Open content as a stream for reading.

        See DAVResource.getContent()
        """
        assert not self.isCollection
        d = self.fctx.data()
        return compat.StringIO(d)
 def getContent(self):
     fileLinks = [
         "<a href='%s'>%s</a>\n" % (os.path.basename(f), f)
         for f in self.data["resPathList"]
     ]
     dict = self.data.copy()
     dict["fileLinks"] = ", ".join(fileLinks)
     if self.name == ".Info.html":
         html = """\
         <html><head>
         <title>%(title)s</title>
         </head><body>
         <h1>%(title)s</h1>
         <table>
         <tr>
             <td>Description</td>
             <td>%(description)s</td>
         </tr><tr>
             <td>Status</td>
             <td>%(status)s</td>
         </tr><tr>
             <td>Tags</td>
             <td>%(tags)s</td>
         </tr><tr>
             <td>Orga unit</td>
             <td>%(orga)s</td>
         </tr><tr>
             <td>Files</td>
             <td>%(fileLinks)s</td>
         </tr><tr>
             <td>Key</td>
             <td>%(key)s</td>
         </tr>
         </table>
         <p>This is a virtual WsgiDAV resource called '%(title)s'.</p>
         </body></html>""" % dict
     elif self.name == ".Info.txt":
         lines = [
             self.data["title"],
             "=" * len(self.data["title"]),
             self.data["description"],
             "",
             "Status: %s" % self.data["status"],
             "Orga:   %8s" % self.data["orga"],
             "Tags:   '%s'" % "', '".join(self.data["tags"]),
             "Key:    %s" % self.data["key"],
         ]
         html = "\n".join(lines)
     elif self.name == ".Description.txt":
         html = self.data["description"]
     else:
         raise DAVError(HTTP_INTERNAL_ERROR,
                        "Invalid artifact '%s'" % self.name)
     return compat.StringIO(html)
示例#4
0
def run_benchmarks(opts):

    py_version = "{}.{}.{}".format(*sys.version_info)

    print(
        "#-- WsgiDAV Benchmark ---------------------------------------------")
    print("Date:     {}".format(datetime.date.today()))
    print("WsgiDAV:  {}".format(__version__))
    print("Python:   {}".format(py_version))
    print("CherryPy: {}".format(cp_version))
    print("OS:       {}".format(platform.platform(aliased=True)))

    if use_lxml:
        from lxml.etree import LXML_VERSION as lxml_version

        print("lxml:     {}".format(lxml_version))
    else:
        print("lxml:     (not installed)")

    def _runner(opts):
        with Timing(">>> Summary >>>:"):
            _bench_litmus(opts)
            _bench_script(opts)
        return

    if opts.get("external_server"):
        _runner(opts)
    else:
        with WsgiDavTestServer(with_auth=False,
                               with_ssl=False,
                               profile=opts.get("profile_server")):
            if opts.get("profile_client"):
                import cProfile
                import pstats

                prof = cProfile.Profile()
                prof = prof.runctx("_runner(opts)", globals(), locals())
                stream = compat.StringIO()
                stats = pstats.Stats(prof, stream=stream)
                #        stats.sort_stats("time")  # Or cumulative
                stats.sort_stats("cumulative")  # Or time
                stats.print_stats(20)  # 80 = how many to print
                # The rest is optional.
                # stats.print_callees()
                # stats.print_callers()
                logging.info("Profile data:")
                logging.info(stream.getvalue())
            else:
                _runner(opts)

    return
示例#5
0
def elementContentAsString(element):
    """Serialize etree.Element.
    
    Note: element may contain more than one child or only text (i.e. no child 
          at all). Therefore the resulting string may raise an exception, when
          passed back to etree.XML(). 
    """
    if len(element) == 0:
        return element.text or ""  # Make sure, None is returned as ''
    stream = compat.StringIO()
    for childnode in element:
        print(xmlToBytes(childnode, pretty_print=False), file=stream)
    s = stream.getvalue()
    stream.close()
    return s
示例#6
0
 def get_content(self):
     html = "<pre>" + pformat(self.doc) + "</pre>"
     return compat.StringIO(html.encode("utf8"))
    def runWSGIApp(self, application, script_name, path_info, query):
        # logging.info ("Running application with SCRIPT_NAME {} PATH_INFO {}".format(
        #     script_name, path_info))

        if self.command == "PUT":
            pass  # breakpoint

        env = {
            "wsgi.version": (1, 0),
            "wsgi.url_scheme": "http",
            "wsgi.input": self.rfile,
            "wsgi.errors": sys.stderr,
            "wsgi.multithread": 1,
            "wsgi.multiprocess": 0,
            "wsgi.run_once": 0,
            "REQUEST_METHOD": self.command,
            "SCRIPT_NAME": script_name,
            "PATH_INFO": path_info,
            "QUERY_STRING": query,
            "CONTENT_TYPE": self.headers.get("Content-Type", ""),
            "CONTENT_LENGTH": self.headers.get("Content-Length", ""),
            "REMOTE_ADDR": self.client_address[0],
            "SERVER_NAME": self.server.server_address[0],
            "SERVER_PORT": compat.to_native(self.server.server_address[1]),
            "SERVER_PROTOCOL": self.request_version,
        }
        for httpHeader, httpValue in self.headers.items():
            if not httpHeader.lower() in ("content-type", "content-length"):
                env["HTTP_{}".format(httpHeader.replace(
                    "-", "_").upper())] = httpValue

        # Setup the state
        self.wsgiSentHeaders = 0
        self.wsgiHeaders = []

        try:
            # We have there environment, now invoke the application
            _logger.debug("runWSGIApp application()...")
            result = application(env, self.wsgiStartResponse)
            try:
                for data in result:
                    if data:
                        self.wsgiWriteData(data)
                    else:
                        _logger.debug("runWSGIApp empty data")
            finally:
                _logger.debug("runWSGIApp finally.")
                if hasattr(result, "close"):
                    result.close()
        except Exception:
            _logger.debug("runWSGIApp caught exception...")
            errorMsg = compat.StringIO()
            traceback.print_exc(file=errorMsg)
            logging.error(errorMsg.getvalue())
            if not self.wsgiSentHeaders:
                self.wsgiStartResponse("500 Server Error",
                                       [("Content-type", "text/html")])
            self.wsgiWriteData(SERVER_ERROR)

        if not self.wsgiSentHeaders:
            # GC issue 29 sending one byte, when content-length is '0' seems wrong
            # We must write out something!
            #            self.wsgiWriteData (" ")
            self.wsgiWriteData(b"")
        return
 def getContent(self):
     return compat.StringIO(self.content)