我已经将Flask-User 1.0连接到我的Mongodb上了一个基本的Web应用程序。并进行注册和登录工作。但是,一旦登录的用户进入了member_page,我希望能够在客户端和服务器之间发送和接收信息。自从我曾经使用过socket.io,就计划使用它。但是我现在知道如何获取有关当前用户的信息。我将为登录用户制作一个日历。用户可以添加和编辑自己的日历。但是目前我无法找到当前用户,因此不知道谁的信息会发回给用户,如果用户在日历中添加了某些内容,情况也是如此。
如果我打印会话,我会得到很多信息。但是我不知道如何提取当前用户的用户名。
<SecureCookieSession {'_fresh': True, '_id': 'ea37d60dd399bf244b53b5fc2b00629d11e3f0b844cbaaaa8902ad00b920133e1b4ea777d2af9492d4feffc81f9500d7e5889bd04a804c75e91e939b97fcfd22', '_permanent': True, 'csrf_token': 'e5040f2814ebf30f563635bbff459158fdd36bef', 'user_id': 'gAAAAABblr9Y80DfmIY66WOcUe5rYE6EjGgAHd5gMeH9Cst91VYKEvtYq14vAPqdgU5lzkb5ELJZrzWWg9mE2oN4_U3PsZeiHWW5iV7VWVh952WKlYEKn3SnMA0aEnOW0zSl47qqKqwB'}>
任何帮助或指导将不胜感激。
from flask import Flask, render_template_string, session
from flask_mongoengine import MongoEngine
from flask_user import login_required, UserManager, UserMixin
# Class-based application configuration
class ConfigClass(object):
""" Flask application config """
# Flask settings
SECRET_KEY = 'This is an INSECURE secret!! DO NOT use this in production!!'
# Flask-MongoEngine settings
MONGODB_SETTINGS = {
'db': 'tst_app',
'host': 'mongodb://localhost:33420/website'
}
# Flask-User settings
USER_APP_NAME = "Flask-User MongoDB App" # Shown in and email templates and page footers
USER_ENABLE_EMAIL = False # Disable email authentication
USER_ENABLE_USERNAME = True # Enable username authentication
USER_REQUIRE_RETYPE_PASSWORD = False # Simplify register form
def create_app():
""" Flask application factory """
# Setup Flask and load app.config
app = Flask(__name__)
app.config.from_object(__name__ + '.ConfigClass')
# Setup Flask-MongoEngine
db = MongoEngine(app)
# Define the User document.
# NB: Make sure to add flask_user UserMixin !!!
class User(db.Document, UserMixin):
active = db.BooleanField(default=True)
# User authentication information
username = db.StringField(default='')
password = db.StringField()
# User information
first_name = db.StringField(default='')
last_name = db.StringField(default='')
# Relationships
roles = db.ListField(db.StringField(), default=[])
# Setup Flask-User and specify the User data-model
user_manager = UserManager(app, db, User)
# The Home page is accessible to anyone
@app.route('/')
def home_page():
# String-based templates
return render_template_string("""
{% extends "flask_user_layout.html" %}
{% block content %}
<h2>Home page</h2>
<p><a href={{ url_for('user.register') }}>Register</a></p>
<p><a href={{ url_for('user.login') }}>Sign in</a></p>
<p><a href={{ url_for('home_page') }}>Home page</a> (accessible to anyone)</p>
<p><a href={{ url_for('member_page') }}>Member page</a> (login required)</p>
<p><a href={{ url_for('user.logout') }}>Sign out</a></p>
{% endblock %}
""")
# The Members page is only accessible to authenticated users via the @login_required decorator
@app.route('/members')
@login_required # User must be authenticated
def member_page():
# String-based templates
return render_template_string("""
{% extends "flask_user_layout.html" %}
{% block content %}
<h2>Members page</h2>
<p><a href={{ url_for('user.register') }}>Register</a></p>
<p><a href={{ url_for('user.login') }}>Sign in</a></p>
<p><a href={{ url_for('home_page') }}>Home page</a> (accessible to anyone)</p>
<p><a href={{ url_for('member_page') }}>Member page</a> (login required)</p>
<p><a href={{ url_for('user.logout') }}>Sign out</a></p>
{% endblock %}
""")
return app
# Start development web server
if __name__ == '__main__':
app = create_app()
app.run(host='0.0.0.0', port=5000, debug=True)
将来为所有人提供的解决方案
我在user_mixin.py中添加了以下代码:
@classmethod
def get_user_id_by_token(cls, token, expiration_in_seconds=None):
# This function works in tandem with UserMixin.get_id()
# Token signatures and timestamps are verified.
# user_id and password_ends_with are decrypted.
# Verifies a token and decrypts a User ID and parts of a User password hash
user_manager = current_app.user_manager
data_items = user_manager.verify_token(token, expiration_in_seconds)
# Verify password_ends_with
token_is_valid = False
if data_items:
# Load user by User ID
user_id = data_items[0]
password_ends_with = data_items[1]
user = user_manager.db_manager.get_user_by_id(user_id)
user_password = '' if user_manager.USER_ENABLE_AUTH0 else user.password[-8:]
# Make sure that last 8 characters of user password matches
token_is_valid = user and user_password==password_ends_with
return user_id if token_is_valid else None
我现在可以调用我的函数,并且将返回user_id
user_id = UserMixin.get_user_id_by_token(session['user_id'])