Commits

Ning Sun committed 28d3ebb

initial commit

  • Participants

Comments (0)

Files changed (7)

+syntax: glob
+*.pyc
+build
+userapp/tmp

cityapp/cityapp.py

+import sys
+reload(sys)
+sys.setdefaultencoding('utf8')
+from bottle import Bottle, mako_view, request, debug, redirect
+from pymongo import Connection
+import random
+debug(True)
+
+dbconn = Connection('localhost')
+MAX_CITIES = dbconn.geo.cities15000.count()
+
+cityapp = Bottle()
+
+def get_nearby(c):
+    cs = dbconn.geo.cities15000.find({'location':{'$near':[c['location'][0], c['location'][1]]}})skip(1).limit(5)
+    return list(cs)
+
+@cityapp.get('/')
+@mako_view('index', encoding='utf8')
+def index():
+    cityid = random.randint(0, MAX_CITIES)
+    c = dbconn.geo.cities15000.find().skip(cityid).limit(1)[0]
+    nearby = get_nearby(c)
+    return dict(city=c, nearby=nearby)
+
+@cityapp.get('/:name')
+@mako_view('index', encoding="utf8")
+def city(name):
+    """docstring for city"""
+    cur = dbconn.geo.cities15000.find({'asciiname':name})
+    try:
+        c = cur[0]
+        nearby = get_nearby(c)
+        return dict(city=c, nearby=nearby)
+    except:
+        redirect('/')
+

cityapp/index.tpl

+<html>
+<head>
+    <meta http-equiv="content-type" content="text/html; charset=utf-8"0>
+
+    <title>${city['name']}</title>
+    
+</head>
+<body>
+    <h1 id="heading">${city['name']}</h1>
+    <p><a href="/${city['asciiname']}">${city['asciiname']}</a>, ${city['countrycode']}</p>
+    <p>TZ: ${city['timezone']}</p>
+    <p><img src="http://maps.google.com/maps/api/staticmap?center=${city['location'][0]},${city['location'][1]}&zoom=10&size=300x300&maptype=terrain&sensor=false" alt="${city['location'][0]}, ${city['location'][1]}" title="${city['location'][0]}, ${city['location'][1]}"/></p>
+    <p>Population: ${city['population']}</p>
+    <p>
+    %for nc in nearby:
+        <a href="/${nc['asciiname']}">${nc['asciiname']}</a>
+    %endfor
+    </p>
+
+</body>
+</html>
+from fabric.api import *
+
+env.hosts = ['sunng@sunng.info']
+
+tarball='cityapp.tar.gz'
+
+def package():
+    local('rm -f cityapp/*.pyc')
+    local('rm -r build')
+    local('mkdir build')
+    local('tar cfz build/%s cityapp' % tarball)
+    
+def upload():
+    put('build/%s'%tarball, 'apps/')
+
+def deploy():
+    with cd('apps'):
+        run('rm -rf cityapp/')
+        run('tar xfz %s'%tarball)
+
+def dodeploy():
+    package()
+    upload()
+    deploy()
+

userapp/index.tpl

+<html>
+<head>
+    <meta http-equiv="content-type" content="text/html; charset=utf-8"0>
+
+    <title>Login</title>
+    
+</head>
+<body>
+    <h1>Chrino</h1>
+    <p>There are ${c} users in the Chrino world.<p>
+    %if u is not None:
+        <h2>${u['name']}</h2>
+        <p>Welcome back sir! ${u['camp']} army is ready for your command!</p>
+        <p><a href="/logout">logout</a></p>
+    %else:
+    <form action="/login_submit" method="post" accept-charset="utf-8">
+        
+    <p>OpenID PassURL: <input type="text" name="openid" value=""></p> 
+    
+    <p><input type="submit" value="Login"></p>
+    </form>
+    % endif
+</body>
+</html>

userapp/login_callback.tpl

+<html>
+<head>
+    <meta http-equiv="content-type" content="text/html; charset=utf-8"0>
+
+    <title>Chrino</title>
+    
+</head>
+<body>
+    <h1>Chrino</h1>
+    %if r:
+        Conguratulations ! Welcome come to Chrino world. ${i} 
+        <h2>Reg</h2>
+        <form action="reg_save" method="post" accept-charset="utf-8">
+             <input type="hidden" name="openid" value="${i}" />
+            <p>Email: <input type="text" name="email" value="" /></p>
+            <p>Nick: <input type="text" name="name" value="" /></p>
+            <p>Camp: 
+                <select name="camp" id="camp">
+                    <option value="China">China</option>
+                    <option value="Soviet">Soviet</option>
+                    <option value="USA">USA</option>
+                    <option value="Europe">Europe</option>
+                </select></p>
+        
+        <p><input type="submit" value="Continue &rarr;"/></p>
+        </form>
+    %else:
+        Openid login failed. sorry.
+    %endif
+</body>
+</html>

userapp/userapp.py

+import cgi
+import time
+from bottle import Bottle, request, redirect, debug, mako_view, redirect, run
+from openid.consumer import consumer
+from openid.store import filestore
+from pymongo import Connection as mongo
+from beaker.middleware import SessionMiddleware
+
+
+debug()
+m = mongo('localhost')
+userapp = Bottle()
+
+@userapp.get('/')
+@mako_view('index')
+def index():
+    count = m.chrino.users.count()
+    session = request.environ.get('beaker.session')
+    if 'opid' in session:
+        opid = session['opid']
+        user = m.chrino.users.find({'openid':opid}).next()
+    else :
+        user = None
+    return dict(c=count, u=user)
+
+@userapp.post('/login_submit')
+def submit_login():
+    oid_url = request.POST['openid']
+
+    opid_consumer = consumer.Consumer({}, None)
+
+    try:
+        opidreq = opid_consumer.begin(oid_url)
+    except consumer.DiscoveryFailure:
+        return "failed to discovery"
+    else:
+        if opidreq is None:
+            return "no such openid service"
+        else:
+            trust_root = 'http://localhost:8080'
+            return_url = "http://localhost:8080/login_callback"
+            if opidreq.shouldSendRedirect():
+                redirect_url = opidreq.redirectURL(trust_root, return_url, immediate=True)
+                redirect(redirect_url)
+            else:
+                return opidreq.htmlMarkup(trust_root, return_url)
+
+@userapp.get('/login_callback')
+@mako_view('login_callback')
+def login_callback():
+    opid_consumer = consumer.Consumer({}, None)
+ 
+    url = 'http://'+request.header.get('host')+"/login_callback"
+    info = opid_consumer.complete(request.GET, url)
+ 
+    if info.status == consumer.SUCCESS:
+        i = cgi.escape(info.getDisplayIdentifier())
+        user = list(m.chrino.users.find({'openid':i}).limit(1))
+        if len(user) > 0:
+            session = request.environ.get('beaker.session')
+            session['opid'] = user[0]['openid']
+            redirect('/')
+        else:
+            return dict(i=i,r=True)
+
+    else:
+        return dict(r=False)
+        
+@userapp.post('/reg_save')
+def save_reg():
+    email = request.POST.get('email')
+    openid = request.POST.get('openid')
+    name = request.POST.get('name')
+    camp = request.POST.get('camp')
+    create_time = int(time.time())
+    d = dict(email=email, openid=openid, camp=camp, name=name, create_time=create_time)
+    m.chrino.users.save(d)
+    session = request.environ.get('beaker.session')
+    session['opid'] = openid
+    redirect('/')
+
+@userapp.get('/logout')
+def logout():
+    session = request.environ.get('beaker.session')
+    session.delete()
+    redirect('/')
+    
+session_opts = {
+    'session.type':'memory',
+    'session.cookie_expires': True,
+    'session.auto': True,
+#    'session.data_dir':'tmp/data',
+#   'session.lock_dir':'tmp/lock'
+}
+userapp = SessionMiddleware(userapp, session_opts)
+run(userapp)