Python一课一练(利用session来保存用户输入)

平常我们在浏览器里输入的时候会用到缓存,在python里由web库里的session来实现,代码很简单,我们会用到四个文件:

1. “map.py”这个文件是数据的来源:
# -*- coding: utf-8 -*-
from sys import exit
from random import randint

class Room(object):

    def __init__(self, name, description):
        self.name = name
        self.description = description
        self.paths = {}

    def go(self, direction):
        return self.paths.get(direction, None)

    def add_paths(self, paths):
        self.paths.update(paths)


central_corridor = Room("Central Corridor",
"""
The Gothons of Planet Percal #25 have invaded your ship and destroyed
your entire crew. You are the last surviving member and your last
mission is to get the neutron destruct bomb from the Weapons Armory,
put it in the bridge, and blow the ship up after getting into an
escape pod.
You're running down the central corridor to the Weapons Armory when
a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume
flowing around his hate filled body. He's blocking the door to the
Armory and about to pull a weapon to blast you.
You can choose
1.shoot!\n2.dodge!\n3.tell a joke!
""")

laser_weapon_armory = Room("Lasor Weapon Armory ",
"""
Lucky for you they made you learn Gothon insults in the academy.
You tell the one Gothon joke you know:
Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr.
The Gothon stops, tries not to laugh, then busts out laughing and can't move.
While he's laughing you run up and shoot him square in the head
putting him down, then jump through the Weapon Armory door.
You do a dive roll into the Weapon Armory, crouch and scan the room
for more Gothons that might be hiding. It's dead quiet, too quiet.
You stand up and run to the far side of the room and find the
neutron bomb in its container. There's a keypad lock on the box
and you need the code to get the bomb out. If you get the code
wrong 10 times then the lock closes forever and you can't
get the bomb. The code is 3 digits.
""")

the_bridge = Room("The Bridge",
"""
The container clicks open and the seal breaks, letting gas out.
You grab the neutron bomb and run as fast as you can to the
bridge where you must place it in the right spot.
""")

finished = Room("Finished",
"""
You won! Good job.
"""
)

#Room是父类,其余的是Room的子类
generic_death = "You LOSE!!!!!!!!!!!!!!!!!!!!!!!!!!"
success = "You has finished this game, Congratulations!"

START = Room('game', 'You start from here.')
START.add_paths({'shoot!': generic_death})
START.add_paths({'dodge!': generic_death})
START.add_paths({'tell a joke': laser_weapon_armory})
START.add_paths({'im your father': the_bridge})
START.add_paths({'finished': finished})
START.add_paths({'': generic_death})
START.add_paths({'throw the bomb': generic_death})
START.add_paths({'success': success})

****************************************
2. 运行主程序“app.py”:
# -*- coding: utf-8 -*-
import web
from gothonweb.map import *

urls = (
    '/game', 'GameEngine',
    '/', 'Index'
)

app = web.application(urls, globals())
render = web.template.render("templates/", base = 'layout')

# 检测本地是否有缓存
if web.config.get("_session") is None:
    # 缓存为空,本地新建sessions文件夹用于存放缓存数据
    store = web.session.DiskStore("sessions")
    session = web.session.Session(app, store, initializer={'room': None})

    web.config._session = session
#有缓存则直接使用
else:
    session = web.config._session


# 此类的作用是初始化session
class Index(object):

    def GET(self):
        print "Index GET start"
        session.room = START
        # return render.show_room1(room = room)
        # seeother方法是默认GET
        web.seeother("/game")


class GameEngine(object):
    def GET(self):
        print "GameEngine GET start"
        # 渲染的html文件需要返回
        if session.room:
            return render.show_room1(room = session.room)
        else:
            return render.you_died1()

    def POST(self):
        print "GameEngine POST start"
        # input入参对应input函数的'name'参数
        form = web.input(action = None)
        if form.action and session.room:
            print "sessiong参数 %r" % session.room
            # seeother不需要返回值
            session.room = session.room.go(form.action)
            web.seeother('/game')

if __name__ == "__main__":
    app.run()


****************************************
3. show.html文件:

$def with (room)

<h1> $room.name </h1>

<pre>
  $room.description
</pre>

$if room.name == "death":
  <h1>You have died!</h1>
  <p><a href="/">Try Again</a></p>
$else:
  <p>
    <form action="/game" method="POST">
          <input type="text" name="action"/></br><input type="SUBMIT"/>
    </form>
  </p>



****************************************
4. you_died1.html文件:

<h1>You have died!</h1>


<a href="/">Try it Again!</a>

转载于:https://my.oschina.net/lengwei/blog/813712

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值