从HTML代码中的脚本访问变量?

时间:2013-08-29 04:29:11

标签: python template-engine bottle

我正在使用Bottle框架(也使用Beaker进行会话)用于Python,并且无法从HTML代码中的脚本访问变量。以下是Python脚本:

import os, MySQLdb, hashlib, random, markdown2
import beaker.middleware
import bottle
from bottle import run, route, post, get, request, abort, template, hook, app, view

@post('/submit')
def submit():
    db = MySQLdb.connect(host='localhost', port=3306, user="root", passwd="blkFDF94alkf", db="_pCMS")
    query = db.cursor()

    user = request.forms.get('credentials.username')
    username = MySQLdb.escape_string(user)
    request.session['username'] = username
    passw = request.forms.get('credentials.password')
    pass_w = MySQLdb.escape_string(passw)
    passw2 = str(pass_w)
    password = hashlib.md5(passw2).hexdigest()
    user_name = request.session['username']


    if username >= 2 and password >= 6:
        if True:
            ugh = query.execute("SELECT * FROM users WHERE username = '%s' AND password = '%s'" % (username, password))
            db.commit()
            return me()
    else:
        return index()

我怀疑上面的代码需要解释,因为我需要知道的是如何在下面的HTML代码中访问该Python脚本的该函数中的变量user_name。这就是我对HTML的看法:

me.tpl:

<div class="label">Name:</div>
    %if len(user_name) >= 2:
        <div class="content">{{user_name}}</div>
    %end
</div>

这是访问变量user_name的正确方法吗?它不是那样工作的,因为它给了我以下错误:

NameError: name 'user_name' is not defined

me()和index()做什么:

@route('/')
@route('/index')
@view('index.tpl')
def index():
    index = { 'index' : _index()}
    return index

def _index():
    return 't'


@get('/me')
@view('me.tpl')
def me():
    me = { 'me' : _me()}
    return me

def _me():
    return 't'

1 个答案:

答案 0 :(得分:0)

您的me视图应采用user_name参数并将其注入模板中:

@get('/me')
@view('me.tpl')
def me(user_name):
    me = { 
        'me': _me(),
        'user_name': user_name
    }
    return me