我正在使用here中的代码使用Steam登录我的网站。我需要在身份验证后获取用户的用户名。我在html模板中有什么:
{% if g.user is defined and g.user is not none %}
{# User has logged in #}
<li>Hello, {{ g.user.nickname }}!</li>
<li><a href="/logout">Logout</a></li>
{% else %}
{# User has not logged in #}
<li><a href="/login"><input type="image" name="SignIn" value="SignIn" src="static/steam.png"/></a></li>
{% endif %}
但是这会返回VARCHAR(80)而不是用户名。我的错是什么?
修改即可。以下是我提到的示例中的代码:
from flask import Flask, render_template, redirect, session, json, g, flash
from flask_bootstrap import Bootstrap
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.openid import OpenID
import urllib
import re
app = Flask(__name__)
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
Bootstrap(app)
app.config.from_pyfile('settings.cfg')
db = SQLAlchemy(app)
oid = OpenID(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
steam_id = db.Column(db.String(40))
nickname = db.String(80)
@staticmethod
def get_or_create(steam_id):
rv = User.query.filter_by(steam_id=steam_id).first()
if rv is None:
rv = User()
rv.steam_id = steam_id
db.session.add(rv)
return rv
db.create_all()
def get_steam_userinfo(steam_id):
options = {
'key': app.config['STEAM_API_KEY'],
'steamids': steam_id
}
url = 'http://api.steampowered.com/ISteamUser/' \
'GetPlayerSummaries/v0001/?%s' % urllib.urlencode(options)
rv = json.load(urllib.urlopen(url))
return rv['response']['players']['player'][0] or {}
_steam_id_re = re.compile('steamcommunity.com/openid/id/(.*?)$')
@app.route('/login')
@oid.loginhandler
def login():
if g.user is not None:
return redirect(oid.get_next_url())
return oid.try_login('http://steamcommunity.com/openid')
@oid.after_login
def create_or_login(resp):
match = _steam_id_re.search(resp.identity_url)
g.user = User.get_or_create(match.group(1))
steamdata = get_steam_userinfo(g.user.steam_id)
g.user.nickname = steamdata['personaname']
db.session.commit()
session['user_id'] = g.user.id
return redirect(oid.get_next_url())
@app.before_request
def before_request():
g.user = None
if 'user_id' in session:
g.user = User.query.get(session['user_id'])
@app.route('/')
def homepage():
return render_template('mainpage.html')
@app.route('/logout')
def logout():
session.pop('user_id', None)
return redirect(oid.get_next_url())
if __name__ == '__main__':
app.run(debug=True)
答案 0 :(得分:1)
您没有将User.nickname
定义为列,您只是为其分配了一个SQL类型。将其更改为具有该类型的列。
nickname = db.Column(db.String)