Get current user id in Flask

2019-07-10 00:46发布

问题:

I'm quite new to Python (and, to be honest, programming in general). I'm currently working on a kind of to-do list, where I need it to put to-do items into appropriate course (it's all related to educational stuff). So, the problem is quite straight-forward. I have this as a Flask-driven route:

@app.route('/add_course', methods=('GET', 'POST'))
@login_required
def course():
    form = forms.CourseForm()
    if form.validate_on_submit():
        models.Course.create(teacher=g.user._get_current_object(),
                             name=form.name.data.strip(),
                             difficulty=form.level.data.strip(),
                             description=form.description.data.strip())
        flash("Course successfully created!", "success")
        return redirect(url_for('index'))
    return render_template('add_course.html', form=form)

Then I have this in forms.py. You can see the clever mark that I have put to indicate where my problem is. It says THE_PROBLEM

def courses():
    try:
        courses = models.Course.select(models.Course.id,
                                   models.Course.name,
                                   models.Course.difficulty).where(THE_PROBLEM)
        course_list = []
        for course in courses:
            course_list.append((str(course.id), course.name + ' - ' + course.difficulty.title()))
        return course_list
    except models.DoesNotExist:
        return [('', 'No courses')]


class ToDoForm(FlaskForm):
    name = StringField("What's up?", validators=[
    DataRequired()
    ])
    due_date = DateTimeField('When?', format='%Y-%m-%d %H-%M')
    course = SelectField('Course', choices=courses())
    priority = SelectField('Priority',
                           choices=[('high', 'High priority'),
                                    ('medium', 'Normal priority'),
                                    ('low', 'Low priority')],
                           validators=[
                               DataRequired()
                           ])
    description = TextAreaField('Description')

So, yeah, what I am looking for is the way to pass the id of the owner (teacher in this very case) who is currently logged in. I use this function courses() to build a list of tuples for the choices attribute of the field course in ToDoForm. I need to pass the id of currently logged-in teacher into this function, so that it can evaluate if this passed teacher has any courses that match his id. I tried to use current_user._get_current_object() and whatever else, but it just caused me tons of errors.

Any help, advice or suggestion will be appreciated. I really hope that what I say here (and what I want to achieve) is understandable

回答1:

In case anybody runs into the same frustrating problem, the solution is quite straightforward. Wrap up external classes into functions and pass required variables as arguments, then use them to your heart's content. Just don't forget to return an instance of the class.