Best Python code snippet using Kiwi_python
pages.py
Source:pages.py  
...28            if curworld == world:29                attrs["selected"] = None30            return attrs31        htmldoc.newline()32        htmldoc.add_tag("option", "All Worlds", attrs=add_selected_world(None, {"value": ""}))33        for world in sorted(a["name"] for a in dbiface.get_worlds()):34            htmldoc.newline()35            htmldoc.add_tag("option", world, attrs=add_selected_world(world, {"value": world}))36class StandardPageContext(object):37    def __init__(self, request):38        #self.request = request39        a = urlparse.urlparse(request.path)40        self.path = a.path41        self.queries = urlparse.parse_qs(a.query)42        self.cookies = Cookie.SimpleCookie(request.headers.getheader("Cookie"))43    def get_guild_stance(self, guild):44        for g, s in self.get_all_guild_stances():45            if g == guild:46                return s47        else:48            return "U"49    def get_all_guild_stances(self):50        if "guildStance" in self.cookies:51            cookieStr = self.cookies["guildStance"].value52            try:53                cookieStr = zlib.decompress(base64.b64decode(cookieStr))54            except:55                pass56            for a in cookieStr.split(","):57                yield a.split("|", 1)58    def get_selected_world(self):59        return self.get_query("world")60    def guild_link(self, guild):61        return guild_link(guild, self.get_guild_stance(guild))62    def get_query(self, query):63        return self.queries.get(query, (None,))[-1]64def standard_page(request, title, content):65    context = StandardPageContext(request)66    body = io.BytesIO()67    sink = gzip.GzipFile(mode="wb", fileobj=body)68    #sink = body69    with standard_content_wrapper(sink.write, context, title) as outfile:70        content(outfile, context)71    #print request.headers.getheader("Accept-Encoding")72    request.send_response(200)73    request.send_header("Content-Type", "text/html")74    request.send_header("Content-Encoding", "gzip")75    request.end_headers()76    sink.close()77    body.seek(0)78    #request.wfile.write(zlib.compress(body.getvalue()))79    #assert not request.wfile.seekable()80    #assert request.wfile.tell() == 081    shutil.copyfileobj(body, request.wfile)82    #assert request.wfile.tell() != 083SKYSCRAPER_AD = '''<script type="text/javascript"><!--84google_ad_client = "pub-5195063250458873";85/* 160x600, created 3/1/10 */86google_ad_slot = "9047224765";87google_ad_width = 160;88google_ad_height = 600;89//-->90</script>91<script type="text/javascript"92src="http://pagead2.googlesyndication.com/pagead/show_ads.js">93</script>'''94LINK_AD = '''<script type="text/javascript"><!--95google_ad_client = "pub-5195063250458873";96/* 728x15, created 3/1/10 */97google_ad_slot = "5533130493";98google_ad_width = 728;99google_ad_height = 15;100//-->101</script>102<script type="text/javascript"103src="http://pagead2.googlesyndication.com/pagead/show_ads.js">104</script>'''105SEARCH_ENGINE = '''106<form action="http://www.google.com/cse" id="cse-search-box" target="_blank">107  <div>108    <input type="hidden" name="cx" value="partner-pub-5195063250458873:51atcrmvpus" />109    <input type="hidden" name="ie" value="ISO-8859-1" />110    <input type="text" name="q" size="15" />111    <input type="submit" name="sa" value="Search" />112  </div>113</form>114<script type="text/javascript" src="http://www.google.com/cse/brand?form=cse-search-box&lang=en"></script>115'''116@contextlib.contextmanager117def standard_content_wrapper(write, context, title):118    """Add the HTML Document to the page context, ready for contents to be written to it, clean up afterwards."""119    #write('''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">''')120    doc = HtmlDocument(write)121    headTitle = "{0} - {1}".format(title, context.get_selected_world() or "All Worlds")122    with doc.open_tag("html"):123        with doc.open_tag("head", inline=False):124            doc.add_tag("meta", inline=False, attrs={"name": "description", "content": "Tibia statistics fansite that shows current protection zone locks, online characters, guild stances and recent deaths."})125            doc.add_tag("meta", inline=False, attrs={"name": "keywords", "content": "tibia, statistics, stats, fansite, protection zone lock, pzls, pz locks, characters, guilds, online guild stances, recent deaths, deaths"})126            doc.add_tag("title", headTitle, inline=False)127            doc.add_tag("link", attrs=dict(rel="stylesheet", type="text/css", href="/tibstats.css"), inline=False)128            doc.add_tag("link", attrs=dict(rel="icon", type="image/gif", href="http://static.tibia.com/images/gameguides/skull_black.gif"), inline=False)129        with doc.open_tag("body", inline=False):130            with doc.open_tag("div", attrs={"id": "header", "class": "bodyrow"}, inline=False):131                doc.writelns(LINK_AD.split("\n"))132            #with doc.open_tag("div", attrs={"class": "bodyrow"}, inline=False):133                #with doc.open_tag("div", attrs={"style": "display: table-cell"}):134            with doc.open_tag("div", attrs={"id": "main", "class": "bodyrow"}, inline=False):135                with doc.open_tag("div", attrs={"id": "left"}, inline=False):136                    with doc.open_tag("div", {"id": "menu"}, inline=False):137                        doc.add_tag("div", "Menu", {"id": "menu-title"})138                        for path, entry in PAGES.iteritems():139                            if isinstance(entry, MenuPageEntry):140                                #world = context.get_selected_world()141                                #if world:142                                #    path += "?" + urllib.urlencode({"world": world})143                                doc.add_tag("a", entry.title, attrs={"href": path})144                                doc.add_tag("br")145                        #with doc.open_tag("form", attrs={"method": "get", "class": "world-form"}, inline=False):146                        #    doc.newline()147                        #    world_select(doc, context.get_selected_world(), onchange=True)148                    #with doc.open_tag("div", attrs={"id": "left-ad"}):149                    #    doc.writelns(SKYSCRAPER_AD.split("\n"))150                with doc.open_tag("div", attrs={"id": "center"}, inline=False):151                    with doc.open_tag("div", attrs={"id": "content-title"}):152                        doc.writelns(SEARCH_ENGINE.split("\n"))153                        doc.write(headTitle)154                    with doc.open_tag("div", attrs={"id": "content"}):155                        yield doc156            with doc.open_tag("div", attrs={"id": "footer", "class": "bodyrow"}):157                doc.write("Version " + TIBSTAT_VERSION)158def stattab_table_tag(openTag):159    return openTag("table", attrs={"class": "stattab", "cellspacing": 1,}, inline=False)160def stattab_row_class():161    return itertools.cycle(("odd", "even"))162def human_time_diff(stamp):163    diff = dbiface.to_unixepoch(stamp) - int(time.time())164    assert isinstance(diff, int) # if this doesn't hold, we'll generate rubbish165    if diff == 0:166        return "now"167    if diff < 0:168        whence = "ago"169        diff = -diff # must be positive for identity: x == (x/y)*y + (x%y)170    elif diff > 0:171        whence = "more"172    humanbits = []173    for divisor, units in ((60, "s"), (60, "m"), (24, "h"), (None, "d")):174        if divisor is not None:175            bitval = diff % divisor176        else:177            bitval = diff178        humanbits.append(("%d%s" % (bitval, units)) if bitval else None)179        del bitval180        if divisor is None:181            break182        diff //= divisor183        if diff == 0:184            break185    del diff186    # take the 2 most significant bits, filter the zeroed ones187    return "".join(filter(None, itertools.islice(reversed(humanbits), 2))) + " " + whence188def guild_stances(outfile, context):189    doc = outfile190    world = context.get_selected_world()191    doc.add_tag("p", 'Here are listed the guilds for the world you have selected. You may set your personal "stance" toward that guild, F=Friend, A=Ally, U=Unspecified, E=Enemy. The guild is then appropriately colored on any page where guild is mentioned to ease categorization at a glance.', attrs={"style": "width: 100%"})192    with doc.open_tag("form", attrs={"method": "get"}):193        doc.write("World:")194        world_select(doc, world, onchange=True)195    guildsListed = set()196    with doc.open_tag("form", attrs={"method": "post",}, inline=False): #"action": "/setcookie"}):197        with stattab_table_tag(doc.open_tag):198            with doc.open_tag("tr"):199                for heading in ("Guild Name", "Members") + STANCE_VALUES:200                    doc.add_tag("th", heading)201                if not world:202                    doc.add_tag("th", "World")203            rowClass = stattab_row_class()204            for guild, memberCount in dbiface.list_guilds(world):205                #if not world or world == guildWorld:206                with doc.open_tag("tr", attrs={"class": rowClass.next()}, inline=False):207                    doc.newline()208                    doc.add_tag("td", guild_link(guild, context.get_guild_stance(guild)))209                    doc.add_tag("td", memberCount)210                    for stance in STANCE_VALUES:211                        doc.newline()212                        with doc.open_tag("td", inline=True):213                            attrs = dict(type="radio", name=guild, value=stance)214                            if stance == context.get_guild_stance(guild):215                                attrs["checked"] = None216                            doc.add_tag("input", attrs=attrs, inline=True)217                        #if not world:218                        #    doc.add_tag("td", guildWorld)219                guildsListed.add(guild)220#        doc.add_tag("input", attrs={"type": "hidden", "name": "NEXT_LOCATION", "value": "/whoisonline"})221        for g, s in context.get_all_guild_stances():222            if g not in guildsListed:223                doc.newline()224                doc.add_tag("input", attrs={"type": "hidden", "name": g, "value": s})225        doc.newline()226        doc.add_tag("input", attrs={"type": "submit", "value": "Change Stances!"})227def guild_stances_page(request, title):228    if request.command == "POST":229        # client POSTed, form a cookie, and set it, and then redirect them to nonPOST version230        contentLength = request.headers.getheader("Content-Length")231        postData = request.rfile.read(int(contentLength))232        guildStances = dict(urlparse.parse_qsl(postData, strict_parsing=True))233        cookie = Cookie.SimpleCookie()234        cookie["guildStance"] = base64.b64encode(zlib.compress(",".join("|".join(a) for a in guildStances.iteritems() if a[1] != "U"), 9))235        #cookie["guildStance"] = ",".join("|".join(a) for a in guildStances.iteritems() if a[1] != "U")236        cookie["guildStance"]["max-age"] = 30 * 24 * 60 * 60237        request.send_response(303) # See Other (GET)238        request.wfile.write(cookie.output() + '\r\n')239        # go back whence thee came240        request.send_header("Location", request.headers.getheader("Referer"))241        request.end_headers()242    else:243        standard_page(request, title, guild_stances)244def tibstats_stylesheet(request):245    #print request.headers246    with contextlib.closing(open("tibstats.css", "rb")) as f:247        fs = os.fstat(f.fileno())248        # variant modification time249        varmtime = request.headers.getheader("If-Modified-Since")250        if varmtime:251            # If-Modified-Since: Sat, 27 Feb 2010 16:13:49 GMT252            varmtime = varmtime.split(";", 1)[0]253            varmtime = calendar.timegm(time.strptime(varmtime, "%a, %d %b %Y %H:%M:%S %Z"))254            #print fs.st_mtime, varmtime255            if fs.st_mtime <= varmtime:256                request.send_response(304)257                request.end_headers()258                return259        request.send_response(200)260        request.send_header("Content-Type", "text/css")261        request.send_header("Content-Length", str(fs.st_size))262        request.send_header("Last-Modified", request.date_time_string(fs.st_mtime))263        request.end_headers()264        shutil.copyfileobj(f, request.wfile)265def recent_deaths(outfile, context):266    doc = outfile267    limits = (0, 200)268    world = context.get_selected_world()269    try:270        minlevel = int(context.get_query("minlevel"))271    except (ValueError, TypeError):272        minlevel = 45273    with doc.open_tag("form", attrs={"method": "get"}):274        doc.write("World:")275        world_select(doc, world, onchange=False)276        doc.write("Min Level:")277        doc.add_tag("input", attrs={"type": "text", "name": "minlevel", "value": minlevel, "maxlength": "3", "size": "3"})278        doc.add_tag("input", attrs={"type": "submit", "value": "Apply Filter"})279    with stattab_table_tag(doc.open_tag):280        with doc.open_tag("tr"):281            for a in ("Time", "Deceased", "Level", "Guild", "Killer", "Accomplices"):282                doc.add_tag("th", a)283            if not world:284                doc.add_tag("th", "World")285        killsIter = dbiface.get_last_deaths(limits, world=world, minlevel=minlevel)286        currentDeath = killsIter.next()287        killsEnded = False288        rowsMade = 0289        rowClass = stattab_row_class()290        while not killsEnded and rowsMade < 30:291            with doc.open_tag("tr", attrs={"class": rowClass.next()}):292                doc.add_tag("td", human_time_diff(currentDeath["stamp"]))293                doc.add_tag("td", char_link(currentDeath["victim"]))294                doc.add_tag("td", currentDeath["level"])295                doc.add_tag("td", context.guild_link(currentDeath["guild"]))296                def make_killer(kill):297                    if kill["isplayer"]:298                        s = char_link(kill["killer"])299                    else:300                        s = kill["killer"]301                    return s302                data = [make_killer(currentDeath)]303                while True:304                    try:305                        nextKill = killsIter.next()306                    except StopIteration:307                        killsEnded = True308                        break309                    if (nextKill["stamp"], nextKill["victim"]) == (currentDeath["stamp"], currentDeath["victim"]):310                        a = make_killer(nextKill)311                        if nextKill["lasthit"]:312                            data.insert(0, a)313                        else:314                            data.append(a)315                    else:316                        #currentDeath = nextKill317                        nextDeath = nextKill318                        break319                doc.add_tag("td", data[0])320                doc.add_tag("td", ", ".join(data[1:]))321                if not world:322                    doc.add_tag("td", currentDeath["world"])323            rowsMade += 1324            currentDeath = nextDeath325def world_online(doc, pageContext):326    doc.newline()327    world = pageContext.get_selected_world()328    #after = update.next_tibiacom_whoisonline_update() - 300329    onlineChars = list(dbiface.get_online_chars(world=world))330    #doc.write("This page is still being optimized.<br>")331    doc.write("There are {0} players online on the worlds you have selected.".format(len(onlineChars)))332    onlineChars.sort(key=lambda x: int(x["level"]), reverse=True)333    with stattab_table_tag(doc.open_tag):334        with doc.open_tag("tr"):335            doc.add_tag("th", "Name")336            doc.add_tag("th", "Level")337            doc.add_tag("th", "Vocation")338            doc.add_tag("th", "Guild")339            if not world:340                doc.add_tag("th", "World")341        rowClass = stattab_row_class()342        for char in onlineChars:343            doc.newline()344            rowAttrs = {"class": rowClass.next()}345            if char["level"] < 45:346                rowAttrs["class"] += " greyed"347            with doc.open_tag("tr", attrs=rowAttrs):348                doc.add_tag("td", char_link(char["name"]))349                for field in ("level", "vocation"):350                    doc.add_tag("td", data=str(char[field]))351                doc.add_tag("td", pageContext.guild_link(char["guild"]))352                if not world:353                    doc.add_tag("td", char["world"])354def pz_locked(doc, pageContext):355    world = pageContext.get_selected_world()356    curtime = int(time.time())357    limits = (0, 30)358    #limits = (0, 200)359    doc.add_tag("p", data="Players sorted by descending protection zone lock time remaining. Also shown is their level, vocation, guild, and most recent victim. Shown first are those that are still PZL'd. The second table contains those that should have lost their PZL by now.")360    column_count = 6361    if not world:362        column_count += 1363    with stattab_table_tag(doc.open_tag):364        def add_header_row():365            with doc.open_tag("tr", inline=False):366                if not world:367                    doc.add_tag("th", "World")368                doc.add_tag("th", "PZ Lock End")369                doc.add_tag("th", "Killer")370                doc.add_tag("th", "Level")371                doc.add_tag("th", "Vocation")372                doc.add_tag("th", "Guild")373                doc.add_tag("th", "Last Victim")374        add_header_row()375        rowColor = stattab_row_class()376        doing_still_pzlocked_rows = True377        for pzlock in dbiface.get_last_pzlocks(world, limits):378            killerInfo = dbiface.get_char(pzlock["killer"])379            #pdb.set_trace()380            pzEndStamp = dbiface.pz_end(pzlock)381            if doing_still_pzlocked_rows:382                if pzEndStamp < int(time.time()):383                    doing_still_pzlocked_rows = False384                    with doc.open_tag("tr"):385                        with doc.open_tag("td", attrs={"colspan": column_count}):386                            doc.add_tag("hr")387                    add_header_row()388            if world is None or killerInfo["world"] == world:389                rowAttrs = {"class": rowColor.next()}390                if not doing_still_pzlocked_rows:391                    rowAttrs["class"] += " greyed"392                with doc.open_tag("tr", attrs=rowAttrs, inline=False):393                    assert killerInfo["name"] == pzlock["killer"]394                    if not world:395                        doc.add_tag("td", killerInfo["world"])396                    doc.add_tag("td", human_time_diff(pzEndStamp))397                    doc.add_tag("td", char_link(pzlock["killer"]))398                    for field in ("level", "vocation"):399                        doc.add_tag("td", killerInfo[field])400                    doc.add_tag("td", pageContext.guild_link(killerInfo["guild"]))401                    doc.add_tag("td", char_link(pzlock["victim"]))402def player_killer_highscores(doc, context):403    world = context.get_selected_world()404    with stattab_table_tag(doc.open_tag):405        with doc.open_tag("tr", inline=False):406            doc.add_tag("th", "Kill Count")407            if not world:408                doc.add_tag("th", "World")409            doc.add_tag("th", "Assassin Name")410            doc.add_tag("th", "Level")411            doc.add_tag("th", "Vocation")412            doc.add_tag("th", "Guild")413        rowClass = stattab_row_class()414        for pker in dbiface.best_player_killers(world):415            with doc.open_tag("tr", attrs={"class": rowClass.next()}, inline=False):416                doc.add_tag("td", pker[0])417                if not world:418                    doc.add_tag("td", pker["world"])419                doc.add_tag("td", char_link(pker["name"]))420                #pdb.set_trace()421                doc.add_tag("td", pker["level"])422                doc.add_tag("td", pker["vocation"])423                doc.add_tag("td", context.guild_link(pker["guild"]))424class PageEntry(object):425    def __init__(self, handler):426        self.handler = handler427    def handle_request(self, request):428        self.handler(request)429class MenuPageEntry(PageEntry):430    def __init__(self, handler, title):431        #pdb.set_trace()432        super(MenuPageEntry, self).__init__(handler)433        self.title = title434    def handle_request(self, request):435        self.handler(request, self.title)436class StandardPageEntry(MenuPageEntry):437    def __init__(self, handler, title):...__pages.py
Source:__pages.py  
...33    """Add the HTML Document to the page context, ready for contents to be written to it, clean up afterwards."""34    def setup_content_doc(pageContext, title):35        doc = pageContext.htmldoc36        doc.start_head()37        doc.add_tag("title", title, inline=False)38        doc.add_tag("link", attrs=dict(rel="stylesheet", type="text/css", href="/tibstats.css"), inline=False)39        doc.add_tag("link", attrs=dict(rel="icon", type="image/gif", href="http://static.tibia.com/images/gameguides/skull_black.gif"), inline=False)40        doc.start_body()41        with doc.open_tag("div", {"id": "menu"}):42            for p in PAGES.values():43                try:44                    title = p.baseTitle45                except AttributeError:46                    continue47                path = p.basePath48                world = pageContext.get_selected_world()49                if world:50                    path += "?" + urllib.urlencode({"world": world})51                doc.add_tag("a", title, attrs={"href": path})52                doc.add_tag("br")53            with doc.open_tag("form", attrs={"method": "get"}):54                doc.add_tag("input", attrs=dict(type="submit", value="Set world"))55                with doc.open_tag("select", attrs={"size": 1, "name": "world"}):56                    def add_selected_world(world, attrs):57                        if pageContext.get_selected_world() == world:58                            attrs["selected"] = None59                        return attrs60                    doc.add_tag("option", "ALL WORLDS", attrs=add_selected_world(None, {"value": ""}))61                    for world in sorted(a["name"] for a in dbiface.get_worlds()):62                        doc.add_tag("option", world, attrs=add_selected_world(world, {"value": world}))63        doc.open_tag("div", {"id": "content"}, inline=False)64        return doc65    def finish_doc_content(doc):66        doc.close_tag("div", inline=False)67        doc.close()68    setup_content_doc(pageContext, title)69    yield70    finish_doc_content(pageContext.htmldoc)71class PageGenerator(object):72    def __init__(self, contentFunc, basePath, baseTitle=None):73        self.basePath = basePath74        self.contentFunc = contentFunc75        if baseTitle:76            self.baseTitle = baseTitle77    def generate_page(self, requestHandler):78        return self.contentFunc(requestHandler)79class StandardPage(PageGenerator):80    """Generates menus etc., and jumps into the content function ready for the main data"""81    def __init__(self, contentFunc, basePath, baseTitle, allowedMethods=("GET",)):82        super(self.__class__, self).__init__(contentFunc, basePath, baseTitle=baseTitle)83        self.allowedMethods = allowedMethods84    def generate_page(self, requestHandler):85        """Overrides and wraps a content function that generates data, and takes a page context."""86        rh = requestHandler87        if rh.command not in self.allowedMethods:88            rh.send_response(405, "Computer says no")89            rh.send_header("Allow", ", ".join(self.allowedMethods))90            rh.end_headers()91            return92        rh.send_response(200)93        rh.send_header("Content-Type", "text/html")94        rh.end_headers()95        pageContext = PageContext(rh)96        parseResult = urlparse.urlparse(rh.path)97        pageContext.path = parseResult.path98        pageContext.query = urlparse.parse_qs(parseResult.query)99        pageContext.cookie = Cookie.SimpleCookie(rh.headers.getheader("Cookie"))100        with htmldoc_content_wrapper(pageContext, self.baseTitle):101            self.contentFunc(pageContext)102def register_page(pageClass, basePath, *args, **kwargs):103    def _1(contentFunc):104        a = pageClass(contentFunc, basePath, *args, **kwargs)105        assert basePath not in PAGES106        PAGES[basePath] = a107    return _1108@register_page(StandardPage, "/whoisonline", "Players Online")109def world_online(pageContext):110    doc = pageContext.htmldoc111    doc.newline()112    world = pageContext.get_selected_world()113    after = int(time.time()) - 300114    #after = 0115    onlineChars = dbiface.get_online_chars(after, world=world)116    doc.write("There are {0} players online.".format(len(onlineChars)))117    onlineChars.sort(key=lambda x: int(x["level"]), reverse=True)118    with doc.open_tag("table"):119        with doc.open_tag("tr"):120            doc.add_tag("th", "Name")121            doc.add_tag("th", "Level")122            doc.add_tag("th", "Vocation")123            doc.add_tag("th", "Guild")124            if not world:125                doc.add_tag("th", "World")126        for char in onlineChars:127            doc.newline()128            with doc.open_tag("tr"):129                doc.add_tag("td", char_link(char["name"]))130                for field in ("level", "vocation"):131                    doc.add_tag("td", data=str(char[field]))132                doc.add_tag("td", pageContext.guild_link(char["guild"]))133                if not world:134                    doc.add_tag("td", char["world"])135def char_link(name):136    return tag("a", name, attrs=dict(href=tibiacom.char_page_url(name)))137def guild_link(name, stance):138    return tag("a", name, attrs={"href": tibiacom.guild_members_url(name), "class": STANCE_CSS_CLASS[stance]})139@register_page(StandardPage, "/pzlocked", "Players with PZL")140def pz_locked(pageContext):141    curtime = int(time.time())142    #curtime = 1267240000143    world = pageContext.get_selected_world()144    doc = pageContext.htmldoc145    with doc.open_tag("table"):146        with doc.open_tag("tr", inline=False):147            if not world:148                doc.add_tag("th", "World")149            doc.add_tag("th", "PZL left")150            doc.add_tag("th", "Killer")151            doc.add_tag("th", "Level")152            doc.add_tag("th", "Vocation")153            doc.add_tag("th", "Guild")154            doc.add_tag("th", "Last Victim")155        for pzlock in dbiface.get_pzlocks(curtime=curtime):156            killerInfo = dbiface.get_char(pzlock["killer"])157            if world is None or killerInfo["world"] == world:158                with doc.open_tag("tr", inline=False):159                    assert killerInfo["name"] == pzlock["killer"]160                    if not world:161                        doc.add_tag("td", killerInfo["world"])162                    doc.add_tag("td", "{0} mins".format((dbiface.pz_end(pzlock) - curtime) // 60))163                    doc.add_tag("td", char_link(pzlock["killer"]))164                    for field in ("level", "vocation"):165                        doc.add_tag("td", killerInfo[field])166                    doc.add_tag("td", pageContext.guild_link(killerInfo["guild"]))167                    doc.add_tag("td", char_link(pzlock["victim"]))168@register_page(PageGenerator, "/guildstances", baseTitle="Guild Stances")169def guild_stances(request):170    contentLength = request.headers.getheader("Content-Length")171    if contentLength:172        if request.path.startswith("/guildstance"):173            # client POSTed, form a cookie, and set it, and then redirect them to nonPOST version174            postData = request.rfile.read(int(contentLength))175            guildStances = dict(urlparse.parse_qsl(postData, strict_parsing=True))176            cookie = Cookie.SimpleCookie()177            cookie["guildStance"] = ",".join("|".join(a) for a in guildStances.iteritems())178            request.send_response(303) # See Other (GET)179            request.wfile.write(cookie.output() + '\r\n')180            request.send_header("Location", self.headers.getheader("Referer"))181            request.end_headers()182            return183    doc = context.htmldoc184    world = context.get_selected_world()185    with doc.open_tag("form", attrs={"method": "post",}): #"action": "/setcookie"}):186        with doc.open_tag("table"):187            with doc.open_tag("tr"):188                for heading in ("Guild Name",) + STANCE_VALUES:189                    doc.add_tag("th", heading)190                if not world:191                    doc.add_tag("th", "World")192            for guild, guildWorld in dbiface.list_guilds():193                if not world or world == guildWorld:194                    with doc.open_tag("tr", inline=False):195                        doc.newline()196                        doc.add_tag("td", guild_link(guild, context.get_guild_stance(guild)))197                        for stance in STANCE_VALUES:198                            doc.newline()199                            with doc.open_tag("td", inline=True):200                                attrs = dict(type="radio", name=guild, value=stance)201                                if stance == context.get_guild_stance(guild):202                                    attrs["checked"] = None203                                doc.add_tag("input", attrs=attrs, inline=True)204                        if not world:205                            doc.add_tag("td", guildWorld)206#        doc.add_tag("input", attrs={"type": "hidden", "name": "NEXT_LOCATION", "value": "/whoisonline"})207        doc.add_tag("input", attrs={"type": "submit"})208@register_page(StandardPage, "/recentdeath", "Recent Deaths")209def recent_deaths(context):210    doc = context.htmldoc211    limits = (0, 100)212    with doc.open_tag("table"):213        with doc.open_tag("tr"):214            for a in ("Time", "Deceased", "Level", "Killer", "Accomplices"):215                doc.add_tag("th", a)216        killsIter = dbiface.get_last_deaths(limits)217        currentDeath = killsIter.next()218        killsEnded = False219        while not killsEnded:220            with doc.open_tag("tr"):221                doc.add_tag("td", currentDeath["stamp"])222                doc.add_tag("td", char_link(currentDeath["victim"]))223                doc.add_tag("td", currentDeath["level"])224                def make_killer(kill):225                    if kill["isplayer"]:226                        s = char_link(kill["killer"])227                    else:228                        s = kill["killer"]229                    return s230                data = [make_killer(currentDeath)]231                while True:232                    try:233                        nextKill = killsIter.next()234                    except StopIteration:235                        killsEnded = True236                        break237                    if (nextKill["stamp"], nextKill["victim"]) == (currentDeath["stamp"], currentDeath["victim"]):238                        a = make_killer(nextKill)239                        if nextKill["lasthit"]:240                            data.insert(0, a)241                        else:242                            data.append(a)243                    else:244                        currentDeath = nextKill245                        break246                doc.add_tag("td", data[0])247                doc.add_tag("td", ", ".join(data[1:]))248@register_page(PageGenerator, "/tibstats.css")249def tibstats_stylesheet(requestHandler):250    f = open("tibstats.css", "rb")251    fs = os.fstat(f.fileno())252    requestHandler.send_response(200)253    requestHandler.send_header("Content-Type", "text/css")254    requestHandler.send_header("Content-Length", str(fs.st_size))255    requestHandler.send_header("Last-Modified", requestHandler.date_time_string(fs.st_mtime))256    requestHandler.end_headers()257    shutil.copyfileobj(f, requestHandler.wfile)258    f.close()259def generate_http_response(requestHandler):260    basePath = requestHandler.path.split("?", 1)[0]261    try:...OOP_composition.py
Source:OOP_composition.py  
...21class Body(Tag):22    def __init__(self):23        super().__init__('body', '') 24        self._body_contents = []25    def add_tag(self, name, contents):26        new_tag = Tag(name, contents)27        self._body_contents.append(new_tag)28    def display(self, file=None):29        for tag in self._body_contents:30            self.contents += str(tag)31        super().display(file=file)32# Using as composition33# class HtmlDoc(object):34    35#     def __init__(self, title=None):36#         self._doc_type = DocType()37#         self._head = Head(title)38#         self._body = Body()39#     def add_tag(self, name, contents):40#         self._body.add_tag(name, contents)41#     def display(self, file=None):42#         self._doc_type.display(file=file)43#         print('<html>', file=file)44#         self._head.display(file=file)45#         self._body.display(file=file)46#         print('</html>', file=file)47# using as aggregation48class HtmlDoc(object):49    50    def __init__(self, doc_type, head, body):51        self._doc_type = doc_type52        self._head = head53        self._body = body54    def add_tag(self, name, contents):55        self._body.add_tag(name, contents)56    def display(self, file=None):57        self._doc_type.display(file=file)58        print('<html>', file=file)59        self._head.display(file=file)60        self._body.display(file=file)61        print('</html>', file=file)62if __name__ == '__main__':63    # my_page = HtmlDoc()64    # my_page.add_tag('h1', 'Main heading')65    # my_page.add_tag('h2', 'sub-heading')66    # my_page.add_tag('p', 'This is a paragraph that will appear on the page')67    # with open('D:\python\Python_practice\documents\\test.html', 'w') as test_doc:68    #     my_page.display(file=test_doc)69    new_body = Body()70    new_body.add_tag('h1', 'Aggregation')71    new_body.add_tag('h1', "Unline <strong>composition</strong>, aggregation uses existing instances"72                            " of objects to build up another object.")73    new_body.add_tag('p',"The composed object doesn't actually own the objects that it's composed of"74                        " - if it's destroyed, those objects continue to exist.")75    new_docType = DocType()76    new_header = Head('Aggregation Document')77    my_page = HtmlDoc(new_docType, new_header, new_body)78# give our document new content by switching its body79    my_page._body = new_body80    with open('D:\python\Python_practice\documents\\test3.html', 'w') as test_doc:81        my_page.display(file=test_doc)...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
